code
stringlengths
501
4.91M
package
stringlengths
2
88
path
stringlengths
11
291
filename
stringlengths
4
197
parsed_code
stringlengths
0
4.91M
quality_prob
float64
0
0.99
learning_prob
float64
0.02
1
import datetime from typing import Dict, List, Optional, TYPE_CHECKING, Union from .. import _serialization if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from .. import models as _models class Resource(_serialization.Model): """Common fields that are returned in the response for all Azure Resource Manager resources. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. :vartype id: str :ivar name: The name of the resource. :vartype name: str :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts". :vartype type: str """ _validation = { "id": {"readonly": True}, "name": {"readonly": True}, "type": {"readonly": True}, } _attribute_map = { "id": {"key": "id", "type": "str"}, "name": {"key": "name", "type": "str"}, "type": {"key": "type", "type": "str"}, } def __init__(self, **kwargs): """ """ super().__init__(**kwargs) self.id = None self.name = None self.type = None class TrackedResource(Resource): """The resource model definition for an Azure Resource Manager tracked top level resource which has 'tags' and a 'location'. Variables are only populated by the server, and will be ignored when sending a request. All required parameters must be populated in order to send to Azure. :ivar id: Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. :vartype id: str :ivar name: The name of the resource. :vartype name: str :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts". :vartype type: str :ivar tags: Resource tags. :vartype tags: dict[str, str] :ivar location: The geo-location where the resource lives. Required. :vartype location: str """ _validation = { "id": {"readonly": True}, "name": {"readonly": True}, "type": {"readonly": True}, "location": {"required": True}, } _attribute_map = { "id": {"key": "id", "type": "str"}, "name": {"key": "name", "type": "str"}, "type": {"key": "type", "type": "str"}, "tags": {"key": "tags", "type": "{str}"}, "location": {"key": "location", "type": "str"}, } def __init__(self, *, location: str, tags: Optional[Dict[str, str]] = None, **kwargs): """ :keyword tags: Resource tags. :paramtype tags: dict[str, str] :keyword location: The geo-location where the resource lives. Required. :paramtype location: str """ super().__init__(**kwargs) self.tags = tags self.location = location class AzureBareMetalInstance(TrackedResource): # pylint: disable=too-many-instance-attributes """AzureBareMetal instance info on Azure (ARM properties and AzureBareMetal properties). Variables are only populated by the server, and will be ignored when sending a request. All required parameters must be populated in order to send to Azure. :ivar id: Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. :vartype id: str :ivar name: The name of the resource. :vartype name: str :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts". :vartype type: str :ivar tags: Resource tags. :vartype tags: dict[str, str] :ivar location: The geo-location where the resource lives. Required. :vartype location: str :ivar system_data: The system metadata relating to this resource. :vartype system_data: ~azure.mgmt.baremetalinfrastructure.models.SystemData :ivar hardware_profile: Specifies the hardware settings for the AzureBareMetal instance. :vartype hardware_profile: ~azure.mgmt.baremetalinfrastructure.models.HardwareProfile :ivar storage_profile: Specifies the storage settings for the AzureBareMetal instance disks. :vartype storage_profile: ~azure.mgmt.baremetalinfrastructure.models.StorageProfile :ivar os_profile: Specifies the operating system settings for the AzureBareMetal instance. :vartype os_profile: ~azure.mgmt.baremetalinfrastructure.models.OSProfile :ivar network_profile: Specifies the network settings for the AzureBareMetal instance. :vartype network_profile: ~azure.mgmt.baremetalinfrastructure.models.NetworkProfile :ivar azure_bare_metal_instance_id: Specifies the AzureBareMetal instance unique ID. :vartype azure_bare_metal_instance_id: str :ivar power_state: Resource power state. Known values are: "starting", "started", "stopping", "stopped", "restarting", and "unknown". :vartype power_state: str or ~azure.mgmt.baremetalinfrastructure.models.AzureBareMetalInstancePowerStateEnum :ivar proximity_placement_group: Resource proximity placement group. :vartype proximity_placement_group: str :ivar hw_revision: Hardware revision of an AzureBareMetal instance. :vartype hw_revision: str :ivar partner_node_id: ARM ID of another AzureBareMetalInstance that will share a network with this AzureBareMetalInstance. :vartype partner_node_id: str :ivar provisioning_state: State of provisioning of the AzureBareMetalInstance. Known values are: "Accepted", "Creating", "Updating", "Failed", "Succeeded", "Deleting", and "Migrating". :vartype provisioning_state: str or ~azure.mgmt.baremetalinfrastructure.models.AzureBareMetalProvisioningStatesEnum """ _validation = { "id": {"readonly": True}, "name": {"readonly": True}, "type": {"readonly": True}, "location": {"required": True}, "system_data": {"readonly": True}, "azure_bare_metal_instance_id": {"readonly": True}, "power_state": {"readonly": True}, "proximity_placement_group": {"readonly": True}, "hw_revision": {"readonly": True}, "provisioning_state": {"readonly": True}, } _attribute_map = { "id": {"key": "id", "type": "str"}, "name": {"key": "name", "type": "str"}, "type": {"key": "type", "type": "str"}, "tags": {"key": "tags", "type": "{str}"}, "location": {"key": "location", "type": "str"}, "system_data": {"key": "systemData", "type": "SystemData"}, "hardware_profile": {"key": "properties.hardwareProfile", "type": "HardwareProfile"}, "storage_profile": {"key": "properties.storageProfile", "type": "StorageProfile"}, "os_profile": {"key": "properties.osProfile", "type": "OSProfile"}, "network_profile": {"key": "properties.networkProfile", "type": "NetworkProfile"}, "azure_bare_metal_instance_id": {"key": "properties.azureBareMetalInstanceId", "type": "str"}, "power_state": {"key": "properties.powerState", "type": "str"}, "proximity_placement_group": {"key": "properties.proximityPlacementGroup", "type": "str"}, "hw_revision": {"key": "properties.hwRevision", "type": "str"}, "partner_node_id": {"key": "properties.partnerNodeId", "type": "str"}, "provisioning_state": {"key": "properties.provisioningState", "type": "str"}, } def __init__( self, *, location: str, tags: Optional[Dict[str, str]] = None, hardware_profile: Optional["_models.HardwareProfile"] = None, storage_profile: Optional["_models.StorageProfile"] = None, os_profile: Optional["_models.OSProfile"] = None, network_profile: Optional["_models.NetworkProfile"] = None, partner_node_id: Optional[str] = None, **kwargs ): """ :keyword tags: Resource tags. :paramtype tags: dict[str, str] :keyword location: The geo-location where the resource lives. Required. :paramtype location: str :keyword hardware_profile: Specifies the hardware settings for the AzureBareMetal instance. :paramtype hardware_profile: ~azure.mgmt.baremetalinfrastructure.models.HardwareProfile :keyword storage_profile: Specifies the storage settings for the AzureBareMetal instance disks. :paramtype storage_profile: ~azure.mgmt.baremetalinfrastructure.models.StorageProfile :keyword os_profile: Specifies the operating system settings for the AzureBareMetal instance. :paramtype os_profile: ~azure.mgmt.baremetalinfrastructure.models.OSProfile :keyword network_profile: Specifies the network settings for the AzureBareMetal instance. :paramtype network_profile: ~azure.mgmt.baremetalinfrastructure.models.NetworkProfile :keyword partner_node_id: ARM ID of another AzureBareMetalInstance that will share a network with this AzureBareMetalInstance. :paramtype partner_node_id: str """ super().__init__(tags=tags, location=location, **kwargs) self.system_data = None self.hardware_profile = hardware_profile self.storage_profile = storage_profile self.os_profile = os_profile self.network_profile = network_profile self.azure_bare_metal_instance_id = None self.power_state = None self.proximity_placement_group = None self.hw_revision = None self.partner_node_id = partner_node_id self.provisioning_state = None class AzureBareMetalInstancesListResult(_serialization.Model): """The response from the List AzureBareMetal Instances operation. :ivar value: The list of Azure BareMetal instances. :vartype value: list[~azure.mgmt.baremetalinfrastructure.models.AzureBareMetalInstance] :ivar next_link: The URL to get the next set of AzureBareMetal instances. :vartype next_link: str """ _attribute_map = { "value": {"key": "value", "type": "[AzureBareMetalInstance]"}, "next_link": {"key": "nextLink", "type": "str"}, } def __init__( self, *, value: Optional[List["_models.AzureBareMetalInstance"]] = None, next_link: Optional[str] = None, **kwargs ): """ :keyword value: The list of Azure BareMetal instances. :paramtype value: list[~azure.mgmt.baremetalinfrastructure.models.AzureBareMetalInstance] :keyword next_link: The URL to get the next set of AzureBareMetal instances. :paramtype next_link: str """ super().__init__(**kwargs) self.value = value self.next_link = next_link class Disk(_serialization.Model): """Specifies the disk information fo the AzureBareMetal instance. Variables are only populated by the server, and will be ignored when sending a request. :ivar name: The disk name. :vartype name: str :ivar disk_size_gb: Specifies the size of an empty data disk in gigabytes. :vartype disk_size_gb: int :ivar lun: Specifies the logical unit number of the data disk. This value is used to identify data disks within the VM and therefore must be unique for each data disk attached to a VM. :vartype lun: int """ _validation = { "lun": {"readonly": True}, } _attribute_map = { "name": {"key": "name", "type": "str"}, "disk_size_gb": {"key": "diskSizeGB", "type": "int"}, "lun": {"key": "lun", "type": "int"}, } def __init__(self, *, name: Optional[str] = None, disk_size_gb: Optional[int] = None, **kwargs): """ :keyword name: The disk name. :paramtype name: str :keyword disk_size_gb: Specifies the size of an empty data disk in gigabytes. :paramtype disk_size_gb: int """ super().__init__(**kwargs) self.name = name self.disk_size_gb = disk_size_gb self.lun = None class Display(_serialization.Model): """Detailed BareMetal operation information. Variables are only populated by the server, and will be ignored when sending a request. :ivar provider: The localized friendly form of the resource provider name. :vartype provider: str :ivar resource: The localized friendly form of the resource type related to this action/operation. :vartype resource: str :ivar operation: The localized friendly name for the operation as shown to the user. :vartype operation: str :ivar description: The localized friendly description for the operation as shown to the user. :vartype description: str """ _validation = { "provider": {"readonly": True}, "resource": {"readonly": True}, "operation": {"readonly": True}, "description": {"readonly": True}, } _attribute_map = { "provider": {"key": "provider", "type": "str"}, "resource": {"key": "resource", "type": "str"}, "operation": {"key": "operation", "type": "str"}, "description": {"key": "description", "type": "str"}, } def __init__(self, **kwargs): """ """ super().__init__(**kwargs) self.provider = None self.resource = None self.operation = None self.description = None class ErrorDefinition(_serialization.Model): """Error definition. Variables are only populated by the server, and will be ignored when sending a request. :ivar code: Service specific error code which serves as the substatus for the HTTP error code. :vartype code: str :ivar message: Description of the error. :vartype message: str :ivar details: Internal error details. :vartype details: list[~azure.mgmt.baremetalinfrastructure.models.ErrorDefinition] """ _validation = { "code": {"readonly": True}, "message": {"readonly": True}, "details": {"readonly": True}, } _attribute_map = { "code": {"key": "code", "type": "str"}, "message": {"key": "message", "type": "str"}, "details": {"key": "details", "type": "[ErrorDefinition]"}, } def __init__(self, **kwargs): """ """ super().__init__(**kwargs) self.code = None self.message = None self.details = None class ErrorResponse(_serialization.Model): """Error response. :ivar error: The error details. :vartype error: ~azure.mgmt.baremetalinfrastructure.models.ErrorDefinition """ _attribute_map = { "error": {"key": "error", "type": "ErrorDefinition"}, } def __init__(self, *, error: Optional["_models.ErrorDefinition"] = None, **kwargs): """ :keyword error: The error details. :paramtype error: ~azure.mgmt.baremetalinfrastructure.models.ErrorDefinition """ super().__init__(**kwargs) self.error = error class HardwareProfile(_serialization.Model): """Specifies the hardware settings for the AzureBareMetal instance. Variables are only populated by the server, and will be ignored when sending a request. :ivar hardware_type: Name of the hardware type (vendor and/or their product name). Known values are: "Cisco_UCS" and "HPE". :vartype hardware_type: str or ~azure.mgmt.baremetalinfrastructure.models.AzureBareMetalHardwareTypeNamesEnum :ivar azure_bare_metal_instance_size: Specifies the AzureBareMetal instance SKU. Known values are: "S72m", "S144m", "S72", "S144", "S192", "S192m", "S192xm", "S96", "S112", "S224", "S224m", "S224om", "S224oo", "S224oom", "S224ooo", "S384", "S384m", "S384xm", "S384xxm", "S448", "S448m", "S448om", "S448oo", "S448oom", "S448ooo", "S576m", "S576xm", "S672", "S672m", "S672om", "S672oo", "S672oom", "S672ooo", "S768", "S768m", "S768xm", "S896", "S896m", "S896om", "S896oo", "S896oom", "S896ooo", and "S960m". :vartype azure_bare_metal_instance_size: str or ~azure.mgmt.baremetalinfrastructure.models.AzureBareMetalInstanceSizeNamesEnum """ _validation = { "hardware_type": {"readonly": True}, "azure_bare_metal_instance_size": {"readonly": True}, } _attribute_map = { "hardware_type": {"key": "hardwareType", "type": "str"}, "azure_bare_metal_instance_size": {"key": "azureBareMetalInstanceSize", "type": "str"}, } def __init__(self, **kwargs): """ """ super().__init__(**kwargs) self.hardware_type = None self.azure_bare_metal_instance_size = None class IpAddress(_serialization.Model): """Specifies the IP address of the network interface. :ivar ip_address: Specifies the IP address of the network interface. :vartype ip_address: str """ _attribute_map = { "ip_address": {"key": "ipAddress", "type": "str"}, } def __init__(self, *, ip_address: Optional[str] = None, **kwargs): """ :keyword ip_address: Specifies the IP address of the network interface. :paramtype ip_address: str """ super().__init__(**kwargs) self.ip_address = ip_address class NetworkProfile(_serialization.Model): """Specifies the network settings for the AzureBareMetal instance disks. Variables are only populated by the server, and will be ignored when sending a request. :ivar network_interfaces: Specifies the network interfaces for the AzureBareMetal instance. :vartype network_interfaces: list[~azure.mgmt.baremetalinfrastructure.models.IpAddress] :ivar circuit_id: Specifies the circuit id for connecting to express route. :vartype circuit_id: str """ _validation = { "circuit_id": {"readonly": True}, } _attribute_map = { "network_interfaces": {"key": "networkInterfaces", "type": "[IpAddress]"}, "circuit_id": {"key": "circuitId", "type": "str"}, } def __init__(self, *, network_interfaces: Optional[List["_models.IpAddress"]] = None, **kwargs): """ :keyword network_interfaces: Specifies the network interfaces for the AzureBareMetal instance. :paramtype network_interfaces: list[~azure.mgmt.baremetalinfrastructure.models.IpAddress] """ super().__init__(**kwargs) self.network_interfaces = network_interfaces self.circuit_id = None class Operation(_serialization.Model): """AzureBareMetal operation information. Variables are only populated by the server, and will be ignored when sending a request. :ivar name: The name of the operation being performed on this particular object. This name should match the action name that appears in RBAC / the event service. :vartype name: str :ivar display: Displayed AzureBareMetal operation information. :vartype display: ~azure.mgmt.baremetalinfrastructure.models.Display :ivar is_data_action: indicates whether an operation is a data action or not. :vartype is_data_action: bool """ _validation = { "name": {"readonly": True}, "is_data_action": {"readonly": True}, } _attribute_map = { "name": {"key": "name", "type": "str"}, "display": {"key": "display", "type": "Display"}, "is_data_action": {"key": "isDataAction", "type": "bool"}, } def __init__(self, *, display: Optional["_models.Display"] = None, **kwargs): """ :keyword display: Displayed AzureBareMetal operation information. :paramtype display: ~azure.mgmt.baremetalinfrastructure.models.Display """ super().__init__(**kwargs) self.name = None self.display = display self.is_data_action = None class OperationList(_serialization.Model): """List of AzureBareMetal operations. :ivar value: List of AzureBareMetal operations. :vartype value: list[~azure.mgmt.baremetalinfrastructure.models.Operation] """ _attribute_map = { "value": {"key": "value", "type": "[Operation]"}, } def __init__(self, *, value: Optional[List["_models.Operation"]] = None, **kwargs): """ :keyword value: List of AzureBareMetal operations. :paramtype value: list[~azure.mgmt.baremetalinfrastructure.models.Operation] """ super().__init__(**kwargs) self.value = value class OSProfile(_serialization.Model): """Specifies the operating system settings for the AzureBareMetal instance. Variables are only populated by the server, and will be ignored when sending a request. :ivar computer_name: Specifies the host OS name of the AzureBareMetal instance. :vartype computer_name: str :ivar os_type: This property allows you to specify the type of the OS. :vartype os_type: str :ivar version: Specifies version of operating system. :vartype version: str :ivar ssh_public_key: Specifies the SSH public key used to access the operating system. :vartype ssh_public_key: str """ _validation = { "os_type": {"readonly": True}, "version": {"readonly": True}, } _attribute_map = { "computer_name": {"key": "computerName", "type": "str"}, "os_type": {"key": "osType", "type": "str"}, "version": {"key": "version", "type": "str"}, "ssh_public_key": {"key": "sshPublicKey", "type": "str"}, } def __init__(self, *, computer_name: Optional[str] = None, ssh_public_key: Optional[str] = None, **kwargs): """ :keyword computer_name: Specifies the host OS name of the AzureBareMetal instance. :paramtype computer_name: str :keyword ssh_public_key: Specifies the SSH public key used to access the operating system. :paramtype ssh_public_key: str """ super().__init__(**kwargs) self.computer_name = computer_name self.os_type = None self.version = None self.ssh_public_key = ssh_public_key class Result(_serialization.Model): """Sample result definition. :ivar sample_property: Sample property of type string. :vartype sample_property: str """ _attribute_map = { "sample_property": {"key": "sampleProperty", "type": "str"}, } def __init__(self, *, sample_property: Optional[str] = None, **kwargs): """ :keyword sample_property: Sample property of type string. :paramtype sample_property: str """ super().__init__(**kwargs) self.sample_property = sample_property class StorageProfile(_serialization.Model): """Specifies the storage settings for the AzureBareMetal instance disks. Variables are only populated by the server, and will be ignored when sending a request. :ivar nfs_ip_address: IP Address to connect to storage. :vartype nfs_ip_address: str :ivar os_disks: Specifies information about the operating system disk used by baremetal instance. :vartype os_disks: list[~azure.mgmt.baremetalinfrastructure.models.Disk] """ _validation = { "nfs_ip_address": {"readonly": True}, } _attribute_map = { "nfs_ip_address": {"key": "nfsIpAddress", "type": "str"}, "os_disks": {"key": "osDisks", "type": "[Disk]"}, } def __init__(self, *, os_disks: Optional[List["_models.Disk"]] = None, **kwargs): """ :keyword os_disks: Specifies information about the operating system disk used by baremetal instance. :paramtype os_disks: list[~azure.mgmt.baremetalinfrastructure.models.Disk] """ super().__init__(**kwargs) self.nfs_ip_address = None self.os_disks = os_disks class SystemData(_serialization.Model): """Metadata pertaining to creation and last modification of the resource. :ivar created_by: The identity that created the resource. :vartype created_by: str :ivar created_by_type: The type of identity that created the resource. Known values are: "User", "Application", "ManagedIdentity", and "Key". :vartype created_by_type: str or ~azure.mgmt.baremetalinfrastructure.models.CreatedByType :ivar created_at: The timestamp of resource creation (UTC). :vartype created_at: ~datetime.datetime :ivar last_modified_by: The identity that last modified the resource. :vartype last_modified_by: str :ivar last_modified_by_type: The type of identity that last modified the resource. Known values are: "User", "Application", "ManagedIdentity", and "Key". :vartype last_modified_by_type: str or ~azure.mgmt.baremetalinfrastructure.models.CreatedByType :ivar last_modified_at: The timestamp of resource last modification (UTC). :vartype last_modified_at: ~datetime.datetime """ _attribute_map = { "created_by": {"key": "createdBy", "type": "str"}, "created_by_type": {"key": "createdByType", "type": "str"}, "created_at": {"key": "createdAt", "type": "iso-8601"}, "last_modified_by": {"key": "lastModifiedBy", "type": "str"}, "last_modified_by_type": {"key": "lastModifiedByType", "type": "str"}, "last_modified_at": {"key": "lastModifiedAt", "type": "iso-8601"}, } def __init__( self, *, created_by: Optional[str] = None, created_by_type: Optional[Union[str, "_models.CreatedByType"]] = None, created_at: Optional[datetime.datetime] = None, last_modified_by: Optional[str] = None, last_modified_by_type: Optional[Union[str, "_models.CreatedByType"]] = None, last_modified_at: Optional[datetime.datetime] = None, **kwargs ): """ :keyword created_by: The identity that created the resource. :paramtype created_by: str :keyword created_by_type: The type of identity that created the resource. Known values are: "User", "Application", "ManagedIdentity", and "Key". :paramtype created_by_type: str or ~azure.mgmt.baremetalinfrastructure.models.CreatedByType :keyword created_at: The timestamp of resource creation (UTC). :paramtype created_at: ~datetime.datetime :keyword last_modified_by: The identity that last modified the resource. :paramtype last_modified_by: str :keyword last_modified_by_type: The type of identity that last modified the resource. Known values are: "User", "Application", "ManagedIdentity", and "Key". :paramtype last_modified_by_type: str or ~azure.mgmt.baremetalinfrastructure.models.CreatedByType :keyword last_modified_at: The timestamp of resource last modification (UTC). :paramtype last_modified_at: ~datetime.datetime """ super().__init__(**kwargs) self.created_by = created_by self.created_by_type = created_by_type self.created_at = created_at self.last_modified_by = last_modified_by self.last_modified_by_type = last_modified_by_type self.last_modified_at = last_modified_at class Tags(_serialization.Model): """Tags field of the AzureBareMetal instance. :ivar tags: Tags field of the AzureBareMetal instance. :vartype tags: dict[str, str] """ _attribute_map = { "tags": {"key": "tags", "type": "{str}"}, } def __init__(self, *, tags: Optional[Dict[str, str]] = None, **kwargs): """ :keyword tags: Tags field of the AzureBareMetal instance. :paramtype tags: dict[str, str] """ super().__init__(**kwargs) self.tags = tags
azure-mgmt-baremetalinfrastructure
/azure_mgmt_baremetalinfrastructure-1.1.0b1-py3-none-any.whl/azure/mgmt/baremetalinfrastructure/models/_models_py3.py
_models_py3.py
import datetime from typing import Dict, List, Optional, TYPE_CHECKING, Union from .. import _serialization if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from .. import models as _models class Resource(_serialization.Model): """Common fields that are returned in the response for all Azure Resource Manager resources. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. :vartype id: str :ivar name: The name of the resource. :vartype name: str :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts". :vartype type: str """ _validation = { "id": {"readonly": True}, "name": {"readonly": True}, "type": {"readonly": True}, } _attribute_map = { "id": {"key": "id", "type": "str"}, "name": {"key": "name", "type": "str"}, "type": {"key": "type", "type": "str"}, } def __init__(self, **kwargs): """ """ super().__init__(**kwargs) self.id = None self.name = None self.type = None class TrackedResource(Resource): """The resource model definition for an Azure Resource Manager tracked top level resource which has 'tags' and a 'location'. Variables are only populated by the server, and will be ignored when sending a request. All required parameters must be populated in order to send to Azure. :ivar id: Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. :vartype id: str :ivar name: The name of the resource. :vartype name: str :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts". :vartype type: str :ivar tags: Resource tags. :vartype tags: dict[str, str] :ivar location: The geo-location where the resource lives. Required. :vartype location: str """ _validation = { "id": {"readonly": True}, "name": {"readonly": True}, "type": {"readonly": True}, "location": {"required": True}, } _attribute_map = { "id": {"key": "id", "type": "str"}, "name": {"key": "name", "type": "str"}, "type": {"key": "type", "type": "str"}, "tags": {"key": "tags", "type": "{str}"}, "location": {"key": "location", "type": "str"}, } def __init__(self, *, location: str, tags: Optional[Dict[str, str]] = None, **kwargs): """ :keyword tags: Resource tags. :paramtype tags: dict[str, str] :keyword location: The geo-location where the resource lives. Required. :paramtype location: str """ super().__init__(**kwargs) self.tags = tags self.location = location class AzureBareMetalInstance(TrackedResource): # pylint: disable=too-many-instance-attributes """AzureBareMetal instance info on Azure (ARM properties and AzureBareMetal properties). Variables are only populated by the server, and will be ignored when sending a request. All required parameters must be populated in order to send to Azure. :ivar id: Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. :vartype id: str :ivar name: The name of the resource. :vartype name: str :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts". :vartype type: str :ivar tags: Resource tags. :vartype tags: dict[str, str] :ivar location: The geo-location where the resource lives. Required. :vartype location: str :ivar system_data: The system metadata relating to this resource. :vartype system_data: ~azure.mgmt.baremetalinfrastructure.models.SystemData :ivar hardware_profile: Specifies the hardware settings for the AzureBareMetal instance. :vartype hardware_profile: ~azure.mgmt.baremetalinfrastructure.models.HardwareProfile :ivar storage_profile: Specifies the storage settings for the AzureBareMetal instance disks. :vartype storage_profile: ~azure.mgmt.baremetalinfrastructure.models.StorageProfile :ivar os_profile: Specifies the operating system settings for the AzureBareMetal instance. :vartype os_profile: ~azure.mgmt.baremetalinfrastructure.models.OSProfile :ivar network_profile: Specifies the network settings for the AzureBareMetal instance. :vartype network_profile: ~azure.mgmt.baremetalinfrastructure.models.NetworkProfile :ivar azure_bare_metal_instance_id: Specifies the AzureBareMetal instance unique ID. :vartype azure_bare_metal_instance_id: str :ivar power_state: Resource power state. Known values are: "starting", "started", "stopping", "stopped", "restarting", and "unknown". :vartype power_state: str or ~azure.mgmt.baremetalinfrastructure.models.AzureBareMetalInstancePowerStateEnum :ivar proximity_placement_group: Resource proximity placement group. :vartype proximity_placement_group: str :ivar hw_revision: Hardware revision of an AzureBareMetal instance. :vartype hw_revision: str :ivar partner_node_id: ARM ID of another AzureBareMetalInstance that will share a network with this AzureBareMetalInstance. :vartype partner_node_id: str :ivar provisioning_state: State of provisioning of the AzureBareMetalInstance. Known values are: "Accepted", "Creating", "Updating", "Failed", "Succeeded", "Deleting", and "Migrating". :vartype provisioning_state: str or ~azure.mgmt.baremetalinfrastructure.models.AzureBareMetalProvisioningStatesEnum """ _validation = { "id": {"readonly": True}, "name": {"readonly": True}, "type": {"readonly": True}, "location": {"required": True}, "system_data": {"readonly": True}, "azure_bare_metal_instance_id": {"readonly": True}, "power_state": {"readonly": True}, "proximity_placement_group": {"readonly": True}, "hw_revision": {"readonly": True}, "provisioning_state": {"readonly": True}, } _attribute_map = { "id": {"key": "id", "type": "str"}, "name": {"key": "name", "type": "str"}, "type": {"key": "type", "type": "str"}, "tags": {"key": "tags", "type": "{str}"}, "location": {"key": "location", "type": "str"}, "system_data": {"key": "systemData", "type": "SystemData"}, "hardware_profile": {"key": "properties.hardwareProfile", "type": "HardwareProfile"}, "storage_profile": {"key": "properties.storageProfile", "type": "StorageProfile"}, "os_profile": {"key": "properties.osProfile", "type": "OSProfile"}, "network_profile": {"key": "properties.networkProfile", "type": "NetworkProfile"}, "azure_bare_metal_instance_id": {"key": "properties.azureBareMetalInstanceId", "type": "str"}, "power_state": {"key": "properties.powerState", "type": "str"}, "proximity_placement_group": {"key": "properties.proximityPlacementGroup", "type": "str"}, "hw_revision": {"key": "properties.hwRevision", "type": "str"}, "partner_node_id": {"key": "properties.partnerNodeId", "type": "str"}, "provisioning_state": {"key": "properties.provisioningState", "type": "str"}, } def __init__( self, *, location: str, tags: Optional[Dict[str, str]] = None, hardware_profile: Optional["_models.HardwareProfile"] = None, storage_profile: Optional["_models.StorageProfile"] = None, os_profile: Optional["_models.OSProfile"] = None, network_profile: Optional["_models.NetworkProfile"] = None, partner_node_id: Optional[str] = None, **kwargs ): """ :keyword tags: Resource tags. :paramtype tags: dict[str, str] :keyword location: The geo-location where the resource lives. Required. :paramtype location: str :keyword hardware_profile: Specifies the hardware settings for the AzureBareMetal instance. :paramtype hardware_profile: ~azure.mgmt.baremetalinfrastructure.models.HardwareProfile :keyword storage_profile: Specifies the storage settings for the AzureBareMetal instance disks. :paramtype storage_profile: ~azure.mgmt.baremetalinfrastructure.models.StorageProfile :keyword os_profile: Specifies the operating system settings for the AzureBareMetal instance. :paramtype os_profile: ~azure.mgmt.baremetalinfrastructure.models.OSProfile :keyword network_profile: Specifies the network settings for the AzureBareMetal instance. :paramtype network_profile: ~azure.mgmt.baremetalinfrastructure.models.NetworkProfile :keyword partner_node_id: ARM ID of another AzureBareMetalInstance that will share a network with this AzureBareMetalInstance. :paramtype partner_node_id: str """ super().__init__(tags=tags, location=location, **kwargs) self.system_data = None self.hardware_profile = hardware_profile self.storage_profile = storage_profile self.os_profile = os_profile self.network_profile = network_profile self.azure_bare_metal_instance_id = None self.power_state = None self.proximity_placement_group = None self.hw_revision = None self.partner_node_id = partner_node_id self.provisioning_state = None class AzureBareMetalInstancesListResult(_serialization.Model): """The response from the List AzureBareMetal Instances operation. :ivar value: The list of Azure BareMetal instances. :vartype value: list[~azure.mgmt.baremetalinfrastructure.models.AzureBareMetalInstance] :ivar next_link: The URL to get the next set of AzureBareMetal instances. :vartype next_link: str """ _attribute_map = { "value": {"key": "value", "type": "[AzureBareMetalInstance]"}, "next_link": {"key": "nextLink", "type": "str"}, } def __init__( self, *, value: Optional[List["_models.AzureBareMetalInstance"]] = None, next_link: Optional[str] = None, **kwargs ): """ :keyword value: The list of Azure BareMetal instances. :paramtype value: list[~azure.mgmt.baremetalinfrastructure.models.AzureBareMetalInstance] :keyword next_link: The URL to get the next set of AzureBareMetal instances. :paramtype next_link: str """ super().__init__(**kwargs) self.value = value self.next_link = next_link class Disk(_serialization.Model): """Specifies the disk information fo the AzureBareMetal instance. Variables are only populated by the server, and will be ignored when sending a request. :ivar name: The disk name. :vartype name: str :ivar disk_size_gb: Specifies the size of an empty data disk in gigabytes. :vartype disk_size_gb: int :ivar lun: Specifies the logical unit number of the data disk. This value is used to identify data disks within the VM and therefore must be unique for each data disk attached to a VM. :vartype lun: int """ _validation = { "lun": {"readonly": True}, } _attribute_map = { "name": {"key": "name", "type": "str"}, "disk_size_gb": {"key": "diskSizeGB", "type": "int"}, "lun": {"key": "lun", "type": "int"}, } def __init__(self, *, name: Optional[str] = None, disk_size_gb: Optional[int] = None, **kwargs): """ :keyword name: The disk name. :paramtype name: str :keyword disk_size_gb: Specifies the size of an empty data disk in gigabytes. :paramtype disk_size_gb: int """ super().__init__(**kwargs) self.name = name self.disk_size_gb = disk_size_gb self.lun = None class Display(_serialization.Model): """Detailed BareMetal operation information. Variables are only populated by the server, and will be ignored when sending a request. :ivar provider: The localized friendly form of the resource provider name. :vartype provider: str :ivar resource: The localized friendly form of the resource type related to this action/operation. :vartype resource: str :ivar operation: The localized friendly name for the operation as shown to the user. :vartype operation: str :ivar description: The localized friendly description for the operation as shown to the user. :vartype description: str """ _validation = { "provider": {"readonly": True}, "resource": {"readonly": True}, "operation": {"readonly": True}, "description": {"readonly": True}, } _attribute_map = { "provider": {"key": "provider", "type": "str"}, "resource": {"key": "resource", "type": "str"}, "operation": {"key": "operation", "type": "str"}, "description": {"key": "description", "type": "str"}, } def __init__(self, **kwargs): """ """ super().__init__(**kwargs) self.provider = None self.resource = None self.operation = None self.description = None class ErrorDefinition(_serialization.Model): """Error definition. Variables are only populated by the server, and will be ignored when sending a request. :ivar code: Service specific error code which serves as the substatus for the HTTP error code. :vartype code: str :ivar message: Description of the error. :vartype message: str :ivar details: Internal error details. :vartype details: list[~azure.mgmt.baremetalinfrastructure.models.ErrorDefinition] """ _validation = { "code": {"readonly": True}, "message": {"readonly": True}, "details": {"readonly": True}, } _attribute_map = { "code": {"key": "code", "type": "str"}, "message": {"key": "message", "type": "str"}, "details": {"key": "details", "type": "[ErrorDefinition]"}, } def __init__(self, **kwargs): """ """ super().__init__(**kwargs) self.code = None self.message = None self.details = None class ErrorResponse(_serialization.Model): """Error response. :ivar error: The error details. :vartype error: ~azure.mgmt.baremetalinfrastructure.models.ErrorDefinition """ _attribute_map = { "error": {"key": "error", "type": "ErrorDefinition"}, } def __init__(self, *, error: Optional["_models.ErrorDefinition"] = None, **kwargs): """ :keyword error: The error details. :paramtype error: ~azure.mgmt.baremetalinfrastructure.models.ErrorDefinition """ super().__init__(**kwargs) self.error = error class HardwareProfile(_serialization.Model): """Specifies the hardware settings for the AzureBareMetal instance. Variables are only populated by the server, and will be ignored when sending a request. :ivar hardware_type: Name of the hardware type (vendor and/or their product name). Known values are: "Cisco_UCS" and "HPE". :vartype hardware_type: str or ~azure.mgmt.baremetalinfrastructure.models.AzureBareMetalHardwareTypeNamesEnum :ivar azure_bare_metal_instance_size: Specifies the AzureBareMetal instance SKU. Known values are: "S72m", "S144m", "S72", "S144", "S192", "S192m", "S192xm", "S96", "S112", "S224", "S224m", "S224om", "S224oo", "S224oom", "S224ooo", "S384", "S384m", "S384xm", "S384xxm", "S448", "S448m", "S448om", "S448oo", "S448oom", "S448ooo", "S576m", "S576xm", "S672", "S672m", "S672om", "S672oo", "S672oom", "S672ooo", "S768", "S768m", "S768xm", "S896", "S896m", "S896om", "S896oo", "S896oom", "S896ooo", and "S960m". :vartype azure_bare_metal_instance_size: str or ~azure.mgmt.baremetalinfrastructure.models.AzureBareMetalInstanceSizeNamesEnum """ _validation = { "hardware_type": {"readonly": True}, "azure_bare_metal_instance_size": {"readonly": True}, } _attribute_map = { "hardware_type": {"key": "hardwareType", "type": "str"}, "azure_bare_metal_instance_size": {"key": "azureBareMetalInstanceSize", "type": "str"}, } def __init__(self, **kwargs): """ """ super().__init__(**kwargs) self.hardware_type = None self.azure_bare_metal_instance_size = None class IpAddress(_serialization.Model): """Specifies the IP address of the network interface. :ivar ip_address: Specifies the IP address of the network interface. :vartype ip_address: str """ _attribute_map = { "ip_address": {"key": "ipAddress", "type": "str"}, } def __init__(self, *, ip_address: Optional[str] = None, **kwargs): """ :keyword ip_address: Specifies the IP address of the network interface. :paramtype ip_address: str """ super().__init__(**kwargs) self.ip_address = ip_address class NetworkProfile(_serialization.Model): """Specifies the network settings for the AzureBareMetal instance disks. Variables are only populated by the server, and will be ignored when sending a request. :ivar network_interfaces: Specifies the network interfaces for the AzureBareMetal instance. :vartype network_interfaces: list[~azure.mgmt.baremetalinfrastructure.models.IpAddress] :ivar circuit_id: Specifies the circuit id for connecting to express route. :vartype circuit_id: str """ _validation = { "circuit_id": {"readonly": True}, } _attribute_map = { "network_interfaces": {"key": "networkInterfaces", "type": "[IpAddress]"}, "circuit_id": {"key": "circuitId", "type": "str"}, } def __init__(self, *, network_interfaces: Optional[List["_models.IpAddress"]] = None, **kwargs): """ :keyword network_interfaces: Specifies the network interfaces for the AzureBareMetal instance. :paramtype network_interfaces: list[~azure.mgmt.baremetalinfrastructure.models.IpAddress] """ super().__init__(**kwargs) self.network_interfaces = network_interfaces self.circuit_id = None class Operation(_serialization.Model): """AzureBareMetal operation information. Variables are only populated by the server, and will be ignored when sending a request. :ivar name: The name of the operation being performed on this particular object. This name should match the action name that appears in RBAC / the event service. :vartype name: str :ivar display: Displayed AzureBareMetal operation information. :vartype display: ~azure.mgmt.baremetalinfrastructure.models.Display :ivar is_data_action: indicates whether an operation is a data action or not. :vartype is_data_action: bool """ _validation = { "name": {"readonly": True}, "is_data_action": {"readonly": True}, } _attribute_map = { "name": {"key": "name", "type": "str"}, "display": {"key": "display", "type": "Display"}, "is_data_action": {"key": "isDataAction", "type": "bool"}, } def __init__(self, *, display: Optional["_models.Display"] = None, **kwargs): """ :keyword display: Displayed AzureBareMetal operation information. :paramtype display: ~azure.mgmt.baremetalinfrastructure.models.Display """ super().__init__(**kwargs) self.name = None self.display = display self.is_data_action = None class OperationList(_serialization.Model): """List of AzureBareMetal operations. :ivar value: List of AzureBareMetal operations. :vartype value: list[~azure.mgmt.baremetalinfrastructure.models.Operation] """ _attribute_map = { "value": {"key": "value", "type": "[Operation]"}, } def __init__(self, *, value: Optional[List["_models.Operation"]] = None, **kwargs): """ :keyword value: List of AzureBareMetal operations. :paramtype value: list[~azure.mgmt.baremetalinfrastructure.models.Operation] """ super().__init__(**kwargs) self.value = value class OSProfile(_serialization.Model): """Specifies the operating system settings for the AzureBareMetal instance. Variables are only populated by the server, and will be ignored when sending a request. :ivar computer_name: Specifies the host OS name of the AzureBareMetal instance. :vartype computer_name: str :ivar os_type: This property allows you to specify the type of the OS. :vartype os_type: str :ivar version: Specifies version of operating system. :vartype version: str :ivar ssh_public_key: Specifies the SSH public key used to access the operating system. :vartype ssh_public_key: str """ _validation = { "os_type": {"readonly": True}, "version": {"readonly": True}, } _attribute_map = { "computer_name": {"key": "computerName", "type": "str"}, "os_type": {"key": "osType", "type": "str"}, "version": {"key": "version", "type": "str"}, "ssh_public_key": {"key": "sshPublicKey", "type": "str"}, } def __init__(self, *, computer_name: Optional[str] = None, ssh_public_key: Optional[str] = None, **kwargs): """ :keyword computer_name: Specifies the host OS name of the AzureBareMetal instance. :paramtype computer_name: str :keyword ssh_public_key: Specifies the SSH public key used to access the operating system. :paramtype ssh_public_key: str """ super().__init__(**kwargs) self.computer_name = computer_name self.os_type = None self.version = None self.ssh_public_key = ssh_public_key class Result(_serialization.Model): """Sample result definition. :ivar sample_property: Sample property of type string. :vartype sample_property: str """ _attribute_map = { "sample_property": {"key": "sampleProperty", "type": "str"}, } def __init__(self, *, sample_property: Optional[str] = None, **kwargs): """ :keyword sample_property: Sample property of type string. :paramtype sample_property: str """ super().__init__(**kwargs) self.sample_property = sample_property class StorageProfile(_serialization.Model): """Specifies the storage settings for the AzureBareMetal instance disks. Variables are only populated by the server, and will be ignored when sending a request. :ivar nfs_ip_address: IP Address to connect to storage. :vartype nfs_ip_address: str :ivar os_disks: Specifies information about the operating system disk used by baremetal instance. :vartype os_disks: list[~azure.mgmt.baremetalinfrastructure.models.Disk] """ _validation = { "nfs_ip_address": {"readonly": True}, } _attribute_map = { "nfs_ip_address": {"key": "nfsIpAddress", "type": "str"}, "os_disks": {"key": "osDisks", "type": "[Disk]"}, } def __init__(self, *, os_disks: Optional[List["_models.Disk"]] = None, **kwargs): """ :keyword os_disks: Specifies information about the operating system disk used by baremetal instance. :paramtype os_disks: list[~azure.mgmt.baremetalinfrastructure.models.Disk] """ super().__init__(**kwargs) self.nfs_ip_address = None self.os_disks = os_disks class SystemData(_serialization.Model): """Metadata pertaining to creation and last modification of the resource. :ivar created_by: The identity that created the resource. :vartype created_by: str :ivar created_by_type: The type of identity that created the resource. Known values are: "User", "Application", "ManagedIdentity", and "Key". :vartype created_by_type: str or ~azure.mgmt.baremetalinfrastructure.models.CreatedByType :ivar created_at: The timestamp of resource creation (UTC). :vartype created_at: ~datetime.datetime :ivar last_modified_by: The identity that last modified the resource. :vartype last_modified_by: str :ivar last_modified_by_type: The type of identity that last modified the resource. Known values are: "User", "Application", "ManagedIdentity", and "Key". :vartype last_modified_by_type: str or ~azure.mgmt.baremetalinfrastructure.models.CreatedByType :ivar last_modified_at: The timestamp of resource last modification (UTC). :vartype last_modified_at: ~datetime.datetime """ _attribute_map = { "created_by": {"key": "createdBy", "type": "str"}, "created_by_type": {"key": "createdByType", "type": "str"}, "created_at": {"key": "createdAt", "type": "iso-8601"}, "last_modified_by": {"key": "lastModifiedBy", "type": "str"}, "last_modified_by_type": {"key": "lastModifiedByType", "type": "str"}, "last_modified_at": {"key": "lastModifiedAt", "type": "iso-8601"}, } def __init__( self, *, created_by: Optional[str] = None, created_by_type: Optional[Union[str, "_models.CreatedByType"]] = None, created_at: Optional[datetime.datetime] = None, last_modified_by: Optional[str] = None, last_modified_by_type: Optional[Union[str, "_models.CreatedByType"]] = None, last_modified_at: Optional[datetime.datetime] = None, **kwargs ): """ :keyword created_by: The identity that created the resource. :paramtype created_by: str :keyword created_by_type: The type of identity that created the resource. Known values are: "User", "Application", "ManagedIdentity", and "Key". :paramtype created_by_type: str or ~azure.mgmt.baremetalinfrastructure.models.CreatedByType :keyword created_at: The timestamp of resource creation (UTC). :paramtype created_at: ~datetime.datetime :keyword last_modified_by: The identity that last modified the resource. :paramtype last_modified_by: str :keyword last_modified_by_type: The type of identity that last modified the resource. Known values are: "User", "Application", "ManagedIdentity", and "Key". :paramtype last_modified_by_type: str or ~azure.mgmt.baremetalinfrastructure.models.CreatedByType :keyword last_modified_at: The timestamp of resource last modification (UTC). :paramtype last_modified_at: ~datetime.datetime """ super().__init__(**kwargs) self.created_by = created_by self.created_by_type = created_by_type self.created_at = created_at self.last_modified_by = last_modified_by self.last_modified_by_type = last_modified_by_type self.last_modified_at = last_modified_at class Tags(_serialization.Model): """Tags field of the AzureBareMetal instance. :ivar tags: Tags field of the AzureBareMetal instance. :vartype tags: dict[str, str] """ _attribute_map = { "tags": {"key": "tags", "type": "{str}"}, } def __init__(self, *, tags: Optional[Dict[str, str]] = None, **kwargs): """ :keyword tags: Tags field of the AzureBareMetal instance. :paramtype tags: dict[str, str] """ super().__init__(**kwargs) self.tags = tags
0.864697
0.202759
from enum import Enum from azure.core import CaseInsensitiveEnumMeta class AzureBareMetalHardwareTypeNamesEnum(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Name of the hardware type (vendor and/or their product name).""" CISCO_UCS = "Cisco_UCS" HPE = "HPE" class AzureBareMetalInstancePowerStateEnum(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Resource power state.""" STARTING = "starting" STARTED = "started" STOPPING = "stopping" STOPPED = "stopped" RESTARTING = "restarting" UNKNOWN = "unknown" class AzureBareMetalInstanceSizeNamesEnum(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Specifies the AzureBareMetal instance SKU.""" S72_M = "S72m" S144_M = "S144m" S72 = "S72" S144 = "S144" S192 = "S192" S192_M = "S192m" S192_XM = "S192xm" S96 = "S96" S112 = "S112" S224 = "S224" S224_M = "S224m" S224_OM = "S224om" S224_OO = "S224oo" S224_OOM = "S224oom" S224_OOO = "S224ooo" S384 = "S384" S384_M = "S384m" S384_XM = "S384xm" S384_XXM = "S384xxm" S448 = "S448" S448_M = "S448m" S448_OM = "S448om" S448_OO = "S448oo" S448_OOM = "S448oom" S448_OOO = "S448ooo" S576_M = "S576m" S576_XM = "S576xm" S672 = "S672" S672_M = "S672m" S672_OM = "S672om" S672_OO = "S672oo" S672_OOM = "S672oom" S672_OOO = "S672ooo" S768 = "S768" S768_M = "S768m" S768_XM = "S768xm" S896 = "S896" S896_M = "S896m" S896_OM = "S896om" S896_OO = "S896oo" S896_OOM = "S896oom" S896_OOO = "S896ooo" S960_M = "S960m" class AzureBareMetalProvisioningStatesEnum(str, Enum, metaclass=CaseInsensitiveEnumMeta): """State of provisioning of the AzureBareMetalInstance.""" ACCEPTED = "Accepted" CREATING = "Creating" UPDATING = "Updating" FAILED = "Failed" SUCCEEDED = "Succeeded" DELETING = "Deleting" MIGRATING = "Migrating" class CreatedByType(str, Enum, metaclass=CaseInsensitiveEnumMeta): """The type of identity that created the resource.""" USER = "User" APPLICATION = "Application" MANAGED_IDENTITY = "ManagedIdentity" KEY = "Key"
azure-mgmt-baremetalinfrastructure
/azure_mgmt_baremetalinfrastructure-1.1.0b1-py3-none-any.whl/azure/mgmt/baremetalinfrastructure/models/_bare_metal_infrastructure_client_enums.py
_bare_metal_infrastructure_client_enums.py
from enum import Enum from azure.core import CaseInsensitiveEnumMeta class AzureBareMetalHardwareTypeNamesEnum(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Name of the hardware type (vendor and/or their product name).""" CISCO_UCS = "Cisco_UCS" HPE = "HPE" class AzureBareMetalInstancePowerStateEnum(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Resource power state.""" STARTING = "starting" STARTED = "started" STOPPING = "stopping" STOPPED = "stopped" RESTARTING = "restarting" UNKNOWN = "unknown" class AzureBareMetalInstanceSizeNamesEnum(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Specifies the AzureBareMetal instance SKU.""" S72_M = "S72m" S144_M = "S144m" S72 = "S72" S144 = "S144" S192 = "S192" S192_M = "S192m" S192_XM = "S192xm" S96 = "S96" S112 = "S112" S224 = "S224" S224_M = "S224m" S224_OM = "S224om" S224_OO = "S224oo" S224_OOM = "S224oom" S224_OOO = "S224ooo" S384 = "S384" S384_M = "S384m" S384_XM = "S384xm" S384_XXM = "S384xxm" S448 = "S448" S448_M = "S448m" S448_OM = "S448om" S448_OO = "S448oo" S448_OOM = "S448oom" S448_OOO = "S448ooo" S576_M = "S576m" S576_XM = "S576xm" S672 = "S672" S672_M = "S672m" S672_OM = "S672om" S672_OO = "S672oo" S672_OOM = "S672oom" S672_OOO = "S672ooo" S768 = "S768" S768_M = "S768m" S768_XM = "S768xm" S896 = "S896" S896_M = "S896m" S896_OM = "S896om" S896_OO = "S896oo" S896_OOM = "S896oom" S896_OOO = "S896ooo" S960_M = "S960m" class AzureBareMetalProvisioningStatesEnum(str, Enum, metaclass=CaseInsensitiveEnumMeta): """State of provisioning of the AzureBareMetalInstance.""" ACCEPTED = "Accepted" CREATING = "Creating" UPDATING = "Updating" FAILED = "Failed" SUCCEEDED = "Succeeded" DELETING = "Deleting" MIGRATING = "Migrating" class CreatedByType(str, Enum, metaclass=CaseInsensitiveEnumMeta): """The type of identity that created the resource.""" USER = "User" APPLICATION = "Application" MANAGED_IDENTITY = "ManagedIdentity" KEY = "Key"
0.71889
0.096877
from copy import deepcopy from typing import Any, TYPE_CHECKING from azure.core.rest import HttpRequest, HttpResponse from azure.mgmt.core import ARMPipelineClient from . import models as _models from ._configuration import BatchManagementClientConfiguration from ._serialization import Deserializer, Serializer from .operations import ( ApplicationOperations, ApplicationPackageOperations, BatchAccountOperations, CertificateOperations, LocationOperations, Operations, PoolOperations, PrivateEndpointConnectionOperations, PrivateLinkResourceOperations, ) if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials import TokenCredential class BatchManagementClient: # pylint: disable=client-accepts-api-version-keyword,too-many-instance-attributes """Batch Client. :ivar batch_account: BatchAccountOperations operations :vartype batch_account: azure.mgmt.batch.operations.BatchAccountOperations :ivar application_package: ApplicationPackageOperations operations :vartype application_package: azure.mgmt.batch.operations.ApplicationPackageOperations :ivar application: ApplicationOperations operations :vartype application: azure.mgmt.batch.operations.ApplicationOperations :ivar location: LocationOperations operations :vartype location: azure.mgmt.batch.operations.LocationOperations :ivar operations: Operations operations :vartype operations: azure.mgmt.batch.operations.Operations :ivar certificate: CertificateOperations operations :vartype certificate: azure.mgmt.batch.operations.CertificateOperations :ivar private_link_resource: PrivateLinkResourceOperations operations :vartype private_link_resource: azure.mgmt.batch.operations.PrivateLinkResourceOperations :ivar private_endpoint_connection: PrivateEndpointConnectionOperations operations :vartype private_endpoint_connection: azure.mgmt.batch.operations.PrivateEndpointConnectionOperations :ivar pool: PoolOperations operations :vartype pool: azure.mgmt.batch.operations.PoolOperations :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials.TokenCredential :param subscription_id: The Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000). Required. :type subscription_id: str :param base_url: Service URL. Default value is "https://management.azure.com". :type base_url: str :keyword api_version: Api Version. Default value is "2023-05-01". Note that overriding this default value may result in unsupported behavior. :paramtype api_version: str :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. """ def __init__( self, credential: "TokenCredential", subscription_id: str, base_url: str = "https://management.azure.com", **kwargs: Any ) -> None: self._config = BatchManagementClientConfiguration( credential=credential, subscription_id=subscription_id, **kwargs ) self._client: ARMPipelineClient = ARMPipelineClient(base_url=base_url, config=self._config, **kwargs) client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)} self._serialize = Serializer(client_models) self._deserialize = Deserializer(client_models) self._serialize.client_side_validation = False self.batch_account = BatchAccountOperations(self._client, self._config, self._serialize, self._deserialize) self.application_package = ApplicationPackageOperations( self._client, self._config, self._serialize, self._deserialize ) self.application = ApplicationOperations(self._client, self._config, self._serialize, self._deserialize) self.location = LocationOperations(self._client, self._config, self._serialize, self._deserialize) self.operations = Operations(self._client, self._config, self._serialize, self._deserialize) self.certificate = CertificateOperations(self._client, self._config, self._serialize, self._deserialize) self.private_link_resource = PrivateLinkResourceOperations( self._client, self._config, self._serialize, self._deserialize ) self.private_endpoint_connection = PrivateEndpointConnectionOperations( self._client, self._config, self._serialize, self._deserialize ) self.pool = PoolOperations(self._client, self._config, self._serialize, self._deserialize) def _send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: """Runs the network request through the client's chained policies. >>> from azure.core.rest import HttpRequest >>> request = HttpRequest("GET", "https://www.example.org/") <HttpRequest [GET], url: 'https://www.example.org/'> >>> response = client._send_request(request) <HttpResponse: 200 OK> For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request :param request: The network request you want to make. Required. :type request: ~azure.core.rest.HttpRequest :keyword bool stream: Whether the response payload will be streamed. Defaults to False. :return: The response of your network call. Does not do error handling on your response. :rtype: ~azure.core.rest.HttpResponse """ request_copy = deepcopy(request) request_copy.url = self._client.format_url(request_copy.url) return self._client.send_request(request_copy, **kwargs) def close(self) -> None: self._client.close() def __enter__(self) -> "BatchManagementClient": self._client.__enter__() return self def __exit__(self, *exc_details: Any) -> None: self._client.__exit__(*exc_details)
azure-mgmt-batch
/azure_mgmt_batch-17.1.0-py3-none-any.whl/azure/mgmt/batch/_batch_management_client.py
_batch_management_client.py
from copy import deepcopy from typing import Any, TYPE_CHECKING from azure.core.rest import HttpRequest, HttpResponse from azure.mgmt.core import ARMPipelineClient from . import models as _models from ._configuration import BatchManagementClientConfiguration from ._serialization import Deserializer, Serializer from .operations import ( ApplicationOperations, ApplicationPackageOperations, BatchAccountOperations, CertificateOperations, LocationOperations, Operations, PoolOperations, PrivateEndpointConnectionOperations, PrivateLinkResourceOperations, ) if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials import TokenCredential class BatchManagementClient: # pylint: disable=client-accepts-api-version-keyword,too-many-instance-attributes """Batch Client. :ivar batch_account: BatchAccountOperations operations :vartype batch_account: azure.mgmt.batch.operations.BatchAccountOperations :ivar application_package: ApplicationPackageOperations operations :vartype application_package: azure.mgmt.batch.operations.ApplicationPackageOperations :ivar application: ApplicationOperations operations :vartype application: azure.mgmt.batch.operations.ApplicationOperations :ivar location: LocationOperations operations :vartype location: azure.mgmt.batch.operations.LocationOperations :ivar operations: Operations operations :vartype operations: azure.mgmt.batch.operations.Operations :ivar certificate: CertificateOperations operations :vartype certificate: azure.mgmt.batch.operations.CertificateOperations :ivar private_link_resource: PrivateLinkResourceOperations operations :vartype private_link_resource: azure.mgmt.batch.operations.PrivateLinkResourceOperations :ivar private_endpoint_connection: PrivateEndpointConnectionOperations operations :vartype private_endpoint_connection: azure.mgmt.batch.operations.PrivateEndpointConnectionOperations :ivar pool: PoolOperations operations :vartype pool: azure.mgmt.batch.operations.PoolOperations :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials.TokenCredential :param subscription_id: The Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000). Required. :type subscription_id: str :param base_url: Service URL. Default value is "https://management.azure.com". :type base_url: str :keyword api_version: Api Version. Default value is "2023-05-01". Note that overriding this default value may result in unsupported behavior. :paramtype api_version: str :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. """ def __init__( self, credential: "TokenCredential", subscription_id: str, base_url: str = "https://management.azure.com", **kwargs: Any ) -> None: self._config = BatchManagementClientConfiguration( credential=credential, subscription_id=subscription_id, **kwargs ) self._client: ARMPipelineClient = ARMPipelineClient(base_url=base_url, config=self._config, **kwargs) client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)} self._serialize = Serializer(client_models) self._deserialize = Deserializer(client_models) self._serialize.client_side_validation = False self.batch_account = BatchAccountOperations(self._client, self._config, self._serialize, self._deserialize) self.application_package = ApplicationPackageOperations( self._client, self._config, self._serialize, self._deserialize ) self.application = ApplicationOperations(self._client, self._config, self._serialize, self._deserialize) self.location = LocationOperations(self._client, self._config, self._serialize, self._deserialize) self.operations = Operations(self._client, self._config, self._serialize, self._deserialize) self.certificate = CertificateOperations(self._client, self._config, self._serialize, self._deserialize) self.private_link_resource = PrivateLinkResourceOperations( self._client, self._config, self._serialize, self._deserialize ) self.private_endpoint_connection = PrivateEndpointConnectionOperations( self._client, self._config, self._serialize, self._deserialize ) self.pool = PoolOperations(self._client, self._config, self._serialize, self._deserialize) def _send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: """Runs the network request through the client's chained policies. >>> from azure.core.rest import HttpRequest >>> request = HttpRequest("GET", "https://www.example.org/") <HttpRequest [GET], url: 'https://www.example.org/'> >>> response = client._send_request(request) <HttpResponse: 200 OK> For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request :param request: The network request you want to make. Required. :type request: ~azure.core.rest.HttpRequest :keyword bool stream: Whether the response payload will be streamed. Defaults to False. :return: The response of your network call. Does not do error handling on your response. :rtype: ~azure.core.rest.HttpResponse """ request_copy = deepcopy(request) request_copy.url = self._client.format_url(request_copy.url) return self._client.send_request(request_copy, **kwargs) def close(self) -> None: self._client.close() def __enter__(self) -> "BatchManagementClient": self._client.__enter__() return self def __exit__(self, *exc_details: Any) -> None: self._client.__exit__(*exc_details)
0.843073
0.091018
from typing import Any, TYPE_CHECKING from azure.core.configuration import Configuration from azure.core.pipeline import policies from azure.mgmt.core.policies import ARMChallengeAuthenticationPolicy, ARMHttpLoggingPolicy from ._version import VERSION if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials import TokenCredential class BatchManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes """Configuration for BatchManagementClient. Note that all parameters used to create this instance are saved as instance attributes. :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials.TokenCredential :param subscription_id: The Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000). Required. :type subscription_id: str :keyword api_version: Api Version. Default value is "2023-05-01". Note that overriding this default value may result in unsupported behavior. :paramtype api_version: str """ def __init__(self, credential: "TokenCredential", subscription_id: str, **kwargs: Any) -> None: super(BatchManagementClientConfiguration, self).__init__(**kwargs) api_version: str = kwargs.pop("api_version", "2023-05-01") if credential is None: raise ValueError("Parameter 'credential' must not be None.") if subscription_id is None: raise ValueError("Parameter 'subscription_id' must not be None.") self.credential = credential self.subscription_id = subscription_id self.api_version = api_version self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) kwargs.setdefault("sdk_moniker", "mgmt-batch/{}".format(VERSION)) self._configure(**kwargs) def _configure(self, **kwargs: Any) -> None: self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) self.retry_policy = kwargs.get("retry_policy") or policies.RetryPolicy(**kwargs) self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) self.redirect_policy = kwargs.get("redirect_policy") or policies.RedirectPolicy(**kwargs) self.authentication_policy = kwargs.get("authentication_policy") if self.credential and not self.authentication_policy: self.authentication_policy = ARMChallengeAuthenticationPolicy( self.credential, *self.credential_scopes, **kwargs )
azure-mgmt-batch
/azure_mgmt_batch-17.1.0-py3-none-any.whl/azure/mgmt/batch/_configuration.py
_configuration.py
from typing import Any, TYPE_CHECKING from azure.core.configuration import Configuration from azure.core.pipeline import policies from azure.mgmt.core.policies import ARMChallengeAuthenticationPolicy, ARMHttpLoggingPolicy from ._version import VERSION if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials import TokenCredential class BatchManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes """Configuration for BatchManagementClient. Note that all parameters used to create this instance are saved as instance attributes. :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials.TokenCredential :param subscription_id: The Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000). Required. :type subscription_id: str :keyword api_version: Api Version. Default value is "2023-05-01". Note that overriding this default value may result in unsupported behavior. :paramtype api_version: str """ def __init__(self, credential: "TokenCredential", subscription_id: str, **kwargs: Any) -> None: super(BatchManagementClientConfiguration, self).__init__(**kwargs) api_version: str = kwargs.pop("api_version", "2023-05-01") if credential is None: raise ValueError("Parameter 'credential' must not be None.") if subscription_id is None: raise ValueError("Parameter 'subscription_id' must not be None.") self.credential = credential self.subscription_id = subscription_id self.api_version = api_version self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) kwargs.setdefault("sdk_moniker", "mgmt-batch/{}".format(VERSION)) self._configure(**kwargs) def _configure(self, **kwargs: Any) -> None: self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) self.retry_policy = kwargs.get("retry_policy") or policies.RetryPolicy(**kwargs) self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) self.redirect_policy = kwargs.get("redirect_policy") or policies.RedirectPolicy(**kwargs) self.authentication_policy = kwargs.get("authentication_policy") if self.credential and not self.authentication_policy: self.authentication_policy = ARMChallengeAuthenticationPolicy( self.credential, *self.credential_scopes, **kwargs )
0.835852
0.092606
from io import IOBase from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, cast, overload import urllib.parse from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, map_error, ) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse from azure.core.polling import LROPoller, NoPolling, PollingMethod from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.arm_polling import ARMPolling from .. import models as _models from .._serialization import Serializer from .._vendor import _convert_request, _format_url_section T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False def build_list_by_batch_account_request( resource_group_name: str, account_name: str, subscription_id: str, *, maxresults: Optional[int] = None, select: Optional[str] = None, filter: Optional[str] = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-05-01")) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/pools", ) # pylint: disable=line-too-long path_format_arguments = { "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), "accountName": _SERIALIZER.url( "account_name", account_name, "str", max_length=24, min_length=3, pattern=r"^[a-zA-Z0-9]+$" ), "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # Construct parameters if maxresults is not None: _params["maxresults"] = _SERIALIZER.query("maxresults", maxresults, "int") if select is not None: _params["$select"] = _SERIALIZER.query("select", select, "str") if filter is not None: _params["$filter"] = _SERIALIZER.query("filter", filter, "str") _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_create_request( resource_group_name: str, account_name: str, pool_name: str, subscription_id: str, *, if_match: Optional[str] = None, if_none_match: Optional[str] = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-05-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/pools/{poolName}", ) # pylint: disable=line-too-long path_format_arguments = { "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), "accountName": _SERIALIZER.url( "account_name", account_name, "str", max_length=24, min_length=3, pattern=r"^[a-zA-Z0-9]+$" ), "poolName": _SERIALIZER.url( "pool_name", pool_name, "str", max_length=64, min_length=1, pattern=r"^[a-zA-Z0-9_-]+$" ), "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers if if_match is not None: _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") if if_none_match is not None: _headers["If-None-Match"] = _SERIALIZER.header("if_none_match", if_none_match, "str") if content_type is not None: _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) def build_update_request( resource_group_name: str, account_name: str, pool_name: str, subscription_id: str, *, if_match: Optional[str] = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-05-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/pools/{poolName}", ) # pylint: disable=line-too-long path_format_arguments = { "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), "accountName": _SERIALIZER.url( "account_name", account_name, "str", max_length=24, min_length=3, pattern=r"^[a-zA-Z0-9]+$" ), "poolName": _SERIALIZER.url( "pool_name", pool_name, "str", max_length=64, min_length=1, pattern=r"^[a-zA-Z0-9_-]+$" ), "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers if if_match is not None: _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") if content_type is not None: _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs) def build_delete_request( resource_group_name: str, account_name: str, pool_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-05-01")) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/pools/{poolName}", ) # pylint: disable=line-too-long path_format_arguments = { "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), "accountName": _SERIALIZER.url( "account_name", account_name, "str", max_length=24, min_length=3, pattern=r"^[a-zA-Z0-9]+$" ), "poolName": _SERIALIZER.url( "pool_name", pool_name, "str", max_length=64, min_length=1, pattern=r"^[a-zA-Z0-9_-]+$" ), "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) def build_get_request( resource_group_name: str, account_name: str, pool_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-05-01")) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/pools/{poolName}", ) # pylint: disable=line-too-long path_format_arguments = { "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), "accountName": _SERIALIZER.url( "account_name", account_name, "str", max_length=24, min_length=3, pattern=r"^[a-zA-Z0-9]+$" ), "poolName": _SERIALIZER.url( "pool_name", pool_name, "str", max_length=64, min_length=1, pattern=r"^[a-zA-Z0-9_-]+$" ), "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_disable_auto_scale_request( resource_group_name: str, account_name: str, pool_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-05-01")) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/pools/{poolName}/disableAutoScale", ) # pylint: disable=line-too-long path_format_arguments = { "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), "accountName": _SERIALIZER.url( "account_name", account_name, "str", max_length=24, min_length=3, pattern=r"^[a-zA-Z0-9]+$" ), "poolName": _SERIALIZER.url( "pool_name", pool_name, "str", max_length=64, min_length=1, pattern=r"^[a-zA-Z0-9_-]+$" ), "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) def build_stop_resize_request( resource_group_name: str, account_name: str, pool_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-05-01")) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/pools/{poolName}/stopResize", ) # pylint: disable=line-too-long path_format_arguments = { "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), "accountName": _SERIALIZER.url( "account_name", account_name, "str", max_length=24, min_length=3, pattern=r"^[a-zA-Z0-9]+$" ), "poolName": _SERIALIZER.url( "pool_name", pool_name, "str", max_length=64, min_length=1, pattern=r"^[a-zA-Z0-9_-]+$" ), "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) class PoolOperations: """ .. warning:: **DO NOT** instantiate this class directly. Instead, you should access the following operations through :class:`~azure.mgmt.batch.BatchManagementClient`'s :attr:`pool` attribute. """ models = _models def __init__(self, *args, **kwargs): input_args = list(args) self._client = input_args.pop(0) if input_args else kwargs.pop("client") self._config = input_args.pop(0) if input_args else kwargs.pop("config") self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace def list_by_batch_account( self, resource_group_name: str, account_name: str, maxresults: Optional[int] = None, select: Optional[str] = None, filter: Optional[str] = None, **kwargs: Any ) -> Iterable["_models.Pool"]: """Lists all of the pools in the specified account. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param maxresults: The maximum number of items to return in the response. Default value is None. :type maxresults: int :param select: Comma separated list of properties that should be returned. e.g. "properties/provisioningState". Only top level properties under properties/ are valid for selection. Default value is None. :type select: str :param filter: OData filter expression. Valid properties for filtering are: name properties/allocationState properties/allocationStateTransitionTime properties/creationTime properties/provisioningState properties/provisioningStateTransitionTime properties/lastModified properties/vmSize properties/interNodeCommunication properties/scaleSettings/autoScale properties/scaleSettings/fixedScale. Default value is None. :type filter: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either Pool or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.batch.models.Pool] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.ListPoolsResult] = kwargs.pop("cls", None) error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_by_batch_account_request( resource_group_name=resource_group_name, account_name=account_name, subscription_id=self._config.subscription_id, maxresults=maxresults, select=select, filter=filter, api_version=api_version, template_url=self.list_by_batch_account.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) else: # make call to next link with the client's api-version _parsed_next_link = urllib.parse.urlparse(next_link) _next_request_params = case_insensitive_dict( { key: [urllib.parse.quote(v) for v in value] for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) _next_request_params["api-version"] = self._config.api_version request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) request.url = self._client.format_url(request.url) request.method = "GET" return request def extract_data(pipeline_response): deserialized = self._deserialize("ListPoolsResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) # type: ignore return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return ItemPaged(get_next, extract_data) list_by_batch_account.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/pools" } @overload def create( self, resource_group_name: str, account_name: str, pool_name: str, parameters: _models.Pool, if_match: Optional[str] = None, if_none_match: Optional[str] = None, *, content_type: str = "application/json", **kwargs: Any ) -> _models.Pool: """Creates a new pool inside the specified account. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param pool_name: The pool name. This must be unique within the account. Required. :type pool_name: str :param parameters: Additional parameters for pool creation. Required. :type parameters: ~azure.mgmt.batch.models.Pool :param if_match: The entity state (ETag) version of the pool to update. A value of "*" can be used to apply the operation only if the pool already exists. If omitted, this operation will always be applied. Default value is None. :type if_match: str :param if_none_match: Set to '*' to allow a new pool to be created, but to prevent updating an existing pool. Other values will be ignored. Default value is None. :type if_none_match: str :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Pool or the result of cls(response) :rtype: ~azure.mgmt.batch.models.Pool :raises ~azure.core.exceptions.HttpResponseError: """ @overload def create( self, resource_group_name: str, account_name: str, pool_name: str, parameters: IO, if_match: Optional[str] = None, if_none_match: Optional[str] = None, *, content_type: str = "application/json", **kwargs: Any ) -> _models.Pool: """Creates a new pool inside the specified account. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param pool_name: The pool name. This must be unique within the account. Required. :type pool_name: str :param parameters: Additional parameters for pool creation. Required. :type parameters: IO :param if_match: The entity state (ETag) version of the pool to update. A value of "*" can be used to apply the operation only if the pool already exists. If omitted, this operation will always be applied. Default value is None. :type if_match: str :param if_none_match: Set to '*' to allow a new pool to be created, but to prevent updating an existing pool. Other values will be ignored. Default value is None. :type if_none_match: str :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Pool or the result of cls(response) :rtype: ~azure.mgmt.batch.models.Pool :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace def create( self, resource_group_name: str, account_name: str, pool_name: str, parameters: Union[_models.Pool, IO], if_match: Optional[str] = None, if_none_match: Optional[str] = None, **kwargs: Any ) -> _models.Pool: """Creates a new pool inside the specified account. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param pool_name: The pool name. This must be unique within the account. Required. :type pool_name: str :param parameters: Additional parameters for pool creation. Is either a Pool type or a IO type. Required. :type parameters: ~azure.mgmt.batch.models.Pool or IO :param if_match: The entity state (ETag) version of the pool to update. A value of "*" can be used to apply the operation only if the pool already exists. If omitted, this operation will always be applied. Default value is None. :type if_match: str :param if_none_match: Set to '*' to allow a new pool to be created, but to prevent updating an existing pool. Other values will be ignored. Default value is None. :type if_none_match: str :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. Default value is None. :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Pool or the result of cls(response) :rtype: ~azure.mgmt.batch.models.Pool :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.Pool] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None if isinstance(parameters, (IOBase, bytes)): _content = parameters else: _json = self._serialize.body(parameters, "Pool") request = build_create_request( resource_group_name=resource_group_name, account_name=account_name, pool_name=pool_name, subscription_id=self._config.subscription_id, if_match=if_match, if_none_match=if_none_match, api_version=api_version, content_type=content_type, json=_json, content=_content, template_url=self.create.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) response_headers = {} response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) deserialized = self._deserialize("Pool", pipeline_response) if cls: return cls(pipeline_response, deserialized, response_headers) return deserialized create.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/pools/{poolName}" } @overload def update( self, resource_group_name: str, account_name: str, pool_name: str, parameters: _models.Pool, if_match: Optional[str] = None, *, content_type: str = "application/json", **kwargs: Any ) -> _models.Pool: """Updates the properties of an existing pool. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param pool_name: The pool name. This must be unique within the account. Required. :type pool_name: str :param parameters: Pool properties that should be updated. Properties that are supplied will be updated, any property not supplied will be unchanged. Required. :type parameters: ~azure.mgmt.batch.models.Pool :param if_match: The entity state (ETag) version of the pool to update. This value can be omitted or set to "*" to apply the operation unconditionally. Default value is None. :type if_match: str :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Pool or the result of cls(response) :rtype: ~azure.mgmt.batch.models.Pool :raises ~azure.core.exceptions.HttpResponseError: """ @overload def update( self, resource_group_name: str, account_name: str, pool_name: str, parameters: IO, if_match: Optional[str] = None, *, content_type: str = "application/json", **kwargs: Any ) -> _models.Pool: """Updates the properties of an existing pool. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param pool_name: The pool name. This must be unique within the account. Required. :type pool_name: str :param parameters: Pool properties that should be updated. Properties that are supplied will be updated, any property not supplied will be unchanged. Required. :type parameters: IO :param if_match: The entity state (ETag) version of the pool to update. This value can be omitted or set to "*" to apply the operation unconditionally. Default value is None. :type if_match: str :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Pool or the result of cls(response) :rtype: ~azure.mgmt.batch.models.Pool :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace def update( self, resource_group_name: str, account_name: str, pool_name: str, parameters: Union[_models.Pool, IO], if_match: Optional[str] = None, **kwargs: Any ) -> _models.Pool: """Updates the properties of an existing pool. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param pool_name: The pool name. This must be unique within the account. Required. :type pool_name: str :param parameters: Pool properties that should be updated. Properties that are supplied will be updated, any property not supplied will be unchanged. Is either a Pool type or a IO type. Required. :type parameters: ~azure.mgmt.batch.models.Pool or IO :param if_match: The entity state (ETag) version of the pool to update. This value can be omitted or set to "*" to apply the operation unconditionally. Default value is None. :type if_match: str :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. Default value is None. :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Pool or the result of cls(response) :rtype: ~azure.mgmt.batch.models.Pool :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.Pool] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None if isinstance(parameters, (IOBase, bytes)): _content = parameters else: _json = self._serialize.body(parameters, "Pool") request = build_update_request( resource_group_name=resource_group_name, account_name=account_name, pool_name=pool_name, subscription_id=self._config.subscription_id, if_match=if_match, api_version=api_version, content_type=content_type, json=_json, content=_content, template_url=self.update.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) response_headers = {} response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) deserialized = self._deserialize("Pool", pipeline_response) if cls: return cls(pipeline_response, deserialized, response_headers) return deserialized update.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/pools/{poolName}" } def _delete_initial( # pylint: disable=inconsistent-return-statements self, resource_group_name: str, account_name: str, pool_name: str, **kwargs: Any ) -> None: error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[None] = kwargs.pop("cls", None) request = build_delete_request( resource_group_name=resource_group_name, account_name=account_name, pool_name=pool_name, subscription_id=self._config.subscription_id, api_version=api_version, template_url=self._delete_initial.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) response_headers = {} if response.status_code == 202: response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) if cls: return cls(pipeline_response, None, response_headers) _delete_initial.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/pools/{poolName}" } @distributed_trace def begin_delete( self, resource_group_name: str, account_name: str, pool_name: str, **kwargs: Any ) -> LROPoller[None]: """Deletes the specified pool. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param pool_name: The pool name. This must be unique within the account. Required. :type pool_name: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.PollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of LROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[None] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[None] = kwargs.pop("cls", None) polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) cont_token: Optional[str] = kwargs.pop("continuation_token", None) if cont_token is None: raw_result = self._delete_initial( # type: ignore resource_group_name=resource_group_name, account_name=account_name, pool_name=pool_name, api_version=api_version, cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) if polling is True: polling_method: PollingMethod = cast( PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) ) elif polling is False: polling_method = cast(PollingMethod, NoPolling()) else: polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) return LROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore begin_delete.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/pools/{poolName}" } @distributed_trace def get(self, resource_group_name: str, account_name: str, pool_name: str, **kwargs: Any) -> _models.Pool: """Gets information about the specified pool. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param pool_name: The pool name. This must be unique within the account. Required. :type pool_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Pool or the result of cls(response) :rtype: ~azure.mgmt.batch.models.Pool :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.Pool] = kwargs.pop("cls", None) request = build_get_request( resource_group_name=resource_group_name, account_name=account_name, pool_name=pool_name, subscription_id=self._config.subscription_id, api_version=api_version, template_url=self.get.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) response_headers = {} response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) deserialized = self._deserialize("Pool", pipeline_response) if cls: return cls(pipeline_response, deserialized, response_headers) return deserialized get.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/pools/{poolName}" } @distributed_trace def disable_auto_scale( self, resource_group_name: str, account_name: str, pool_name: str, **kwargs: Any ) -> _models.Pool: """Disables automatic scaling for a pool. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param pool_name: The pool name. This must be unique within the account. Required. :type pool_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Pool or the result of cls(response) :rtype: ~azure.mgmt.batch.models.Pool :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.Pool] = kwargs.pop("cls", None) request = build_disable_auto_scale_request( resource_group_name=resource_group_name, account_name=account_name, pool_name=pool_name, subscription_id=self._config.subscription_id, api_version=api_version, template_url=self.disable_auto_scale.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) response_headers = {} response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) deserialized = self._deserialize("Pool", pipeline_response) if cls: return cls(pipeline_response, deserialized, response_headers) return deserialized disable_auto_scale.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/pools/{poolName}/disableAutoScale" } @distributed_trace def stop_resize(self, resource_group_name: str, account_name: str, pool_name: str, **kwargs: Any) -> _models.Pool: """Stops an ongoing resize operation on the pool. This does not restore the pool to its previous state before the resize operation: it only stops any further changes being made, and the pool maintains its current state. After stopping, the pool stabilizes at the number of nodes it was at when the stop operation was done. During the stop operation, the pool allocation state changes first to stopping and then to steady. A resize operation need not be an explicit resize pool request; this API can also be used to halt the initial sizing of the pool when it is created. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param pool_name: The pool name. This must be unique within the account. Required. :type pool_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Pool or the result of cls(response) :rtype: ~azure.mgmt.batch.models.Pool :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.Pool] = kwargs.pop("cls", None) request = build_stop_resize_request( resource_group_name=resource_group_name, account_name=account_name, pool_name=pool_name, subscription_id=self._config.subscription_id, api_version=api_version, template_url=self.stop_resize.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) response_headers = {} response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) deserialized = self._deserialize("Pool", pipeline_response) if cls: return cls(pipeline_response, deserialized, response_headers) return deserialized stop_resize.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/pools/{poolName}/stopResize" }
azure-mgmt-batch
/azure_mgmt_batch-17.1.0-py3-none-any.whl/azure/mgmt/batch/operations/_pool_operations.py
_pool_operations.py
from io import IOBase from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, cast, overload import urllib.parse from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, map_error, ) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse from azure.core.polling import LROPoller, NoPolling, PollingMethod from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.arm_polling import ARMPolling from .. import models as _models from .._serialization import Serializer from .._vendor import _convert_request, _format_url_section T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False def build_list_by_batch_account_request( resource_group_name: str, account_name: str, subscription_id: str, *, maxresults: Optional[int] = None, select: Optional[str] = None, filter: Optional[str] = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-05-01")) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/pools", ) # pylint: disable=line-too-long path_format_arguments = { "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), "accountName": _SERIALIZER.url( "account_name", account_name, "str", max_length=24, min_length=3, pattern=r"^[a-zA-Z0-9]+$" ), "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # Construct parameters if maxresults is not None: _params["maxresults"] = _SERIALIZER.query("maxresults", maxresults, "int") if select is not None: _params["$select"] = _SERIALIZER.query("select", select, "str") if filter is not None: _params["$filter"] = _SERIALIZER.query("filter", filter, "str") _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_create_request( resource_group_name: str, account_name: str, pool_name: str, subscription_id: str, *, if_match: Optional[str] = None, if_none_match: Optional[str] = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-05-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/pools/{poolName}", ) # pylint: disable=line-too-long path_format_arguments = { "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), "accountName": _SERIALIZER.url( "account_name", account_name, "str", max_length=24, min_length=3, pattern=r"^[a-zA-Z0-9]+$" ), "poolName": _SERIALIZER.url( "pool_name", pool_name, "str", max_length=64, min_length=1, pattern=r"^[a-zA-Z0-9_-]+$" ), "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers if if_match is not None: _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") if if_none_match is not None: _headers["If-None-Match"] = _SERIALIZER.header("if_none_match", if_none_match, "str") if content_type is not None: _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) def build_update_request( resource_group_name: str, account_name: str, pool_name: str, subscription_id: str, *, if_match: Optional[str] = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-05-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/pools/{poolName}", ) # pylint: disable=line-too-long path_format_arguments = { "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), "accountName": _SERIALIZER.url( "account_name", account_name, "str", max_length=24, min_length=3, pattern=r"^[a-zA-Z0-9]+$" ), "poolName": _SERIALIZER.url( "pool_name", pool_name, "str", max_length=64, min_length=1, pattern=r"^[a-zA-Z0-9_-]+$" ), "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers if if_match is not None: _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") if content_type is not None: _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs) def build_delete_request( resource_group_name: str, account_name: str, pool_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-05-01")) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/pools/{poolName}", ) # pylint: disable=line-too-long path_format_arguments = { "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), "accountName": _SERIALIZER.url( "account_name", account_name, "str", max_length=24, min_length=3, pattern=r"^[a-zA-Z0-9]+$" ), "poolName": _SERIALIZER.url( "pool_name", pool_name, "str", max_length=64, min_length=1, pattern=r"^[a-zA-Z0-9_-]+$" ), "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) def build_get_request( resource_group_name: str, account_name: str, pool_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-05-01")) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/pools/{poolName}", ) # pylint: disable=line-too-long path_format_arguments = { "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), "accountName": _SERIALIZER.url( "account_name", account_name, "str", max_length=24, min_length=3, pattern=r"^[a-zA-Z0-9]+$" ), "poolName": _SERIALIZER.url( "pool_name", pool_name, "str", max_length=64, min_length=1, pattern=r"^[a-zA-Z0-9_-]+$" ), "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_disable_auto_scale_request( resource_group_name: str, account_name: str, pool_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-05-01")) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/pools/{poolName}/disableAutoScale", ) # pylint: disable=line-too-long path_format_arguments = { "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), "accountName": _SERIALIZER.url( "account_name", account_name, "str", max_length=24, min_length=3, pattern=r"^[a-zA-Z0-9]+$" ), "poolName": _SERIALIZER.url( "pool_name", pool_name, "str", max_length=64, min_length=1, pattern=r"^[a-zA-Z0-9_-]+$" ), "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) def build_stop_resize_request( resource_group_name: str, account_name: str, pool_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-05-01")) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/pools/{poolName}/stopResize", ) # pylint: disable=line-too-long path_format_arguments = { "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), "accountName": _SERIALIZER.url( "account_name", account_name, "str", max_length=24, min_length=3, pattern=r"^[a-zA-Z0-9]+$" ), "poolName": _SERIALIZER.url( "pool_name", pool_name, "str", max_length=64, min_length=1, pattern=r"^[a-zA-Z0-9_-]+$" ), "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) class PoolOperations: """ .. warning:: **DO NOT** instantiate this class directly. Instead, you should access the following operations through :class:`~azure.mgmt.batch.BatchManagementClient`'s :attr:`pool` attribute. """ models = _models def __init__(self, *args, **kwargs): input_args = list(args) self._client = input_args.pop(0) if input_args else kwargs.pop("client") self._config = input_args.pop(0) if input_args else kwargs.pop("config") self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace def list_by_batch_account( self, resource_group_name: str, account_name: str, maxresults: Optional[int] = None, select: Optional[str] = None, filter: Optional[str] = None, **kwargs: Any ) -> Iterable["_models.Pool"]: """Lists all of the pools in the specified account. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param maxresults: The maximum number of items to return in the response. Default value is None. :type maxresults: int :param select: Comma separated list of properties that should be returned. e.g. "properties/provisioningState". Only top level properties under properties/ are valid for selection. Default value is None. :type select: str :param filter: OData filter expression. Valid properties for filtering are: name properties/allocationState properties/allocationStateTransitionTime properties/creationTime properties/provisioningState properties/provisioningStateTransitionTime properties/lastModified properties/vmSize properties/interNodeCommunication properties/scaleSettings/autoScale properties/scaleSettings/fixedScale. Default value is None. :type filter: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either Pool or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.batch.models.Pool] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.ListPoolsResult] = kwargs.pop("cls", None) error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_by_batch_account_request( resource_group_name=resource_group_name, account_name=account_name, subscription_id=self._config.subscription_id, maxresults=maxresults, select=select, filter=filter, api_version=api_version, template_url=self.list_by_batch_account.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) else: # make call to next link with the client's api-version _parsed_next_link = urllib.parse.urlparse(next_link) _next_request_params = case_insensitive_dict( { key: [urllib.parse.quote(v) for v in value] for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) _next_request_params["api-version"] = self._config.api_version request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) request.url = self._client.format_url(request.url) request.method = "GET" return request def extract_data(pipeline_response): deserialized = self._deserialize("ListPoolsResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) # type: ignore return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return ItemPaged(get_next, extract_data) list_by_batch_account.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/pools" } @overload def create( self, resource_group_name: str, account_name: str, pool_name: str, parameters: _models.Pool, if_match: Optional[str] = None, if_none_match: Optional[str] = None, *, content_type: str = "application/json", **kwargs: Any ) -> _models.Pool: """Creates a new pool inside the specified account. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param pool_name: The pool name. This must be unique within the account. Required. :type pool_name: str :param parameters: Additional parameters for pool creation. Required. :type parameters: ~azure.mgmt.batch.models.Pool :param if_match: The entity state (ETag) version of the pool to update. A value of "*" can be used to apply the operation only if the pool already exists. If omitted, this operation will always be applied. Default value is None. :type if_match: str :param if_none_match: Set to '*' to allow a new pool to be created, but to prevent updating an existing pool. Other values will be ignored. Default value is None. :type if_none_match: str :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Pool or the result of cls(response) :rtype: ~azure.mgmt.batch.models.Pool :raises ~azure.core.exceptions.HttpResponseError: """ @overload def create( self, resource_group_name: str, account_name: str, pool_name: str, parameters: IO, if_match: Optional[str] = None, if_none_match: Optional[str] = None, *, content_type: str = "application/json", **kwargs: Any ) -> _models.Pool: """Creates a new pool inside the specified account. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param pool_name: The pool name. This must be unique within the account. Required. :type pool_name: str :param parameters: Additional parameters for pool creation. Required. :type parameters: IO :param if_match: The entity state (ETag) version of the pool to update. A value of "*" can be used to apply the operation only if the pool already exists. If omitted, this operation will always be applied. Default value is None. :type if_match: str :param if_none_match: Set to '*' to allow a new pool to be created, but to prevent updating an existing pool. Other values will be ignored. Default value is None. :type if_none_match: str :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Pool or the result of cls(response) :rtype: ~azure.mgmt.batch.models.Pool :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace def create( self, resource_group_name: str, account_name: str, pool_name: str, parameters: Union[_models.Pool, IO], if_match: Optional[str] = None, if_none_match: Optional[str] = None, **kwargs: Any ) -> _models.Pool: """Creates a new pool inside the specified account. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param pool_name: The pool name. This must be unique within the account. Required. :type pool_name: str :param parameters: Additional parameters for pool creation. Is either a Pool type or a IO type. Required. :type parameters: ~azure.mgmt.batch.models.Pool or IO :param if_match: The entity state (ETag) version of the pool to update. A value of "*" can be used to apply the operation only if the pool already exists. If omitted, this operation will always be applied. Default value is None. :type if_match: str :param if_none_match: Set to '*' to allow a new pool to be created, but to prevent updating an existing pool. Other values will be ignored. Default value is None. :type if_none_match: str :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. Default value is None. :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Pool or the result of cls(response) :rtype: ~azure.mgmt.batch.models.Pool :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.Pool] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None if isinstance(parameters, (IOBase, bytes)): _content = parameters else: _json = self._serialize.body(parameters, "Pool") request = build_create_request( resource_group_name=resource_group_name, account_name=account_name, pool_name=pool_name, subscription_id=self._config.subscription_id, if_match=if_match, if_none_match=if_none_match, api_version=api_version, content_type=content_type, json=_json, content=_content, template_url=self.create.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) response_headers = {} response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) deserialized = self._deserialize("Pool", pipeline_response) if cls: return cls(pipeline_response, deserialized, response_headers) return deserialized create.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/pools/{poolName}" } @overload def update( self, resource_group_name: str, account_name: str, pool_name: str, parameters: _models.Pool, if_match: Optional[str] = None, *, content_type: str = "application/json", **kwargs: Any ) -> _models.Pool: """Updates the properties of an existing pool. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param pool_name: The pool name. This must be unique within the account. Required. :type pool_name: str :param parameters: Pool properties that should be updated. Properties that are supplied will be updated, any property not supplied will be unchanged. Required. :type parameters: ~azure.mgmt.batch.models.Pool :param if_match: The entity state (ETag) version of the pool to update. This value can be omitted or set to "*" to apply the operation unconditionally. Default value is None. :type if_match: str :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Pool or the result of cls(response) :rtype: ~azure.mgmt.batch.models.Pool :raises ~azure.core.exceptions.HttpResponseError: """ @overload def update( self, resource_group_name: str, account_name: str, pool_name: str, parameters: IO, if_match: Optional[str] = None, *, content_type: str = "application/json", **kwargs: Any ) -> _models.Pool: """Updates the properties of an existing pool. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param pool_name: The pool name. This must be unique within the account. Required. :type pool_name: str :param parameters: Pool properties that should be updated. Properties that are supplied will be updated, any property not supplied will be unchanged. Required. :type parameters: IO :param if_match: The entity state (ETag) version of the pool to update. This value can be omitted or set to "*" to apply the operation unconditionally. Default value is None. :type if_match: str :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Pool or the result of cls(response) :rtype: ~azure.mgmt.batch.models.Pool :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace def update( self, resource_group_name: str, account_name: str, pool_name: str, parameters: Union[_models.Pool, IO], if_match: Optional[str] = None, **kwargs: Any ) -> _models.Pool: """Updates the properties of an existing pool. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param pool_name: The pool name. This must be unique within the account. Required. :type pool_name: str :param parameters: Pool properties that should be updated. Properties that are supplied will be updated, any property not supplied will be unchanged. Is either a Pool type or a IO type. Required. :type parameters: ~azure.mgmt.batch.models.Pool or IO :param if_match: The entity state (ETag) version of the pool to update. This value can be omitted or set to "*" to apply the operation unconditionally. Default value is None. :type if_match: str :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. Default value is None. :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Pool or the result of cls(response) :rtype: ~azure.mgmt.batch.models.Pool :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.Pool] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None if isinstance(parameters, (IOBase, bytes)): _content = parameters else: _json = self._serialize.body(parameters, "Pool") request = build_update_request( resource_group_name=resource_group_name, account_name=account_name, pool_name=pool_name, subscription_id=self._config.subscription_id, if_match=if_match, api_version=api_version, content_type=content_type, json=_json, content=_content, template_url=self.update.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) response_headers = {} response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) deserialized = self._deserialize("Pool", pipeline_response) if cls: return cls(pipeline_response, deserialized, response_headers) return deserialized update.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/pools/{poolName}" } def _delete_initial( # pylint: disable=inconsistent-return-statements self, resource_group_name: str, account_name: str, pool_name: str, **kwargs: Any ) -> None: error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[None] = kwargs.pop("cls", None) request = build_delete_request( resource_group_name=resource_group_name, account_name=account_name, pool_name=pool_name, subscription_id=self._config.subscription_id, api_version=api_version, template_url=self._delete_initial.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) response_headers = {} if response.status_code == 202: response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) if cls: return cls(pipeline_response, None, response_headers) _delete_initial.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/pools/{poolName}" } @distributed_trace def begin_delete( self, resource_group_name: str, account_name: str, pool_name: str, **kwargs: Any ) -> LROPoller[None]: """Deletes the specified pool. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param pool_name: The pool name. This must be unique within the account. Required. :type pool_name: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.PollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of LROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[None] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[None] = kwargs.pop("cls", None) polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) cont_token: Optional[str] = kwargs.pop("continuation_token", None) if cont_token is None: raw_result = self._delete_initial( # type: ignore resource_group_name=resource_group_name, account_name=account_name, pool_name=pool_name, api_version=api_version, cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) if polling is True: polling_method: PollingMethod = cast( PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) ) elif polling is False: polling_method = cast(PollingMethod, NoPolling()) else: polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) return LROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore begin_delete.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/pools/{poolName}" } @distributed_trace def get(self, resource_group_name: str, account_name: str, pool_name: str, **kwargs: Any) -> _models.Pool: """Gets information about the specified pool. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param pool_name: The pool name. This must be unique within the account. Required. :type pool_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Pool or the result of cls(response) :rtype: ~azure.mgmt.batch.models.Pool :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.Pool] = kwargs.pop("cls", None) request = build_get_request( resource_group_name=resource_group_name, account_name=account_name, pool_name=pool_name, subscription_id=self._config.subscription_id, api_version=api_version, template_url=self.get.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) response_headers = {} response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) deserialized = self._deserialize("Pool", pipeline_response) if cls: return cls(pipeline_response, deserialized, response_headers) return deserialized get.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/pools/{poolName}" } @distributed_trace def disable_auto_scale( self, resource_group_name: str, account_name: str, pool_name: str, **kwargs: Any ) -> _models.Pool: """Disables automatic scaling for a pool. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param pool_name: The pool name. This must be unique within the account. Required. :type pool_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Pool or the result of cls(response) :rtype: ~azure.mgmt.batch.models.Pool :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.Pool] = kwargs.pop("cls", None) request = build_disable_auto_scale_request( resource_group_name=resource_group_name, account_name=account_name, pool_name=pool_name, subscription_id=self._config.subscription_id, api_version=api_version, template_url=self.disable_auto_scale.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) response_headers = {} response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) deserialized = self._deserialize("Pool", pipeline_response) if cls: return cls(pipeline_response, deserialized, response_headers) return deserialized disable_auto_scale.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/pools/{poolName}/disableAutoScale" } @distributed_trace def stop_resize(self, resource_group_name: str, account_name: str, pool_name: str, **kwargs: Any) -> _models.Pool: """Stops an ongoing resize operation on the pool. This does not restore the pool to its previous state before the resize operation: it only stops any further changes being made, and the pool maintains its current state. After stopping, the pool stabilizes at the number of nodes it was at when the stop operation was done. During the stop operation, the pool allocation state changes first to stopping and then to steady. A resize operation need not be an explicit resize pool request; this API can also be used to halt the initial sizing of the pool when it is created. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param pool_name: The pool name. This must be unique within the account. Required. :type pool_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Pool or the result of cls(response) :rtype: ~azure.mgmt.batch.models.Pool :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.Pool] = kwargs.pop("cls", None) request = build_stop_resize_request( resource_group_name=resource_group_name, account_name=account_name, pool_name=pool_name, subscription_id=self._config.subscription_id, api_version=api_version, template_url=self.stop_resize.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) response_headers = {} response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) deserialized = self._deserialize("Pool", pipeline_response) if cls: return cls(pipeline_response, deserialized, response_headers) return deserialized stop_resize.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/pools/{poolName}/stopResize" }
0.784402
0.082143
from io import IOBase from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, cast, overload import urllib.parse from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, map_error, ) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse from azure.core.polling import LROPoller, NoPolling, PollingMethod from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.arm_polling import ARMPolling from .. import models as _models from .._serialization import Serializer from .._vendor import _convert_request, _format_url_section T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False def build_create_request( resource_group_name: str, account_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-05-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}", ) # pylint: disable=line-too-long path_format_arguments = { "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), "accountName": _SERIALIZER.url( "account_name", account_name, "str", max_length=24, min_length=3, pattern=r"^[a-z0-9]+$" ), "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers if content_type is not None: _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) def build_update_request( resource_group_name: str, account_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-05-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}", ) # pylint: disable=line-too-long path_format_arguments = { "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), "accountName": _SERIALIZER.url( "account_name", account_name, "str", max_length=24, min_length=3, pattern=r"^[a-zA-Z0-9]+$" ), "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers if content_type is not None: _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs) def build_delete_request( resource_group_name: str, account_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-05-01")) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}", ) # pylint: disable=line-too-long path_format_arguments = { "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), "accountName": _SERIALIZER.url( "account_name", account_name, "str", max_length=24, min_length=3, pattern=r"^[a-zA-Z0-9]+$" ), "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) def build_get_request(resource_group_name: str, account_name: str, subscription_id: str, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-05-01")) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}", ) # pylint: disable=line-too-long path_format_arguments = { "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), "accountName": _SERIALIZER.url( "account_name", account_name, "str", max_length=24, min_length=3, pattern=r"^[a-zA-Z0-9]+$" ), "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_list_request(subscription_id: str, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-05-01")) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Batch/batchAccounts") path_format_arguments = { "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_list_by_resource_group_request(resource_group_name: str, subscription_id: str, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-05-01")) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts", ) # pylint: disable=line-too-long path_format_arguments = { "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_synchronize_auto_storage_keys_request( resource_group_name: str, account_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-05-01")) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/syncAutoStorageKeys", ) # pylint: disable=line-too-long path_format_arguments = { "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), "accountName": _SERIALIZER.url( "account_name", account_name, "str", max_length=24, min_length=3, pattern=r"^[a-zA-Z0-9]+$" ), "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) def build_regenerate_key_request( resource_group_name: str, account_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-05-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/regenerateKeys", ) # pylint: disable=line-too-long path_format_arguments = { "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), "accountName": _SERIALIZER.url( "account_name", account_name, "str", max_length=24, min_length=3, pattern=r"^[a-zA-Z0-9]+$" ), "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers if content_type is not None: _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) def build_get_keys_request( resource_group_name: str, account_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-05-01")) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/listKeys", ) # pylint: disable=line-too-long path_format_arguments = { "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), "accountName": _SERIALIZER.url( "account_name", account_name, "str", max_length=24, min_length=3, pattern=r"^[a-zA-Z0-9]+$" ), "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) def build_list_detectors_request( resource_group_name: str, account_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-05-01")) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/detectors", ) # pylint: disable=line-too-long path_format_arguments = { "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), "accountName": _SERIALIZER.url( "account_name", account_name, "str", max_length=24, min_length=3, pattern=r"^[a-zA-Z0-9]+$" ), } _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_get_detector_request( resource_group_name: str, account_name: str, detector_id: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-05-01")) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/detectors/{detectorId}", ) # pylint: disable=line-too-long path_format_arguments = { "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), "accountName": _SERIALIZER.url( "account_name", account_name, "str", max_length=24, min_length=3, pattern=r"^[a-zA-Z0-9]+$" ), "detectorId": _SERIALIZER.url("detector_id", detector_id, "str"), } _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_list_outbound_network_dependencies_endpoints_request( resource_group_name: str, account_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-05-01")) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/outboundNetworkDependenciesEndpoints", ) # pylint: disable=line-too-long path_format_arguments = { "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), "accountName": _SERIALIZER.url( "account_name", account_name, "str", max_length=24, min_length=3, pattern=r"^[a-zA-Z0-9]+$" ), "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) class BatchAccountOperations: """ .. warning:: **DO NOT** instantiate this class directly. Instead, you should access the following operations through :class:`~azure.mgmt.batch.BatchManagementClient`'s :attr:`batch_account` attribute. """ models = _models def __init__(self, *args, **kwargs): input_args = list(args) self._client = input_args.pop(0) if input_args else kwargs.pop("client") self._config = input_args.pop(0) if input_args else kwargs.pop("config") self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") def _create_initial( self, resource_group_name: str, account_name: str, parameters: Union[_models.BatchAccountCreateParameters, IO], **kwargs: Any ) -> Optional[_models.BatchAccount]: error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[Optional[_models.BatchAccount]] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None if isinstance(parameters, (IOBase, bytes)): _content = parameters else: _json = self._serialize.body(parameters, "BatchAccountCreateParameters") request = build_create_request( resource_group_name=resource_group_name, account_name=account_name, subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, content=_content, template_url=self._create_initial.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = None response_headers = {} if response.status_code == 200: deserialized = self._deserialize("BatchAccount", pipeline_response) if response.status_code == 202: response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) if cls: return cls(pipeline_response, deserialized, response_headers) return deserialized _create_initial.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}" } @overload def begin_create( self, resource_group_name: str, account_name: str, parameters: _models.BatchAccountCreateParameters, *, content_type: str = "application/json", **kwargs: Any ) -> LROPoller[_models.BatchAccount]: """Creates a new Batch account with the specified parameters. Existing accounts cannot be updated with this API and should instead be updated with the Update Batch Account API. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: A name for the Batch account which must be unique within the region. Batch account names must be between 3 and 24 characters in length and must use only numbers and lowercase letters. This name is used as part of the DNS name that is used to access the Batch service in the region in which the account is created. For example: http://accountname.region.batch.azure.com/. Required. :type account_name: str :param parameters: Additional parameters for account creation. Required. :type parameters: ~azure.mgmt.batch.models.BatchAccountCreateParameters :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.PollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of LROPoller that returns either BatchAccount or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.batch.models.BatchAccount] :raises ~azure.core.exceptions.HttpResponseError: """ @overload def begin_create( self, resource_group_name: str, account_name: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any ) -> LROPoller[_models.BatchAccount]: """Creates a new Batch account with the specified parameters. Existing accounts cannot be updated with this API and should instead be updated with the Update Batch Account API. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: A name for the Batch account which must be unique within the region. Batch account names must be between 3 and 24 characters in length and must use only numbers and lowercase letters. This name is used as part of the DNS name that is used to access the Batch service in the region in which the account is created. For example: http://accountname.region.batch.azure.com/. Required. :type account_name: str :param parameters: Additional parameters for account creation. Required. :type parameters: IO :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.PollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of LROPoller that returns either BatchAccount or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.batch.models.BatchAccount] :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace def begin_create( self, resource_group_name: str, account_name: str, parameters: Union[_models.BatchAccountCreateParameters, IO], **kwargs: Any ) -> LROPoller[_models.BatchAccount]: """Creates a new Batch account with the specified parameters. Existing accounts cannot be updated with this API and should instead be updated with the Update Batch Account API. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: A name for the Batch account which must be unique within the region. Batch account names must be between 3 and 24 characters in length and must use only numbers and lowercase letters. This name is used as part of the DNS name that is used to access the Batch service in the region in which the account is created. For example: http://accountname.region.batch.azure.com/. Required. :type account_name: str :param parameters: Additional parameters for account creation. Is either a BatchAccountCreateParameters type or a IO type. Required. :type parameters: ~azure.mgmt.batch.models.BatchAccountCreateParameters or IO :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. Default value is None. :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.PollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of LROPoller that returns either BatchAccount or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.batch.models.BatchAccount] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.BatchAccount] = kwargs.pop("cls", None) polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) cont_token: Optional[str] = kwargs.pop("continuation_token", None) if cont_token is None: raw_result = self._create_initial( resource_group_name=resource_group_name, account_name=account_name, parameters=parameters, api_version=api_version, content_type=content_type, cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): deserialized = self._deserialize("BatchAccount", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized if polling is True: polling_method: PollingMethod = cast( PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) ) elif polling is False: polling_method = cast(PollingMethod, NoPolling()) else: polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) return LROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore begin_create.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}" } @overload def update( self, resource_group_name: str, account_name: str, parameters: _models.BatchAccountUpdateParameters, *, content_type: str = "application/json", **kwargs: Any ) -> _models.BatchAccount: """Updates the properties of an existing Batch account. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param parameters: Additional parameters for account update. Required. :type parameters: ~azure.mgmt.batch.models.BatchAccountUpdateParameters :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: BatchAccount or the result of cls(response) :rtype: ~azure.mgmt.batch.models.BatchAccount :raises ~azure.core.exceptions.HttpResponseError: """ @overload def update( self, resource_group_name: str, account_name: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any ) -> _models.BatchAccount: """Updates the properties of an existing Batch account. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param parameters: Additional parameters for account update. Required. :type parameters: IO :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: BatchAccount or the result of cls(response) :rtype: ~azure.mgmt.batch.models.BatchAccount :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace def update( self, resource_group_name: str, account_name: str, parameters: Union[_models.BatchAccountUpdateParameters, IO], **kwargs: Any ) -> _models.BatchAccount: """Updates the properties of an existing Batch account. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param parameters: Additional parameters for account update. Is either a BatchAccountUpdateParameters type or a IO type. Required. :type parameters: ~azure.mgmt.batch.models.BatchAccountUpdateParameters or IO :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. Default value is None. :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: BatchAccount or the result of cls(response) :rtype: ~azure.mgmt.batch.models.BatchAccount :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.BatchAccount] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None if isinstance(parameters, (IOBase, bytes)): _content = parameters else: _json = self._serialize.body(parameters, "BatchAccountUpdateParameters") request = build_update_request( resource_group_name=resource_group_name, account_name=account_name, subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, content=_content, template_url=self.update.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize("BatchAccount", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized update.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}" } def _delete_initial( # pylint: disable=inconsistent-return-statements self, resource_group_name: str, account_name: str, **kwargs: Any ) -> None: error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[None] = kwargs.pop("cls", None) request = build_delete_request( resource_group_name=resource_group_name, account_name=account_name, subscription_id=self._config.subscription_id, api_version=api_version, template_url=self._delete_initial.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) response_headers = {} if response.status_code == 202: response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) if cls: return cls(pipeline_response, None, response_headers) _delete_initial.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}" } @distributed_trace def begin_delete(self, resource_group_name: str, account_name: str, **kwargs: Any) -> LROPoller[None]: """Deletes the specified Batch account. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.PollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of LROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[None] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[None] = kwargs.pop("cls", None) polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) cont_token: Optional[str] = kwargs.pop("continuation_token", None) if cont_token is None: raw_result = self._delete_initial( # type: ignore resource_group_name=resource_group_name, account_name=account_name, api_version=api_version, cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) if polling is True: polling_method: PollingMethod = cast( PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) ) elif polling is False: polling_method = cast(PollingMethod, NoPolling()) else: polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) return LROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore begin_delete.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}" } @distributed_trace def get(self, resource_group_name: str, account_name: str, **kwargs: Any) -> _models.BatchAccount: """Gets information about the specified Batch account. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: BatchAccount or the result of cls(response) :rtype: ~azure.mgmt.batch.models.BatchAccount :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.BatchAccount] = kwargs.pop("cls", None) request = build_get_request( resource_group_name=resource_group_name, account_name=account_name, subscription_id=self._config.subscription_id, api_version=api_version, template_url=self.get.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize("BatchAccount", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}" } @distributed_trace def list(self, **kwargs: Any) -> Iterable["_models.BatchAccount"]: """Gets information about the Batch accounts associated with the subscription. :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either BatchAccount or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.batch.models.BatchAccount] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.BatchAccountListResult] = kwargs.pop("cls", None) error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_request( subscription_id=self._config.subscription_id, api_version=api_version, template_url=self.list.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) else: # make call to next link with the client's api-version _parsed_next_link = urllib.parse.urlparse(next_link) _next_request_params = case_insensitive_dict( { key: [urllib.parse.quote(v) for v in value] for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) _next_request_params["api-version"] = self._config.api_version request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) request.url = self._client.format_url(request.url) request.method = "GET" return request def extract_data(pipeline_response): deserialized = self._deserialize("BatchAccountListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) # type: ignore return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return ItemPaged(get_next, extract_data) list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Batch/batchAccounts"} @distributed_trace def list_by_resource_group(self, resource_group_name: str, **kwargs: Any) -> Iterable["_models.BatchAccount"]: """Gets information about the Batch accounts associated with the specified resource group. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either BatchAccount or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.batch.models.BatchAccount] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.BatchAccountListResult] = kwargs.pop("cls", None) error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_by_resource_group_request( resource_group_name=resource_group_name, subscription_id=self._config.subscription_id, api_version=api_version, template_url=self.list_by_resource_group.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) else: # make call to next link with the client's api-version _parsed_next_link = urllib.parse.urlparse(next_link) _next_request_params = case_insensitive_dict( { key: [urllib.parse.quote(v) for v in value] for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) _next_request_params["api-version"] = self._config.api_version request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) request.url = self._client.format_url(request.url) request.method = "GET" return request def extract_data(pipeline_response): deserialized = self._deserialize("BatchAccountListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) # type: ignore return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return ItemPaged(get_next, extract_data) list_by_resource_group.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts" } @distributed_trace def synchronize_auto_storage_keys( # pylint: disable=inconsistent-return-statements self, resource_group_name: str, account_name: str, **kwargs: Any ) -> None: """Synchronizes access keys for the auto-storage account configured for the specified Batch account, only if storage key authentication is being used. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: None or the result of cls(response) :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[None] = kwargs.pop("cls", None) request = build_synchronize_auto_storage_keys_request( resource_group_name=resource_group_name, account_name=account_name, subscription_id=self._config.subscription_id, api_version=api_version, template_url=self.synchronize_auto_storage_keys.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [204]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) synchronize_auto_storage_keys.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/syncAutoStorageKeys" } @overload def regenerate_key( self, resource_group_name: str, account_name: str, parameters: _models.BatchAccountRegenerateKeyParameters, *, content_type: str = "application/json", **kwargs: Any ) -> _models.BatchAccountKeys: """Regenerates the specified account key for the Batch account. This operation applies only to Batch accounts with allowedAuthenticationModes containing 'SharedKey'. If the Batch account doesn't contain 'SharedKey' in its allowedAuthenticationMode, clients cannot use shared keys to authenticate, and must use another allowedAuthenticationModes instead. In this case, regenerating the keys will fail. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param parameters: The type of key to regenerate. Required. :type parameters: ~azure.mgmt.batch.models.BatchAccountRegenerateKeyParameters :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: BatchAccountKeys or the result of cls(response) :rtype: ~azure.mgmt.batch.models.BatchAccountKeys :raises ~azure.core.exceptions.HttpResponseError: """ @overload def regenerate_key( self, resource_group_name: str, account_name: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any ) -> _models.BatchAccountKeys: """Regenerates the specified account key for the Batch account. This operation applies only to Batch accounts with allowedAuthenticationModes containing 'SharedKey'. If the Batch account doesn't contain 'SharedKey' in its allowedAuthenticationMode, clients cannot use shared keys to authenticate, and must use another allowedAuthenticationModes instead. In this case, regenerating the keys will fail. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param parameters: The type of key to regenerate. Required. :type parameters: IO :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: BatchAccountKeys or the result of cls(response) :rtype: ~azure.mgmt.batch.models.BatchAccountKeys :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace def regenerate_key( self, resource_group_name: str, account_name: str, parameters: Union[_models.BatchAccountRegenerateKeyParameters, IO], **kwargs: Any ) -> _models.BatchAccountKeys: """Regenerates the specified account key for the Batch account. This operation applies only to Batch accounts with allowedAuthenticationModes containing 'SharedKey'. If the Batch account doesn't contain 'SharedKey' in its allowedAuthenticationMode, clients cannot use shared keys to authenticate, and must use another allowedAuthenticationModes instead. In this case, regenerating the keys will fail. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param parameters: The type of key to regenerate. Is either a BatchAccountRegenerateKeyParameters type or a IO type. Required. :type parameters: ~azure.mgmt.batch.models.BatchAccountRegenerateKeyParameters or IO :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. Default value is None. :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: BatchAccountKeys or the result of cls(response) :rtype: ~azure.mgmt.batch.models.BatchAccountKeys :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.BatchAccountKeys] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None if isinstance(parameters, (IOBase, bytes)): _content = parameters else: _json = self._serialize.body(parameters, "BatchAccountRegenerateKeyParameters") request = build_regenerate_key_request( resource_group_name=resource_group_name, account_name=account_name, subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, content=_content, template_url=self.regenerate_key.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize("BatchAccountKeys", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized regenerate_key.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/regenerateKeys" } @distributed_trace def get_keys(self, resource_group_name: str, account_name: str, **kwargs: Any) -> _models.BatchAccountKeys: """Gets the account keys for the specified Batch account. This operation applies only to Batch accounts with allowedAuthenticationModes containing 'SharedKey'. If the Batch account doesn't contain 'SharedKey' in its allowedAuthenticationMode, clients cannot use shared keys to authenticate, and must use another allowedAuthenticationModes instead. In this case, getting the keys will fail. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: BatchAccountKeys or the result of cls(response) :rtype: ~azure.mgmt.batch.models.BatchAccountKeys :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.BatchAccountKeys] = kwargs.pop("cls", None) request = build_get_keys_request( resource_group_name=resource_group_name, account_name=account_name, subscription_id=self._config.subscription_id, api_version=api_version, template_url=self.get_keys.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize("BatchAccountKeys", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get_keys.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/listKeys" } @distributed_trace def list_detectors( self, resource_group_name: str, account_name: str, **kwargs: Any ) -> Iterable["_models.DetectorResponse"]: """Gets information about the detectors available for a given Batch account. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either DetectorResponse or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.batch.models.DetectorResponse] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.DetectorListResult] = kwargs.pop("cls", None) error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_detectors_request( resource_group_name=resource_group_name, account_name=account_name, subscription_id=self._config.subscription_id, api_version=api_version, template_url=self.list_detectors.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) else: # make call to next link with the client's api-version _parsed_next_link = urllib.parse.urlparse(next_link) _next_request_params = case_insensitive_dict( { key: [urllib.parse.quote(v) for v in value] for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) _next_request_params["api-version"] = self._config.api_version request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) request.url = self._client.format_url(request.url) request.method = "GET" return request def extract_data(pipeline_response): deserialized = self._deserialize("DetectorListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) # type: ignore return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return ItemPaged(get_next, extract_data) list_detectors.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/detectors" } @distributed_trace def get_detector( self, resource_group_name: str, account_name: str, detector_id: str, **kwargs: Any ) -> _models.DetectorResponse: """Gets information about the given detector for a given Batch account. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param detector_id: The name of the detector. Required. :type detector_id: str :keyword callable cls: A custom type or function that will be passed the direct response :return: DetectorResponse or the result of cls(response) :rtype: ~azure.mgmt.batch.models.DetectorResponse :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.DetectorResponse] = kwargs.pop("cls", None) request = build_get_detector_request( resource_group_name=resource_group_name, account_name=account_name, detector_id=detector_id, subscription_id=self._config.subscription_id, api_version=api_version, template_url=self.get_detector.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize("DetectorResponse", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get_detector.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/detectors/{detectorId}" } @distributed_trace def list_outbound_network_dependencies_endpoints( self, resource_group_name: str, account_name: str, **kwargs: Any ) -> Iterable["_models.OutboundEnvironmentEndpoint"]: """Lists the endpoints that a Batch Compute Node under this Batch Account may call as part of Batch service administration. If you are deploying a Pool inside of a virtual network that you specify, you must make sure your network allows outbound access to these endpoints. Failure to allow access to these endpoints may cause Batch to mark the affected nodes as unusable. For more information about creating a pool inside of a virtual network, see https://docs.microsoft.com/en-us/azure/batch/batch-virtual-network. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either OutboundEnvironmentEndpoint or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.batch.models.OutboundEnvironmentEndpoint] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.OutboundEnvironmentEndpointCollection] = kwargs.pop("cls", None) error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_outbound_network_dependencies_endpoints_request( resource_group_name=resource_group_name, account_name=account_name, subscription_id=self._config.subscription_id, api_version=api_version, template_url=self.list_outbound_network_dependencies_endpoints.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) else: # make call to next link with the client's api-version _parsed_next_link = urllib.parse.urlparse(next_link) _next_request_params = case_insensitive_dict( { key: [urllib.parse.quote(v) for v in value] for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) _next_request_params["api-version"] = self._config.api_version request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) request.url = self._client.format_url(request.url) request.method = "GET" return request def extract_data(pipeline_response): deserialized = self._deserialize("OutboundEnvironmentEndpointCollection", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) # type: ignore return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return ItemPaged(get_next, extract_data) list_outbound_network_dependencies_endpoints.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/outboundNetworkDependenciesEndpoints" }
azure-mgmt-batch
/azure_mgmt_batch-17.1.0-py3-none-any.whl/azure/mgmt/batch/operations/_batch_account_operations.py
_batch_account_operations.py
from io import IOBase from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, cast, overload import urllib.parse from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, map_error, ) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse from azure.core.polling import LROPoller, NoPolling, PollingMethod from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.arm_polling import ARMPolling from .. import models as _models from .._serialization import Serializer from .._vendor import _convert_request, _format_url_section T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False def build_create_request( resource_group_name: str, account_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-05-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}", ) # pylint: disable=line-too-long path_format_arguments = { "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), "accountName": _SERIALIZER.url( "account_name", account_name, "str", max_length=24, min_length=3, pattern=r"^[a-z0-9]+$" ), "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers if content_type is not None: _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) def build_update_request( resource_group_name: str, account_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-05-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}", ) # pylint: disable=line-too-long path_format_arguments = { "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), "accountName": _SERIALIZER.url( "account_name", account_name, "str", max_length=24, min_length=3, pattern=r"^[a-zA-Z0-9]+$" ), "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers if content_type is not None: _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs) def build_delete_request( resource_group_name: str, account_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-05-01")) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}", ) # pylint: disable=line-too-long path_format_arguments = { "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), "accountName": _SERIALIZER.url( "account_name", account_name, "str", max_length=24, min_length=3, pattern=r"^[a-zA-Z0-9]+$" ), "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) def build_get_request(resource_group_name: str, account_name: str, subscription_id: str, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-05-01")) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}", ) # pylint: disable=line-too-long path_format_arguments = { "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), "accountName": _SERIALIZER.url( "account_name", account_name, "str", max_length=24, min_length=3, pattern=r"^[a-zA-Z0-9]+$" ), "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_list_request(subscription_id: str, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-05-01")) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Batch/batchAccounts") path_format_arguments = { "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_list_by_resource_group_request(resource_group_name: str, subscription_id: str, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-05-01")) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts", ) # pylint: disable=line-too-long path_format_arguments = { "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_synchronize_auto_storage_keys_request( resource_group_name: str, account_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-05-01")) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/syncAutoStorageKeys", ) # pylint: disable=line-too-long path_format_arguments = { "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), "accountName": _SERIALIZER.url( "account_name", account_name, "str", max_length=24, min_length=3, pattern=r"^[a-zA-Z0-9]+$" ), "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) def build_regenerate_key_request( resource_group_name: str, account_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-05-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/regenerateKeys", ) # pylint: disable=line-too-long path_format_arguments = { "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), "accountName": _SERIALIZER.url( "account_name", account_name, "str", max_length=24, min_length=3, pattern=r"^[a-zA-Z0-9]+$" ), "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers if content_type is not None: _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) def build_get_keys_request( resource_group_name: str, account_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-05-01")) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/listKeys", ) # pylint: disable=line-too-long path_format_arguments = { "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), "accountName": _SERIALIZER.url( "account_name", account_name, "str", max_length=24, min_length=3, pattern=r"^[a-zA-Z0-9]+$" ), "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) def build_list_detectors_request( resource_group_name: str, account_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-05-01")) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/detectors", ) # pylint: disable=line-too-long path_format_arguments = { "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), "accountName": _SERIALIZER.url( "account_name", account_name, "str", max_length=24, min_length=3, pattern=r"^[a-zA-Z0-9]+$" ), } _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_get_detector_request( resource_group_name: str, account_name: str, detector_id: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-05-01")) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/detectors/{detectorId}", ) # pylint: disable=line-too-long path_format_arguments = { "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), "accountName": _SERIALIZER.url( "account_name", account_name, "str", max_length=24, min_length=3, pattern=r"^[a-zA-Z0-9]+$" ), "detectorId": _SERIALIZER.url("detector_id", detector_id, "str"), } _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_list_outbound_network_dependencies_endpoints_request( resource_group_name: str, account_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-05-01")) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/outboundNetworkDependenciesEndpoints", ) # pylint: disable=line-too-long path_format_arguments = { "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), "accountName": _SERIALIZER.url( "account_name", account_name, "str", max_length=24, min_length=3, pattern=r"^[a-zA-Z0-9]+$" ), "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) class BatchAccountOperations: """ .. warning:: **DO NOT** instantiate this class directly. Instead, you should access the following operations through :class:`~azure.mgmt.batch.BatchManagementClient`'s :attr:`batch_account` attribute. """ models = _models def __init__(self, *args, **kwargs): input_args = list(args) self._client = input_args.pop(0) if input_args else kwargs.pop("client") self._config = input_args.pop(0) if input_args else kwargs.pop("config") self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") def _create_initial( self, resource_group_name: str, account_name: str, parameters: Union[_models.BatchAccountCreateParameters, IO], **kwargs: Any ) -> Optional[_models.BatchAccount]: error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[Optional[_models.BatchAccount]] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None if isinstance(parameters, (IOBase, bytes)): _content = parameters else: _json = self._serialize.body(parameters, "BatchAccountCreateParameters") request = build_create_request( resource_group_name=resource_group_name, account_name=account_name, subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, content=_content, template_url=self._create_initial.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = None response_headers = {} if response.status_code == 200: deserialized = self._deserialize("BatchAccount", pipeline_response) if response.status_code == 202: response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) if cls: return cls(pipeline_response, deserialized, response_headers) return deserialized _create_initial.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}" } @overload def begin_create( self, resource_group_name: str, account_name: str, parameters: _models.BatchAccountCreateParameters, *, content_type: str = "application/json", **kwargs: Any ) -> LROPoller[_models.BatchAccount]: """Creates a new Batch account with the specified parameters. Existing accounts cannot be updated with this API and should instead be updated with the Update Batch Account API. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: A name for the Batch account which must be unique within the region. Batch account names must be between 3 and 24 characters in length and must use only numbers and lowercase letters. This name is used as part of the DNS name that is used to access the Batch service in the region in which the account is created. For example: http://accountname.region.batch.azure.com/. Required. :type account_name: str :param parameters: Additional parameters for account creation. Required. :type parameters: ~azure.mgmt.batch.models.BatchAccountCreateParameters :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.PollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of LROPoller that returns either BatchAccount or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.batch.models.BatchAccount] :raises ~azure.core.exceptions.HttpResponseError: """ @overload def begin_create( self, resource_group_name: str, account_name: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any ) -> LROPoller[_models.BatchAccount]: """Creates a new Batch account with the specified parameters. Existing accounts cannot be updated with this API and should instead be updated with the Update Batch Account API. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: A name for the Batch account which must be unique within the region. Batch account names must be between 3 and 24 characters in length and must use only numbers and lowercase letters. This name is used as part of the DNS name that is used to access the Batch service in the region in which the account is created. For example: http://accountname.region.batch.azure.com/. Required. :type account_name: str :param parameters: Additional parameters for account creation. Required. :type parameters: IO :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.PollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of LROPoller that returns either BatchAccount or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.batch.models.BatchAccount] :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace def begin_create( self, resource_group_name: str, account_name: str, parameters: Union[_models.BatchAccountCreateParameters, IO], **kwargs: Any ) -> LROPoller[_models.BatchAccount]: """Creates a new Batch account with the specified parameters. Existing accounts cannot be updated with this API and should instead be updated with the Update Batch Account API. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: A name for the Batch account which must be unique within the region. Batch account names must be between 3 and 24 characters in length and must use only numbers and lowercase letters. This name is used as part of the DNS name that is used to access the Batch service in the region in which the account is created. For example: http://accountname.region.batch.azure.com/. Required. :type account_name: str :param parameters: Additional parameters for account creation. Is either a BatchAccountCreateParameters type or a IO type. Required. :type parameters: ~azure.mgmt.batch.models.BatchAccountCreateParameters or IO :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. Default value is None. :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.PollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of LROPoller that returns either BatchAccount or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.batch.models.BatchAccount] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.BatchAccount] = kwargs.pop("cls", None) polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) cont_token: Optional[str] = kwargs.pop("continuation_token", None) if cont_token is None: raw_result = self._create_initial( resource_group_name=resource_group_name, account_name=account_name, parameters=parameters, api_version=api_version, content_type=content_type, cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): deserialized = self._deserialize("BatchAccount", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized if polling is True: polling_method: PollingMethod = cast( PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) ) elif polling is False: polling_method = cast(PollingMethod, NoPolling()) else: polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) return LROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore begin_create.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}" } @overload def update( self, resource_group_name: str, account_name: str, parameters: _models.BatchAccountUpdateParameters, *, content_type: str = "application/json", **kwargs: Any ) -> _models.BatchAccount: """Updates the properties of an existing Batch account. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param parameters: Additional parameters for account update. Required. :type parameters: ~azure.mgmt.batch.models.BatchAccountUpdateParameters :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: BatchAccount or the result of cls(response) :rtype: ~azure.mgmt.batch.models.BatchAccount :raises ~azure.core.exceptions.HttpResponseError: """ @overload def update( self, resource_group_name: str, account_name: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any ) -> _models.BatchAccount: """Updates the properties of an existing Batch account. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param parameters: Additional parameters for account update. Required. :type parameters: IO :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: BatchAccount or the result of cls(response) :rtype: ~azure.mgmt.batch.models.BatchAccount :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace def update( self, resource_group_name: str, account_name: str, parameters: Union[_models.BatchAccountUpdateParameters, IO], **kwargs: Any ) -> _models.BatchAccount: """Updates the properties of an existing Batch account. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param parameters: Additional parameters for account update. Is either a BatchAccountUpdateParameters type or a IO type. Required. :type parameters: ~azure.mgmt.batch.models.BatchAccountUpdateParameters or IO :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. Default value is None. :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: BatchAccount or the result of cls(response) :rtype: ~azure.mgmt.batch.models.BatchAccount :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.BatchAccount] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None if isinstance(parameters, (IOBase, bytes)): _content = parameters else: _json = self._serialize.body(parameters, "BatchAccountUpdateParameters") request = build_update_request( resource_group_name=resource_group_name, account_name=account_name, subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, content=_content, template_url=self.update.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize("BatchAccount", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized update.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}" } def _delete_initial( # pylint: disable=inconsistent-return-statements self, resource_group_name: str, account_name: str, **kwargs: Any ) -> None: error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[None] = kwargs.pop("cls", None) request = build_delete_request( resource_group_name=resource_group_name, account_name=account_name, subscription_id=self._config.subscription_id, api_version=api_version, template_url=self._delete_initial.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) response_headers = {} if response.status_code == 202: response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) if cls: return cls(pipeline_response, None, response_headers) _delete_initial.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}" } @distributed_trace def begin_delete(self, resource_group_name: str, account_name: str, **kwargs: Any) -> LROPoller[None]: """Deletes the specified Batch account. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.PollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of LROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[None] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[None] = kwargs.pop("cls", None) polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) cont_token: Optional[str] = kwargs.pop("continuation_token", None) if cont_token is None: raw_result = self._delete_initial( # type: ignore resource_group_name=resource_group_name, account_name=account_name, api_version=api_version, cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) if polling is True: polling_method: PollingMethod = cast( PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) ) elif polling is False: polling_method = cast(PollingMethod, NoPolling()) else: polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) return LROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore begin_delete.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}" } @distributed_trace def get(self, resource_group_name: str, account_name: str, **kwargs: Any) -> _models.BatchAccount: """Gets information about the specified Batch account. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: BatchAccount or the result of cls(response) :rtype: ~azure.mgmt.batch.models.BatchAccount :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.BatchAccount] = kwargs.pop("cls", None) request = build_get_request( resource_group_name=resource_group_name, account_name=account_name, subscription_id=self._config.subscription_id, api_version=api_version, template_url=self.get.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize("BatchAccount", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}" } @distributed_trace def list(self, **kwargs: Any) -> Iterable["_models.BatchAccount"]: """Gets information about the Batch accounts associated with the subscription. :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either BatchAccount or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.batch.models.BatchAccount] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.BatchAccountListResult] = kwargs.pop("cls", None) error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_request( subscription_id=self._config.subscription_id, api_version=api_version, template_url=self.list.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) else: # make call to next link with the client's api-version _parsed_next_link = urllib.parse.urlparse(next_link) _next_request_params = case_insensitive_dict( { key: [urllib.parse.quote(v) for v in value] for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) _next_request_params["api-version"] = self._config.api_version request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) request.url = self._client.format_url(request.url) request.method = "GET" return request def extract_data(pipeline_response): deserialized = self._deserialize("BatchAccountListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) # type: ignore return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return ItemPaged(get_next, extract_data) list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Batch/batchAccounts"} @distributed_trace def list_by_resource_group(self, resource_group_name: str, **kwargs: Any) -> Iterable["_models.BatchAccount"]: """Gets information about the Batch accounts associated with the specified resource group. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either BatchAccount or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.batch.models.BatchAccount] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.BatchAccountListResult] = kwargs.pop("cls", None) error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_by_resource_group_request( resource_group_name=resource_group_name, subscription_id=self._config.subscription_id, api_version=api_version, template_url=self.list_by_resource_group.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) else: # make call to next link with the client's api-version _parsed_next_link = urllib.parse.urlparse(next_link) _next_request_params = case_insensitive_dict( { key: [urllib.parse.quote(v) for v in value] for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) _next_request_params["api-version"] = self._config.api_version request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) request.url = self._client.format_url(request.url) request.method = "GET" return request def extract_data(pipeline_response): deserialized = self._deserialize("BatchAccountListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) # type: ignore return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return ItemPaged(get_next, extract_data) list_by_resource_group.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts" } @distributed_trace def synchronize_auto_storage_keys( # pylint: disable=inconsistent-return-statements self, resource_group_name: str, account_name: str, **kwargs: Any ) -> None: """Synchronizes access keys for the auto-storage account configured for the specified Batch account, only if storage key authentication is being used. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: None or the result of cls(response) :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[None] = kwargs.pop("cls", None) request = build_synchronize_auto_storage_keys_request( resource_group_name=resource_group_name, account_name=account_name, subscription_id=self._config.subscription_id, api_version=api_version, template_url=self.synchronize_auto_storage_keys.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [204]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) synchronize_auto_storage_keys.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/syncAutoStorageKeys" } @overload def regenerate_key( self, resource_group_name: str, account_name: str, parameters: _models.BatchAccountRegenerateKeyParameters, *, content_type: str = "application/json", **kwargs: Any ) -> _models.BatchAccountKeys: """Regenerates the specified account key for the Batch account. This operation applies only to Batch accounts with allowedAuthenticationModes containing 'SharedKey'. If the Batch account doesn't contain 'SharedKey' in its allowedAuthenticationMode, clients cannot use shared keys to authenticate, and must use another allowedAuthenticationModes instead. In this case, regenerating the keys will fail. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param parameters: The type of key to regenerate. Required. :type parameters: ~azure.mgmt.batch.models.BatchAccountRegenerateKeyParameters :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: BatchAccountKeys or the result of cls(response) :rtype: ~azure.mgmt.batch.models.BatchAccountKeys :raises ~azure.core.exceptions.HttpResponseError: """ @overload def regenerate_key( self, resource_group_name: str, account_name: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any ) -> _models.BatchAccountKeys: """Regenerates the specified account key for the Batch account. This operation applies only to Batch accounts with allowedAuthenticationModes containing 'SharedKey'. If the Batch account doesn't contain 'SharedKey' in its allowedAuthenticationMode, clients cannot use shared keys to authenticate, and must use another allowedAuthenticationModes instead. In this case, regenerating the keys will fail. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param parameters: The type of key to regenerate. Required. :type parameters: IO :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: BatchAccountKeys or the result of cls(response) :rtype: ~azure.mgmt.batch.models.BatchAccountKeys :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace def regenerate_key( self, resource_group_name: str, account_name: str, parameters: Union[_models.BatchAccountRegenerateKeyParameters, IO], **kwargs: Any ) -> _models.BatchAccountKeys: """Regenerates the specified account key for the Batch account. This operation applies only to Batch accounts with allowedAuthenticationModes containing 'SharedKey'. If the Batch account doesn't contain 'SharedKey' in its allowedAuthenticationMode, clients cannot use shared keys to authenticate, and must use another allowedAuthenticationModes instead. In this case, regenerating the keys will fail. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param parameters: The type of key to regenerate. Is either a BatchAccountRegenerateKeyParameters type or a IO type. Required. :type parameters: ~azure.mgmt.batch.models.BatchAccountRegenerateKeyParameters or IO :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. Default value is None. :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: BatchAccountKeys or the result of cls(response) :rtype: ~azure.mgmt.batch.models.BatchAccountKeys :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.BatchAccountKeys] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None if isinstance(parameters, (IOBase, bytes)): _content = parameters else: _json = self._serialize.body(parameters, "BatchAccountRegenerateKeyParameters") request = build_regenerate_key_request( resource_group_name=resource_group_name, account_name=account_name, subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, content=_content, template_url=self.regenerate_key.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize("BatchAccountKeys", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized regenerate_key.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/regenerateKeys" } @distributed_trace def get_keys(self, resource_group_name: str, account_name: str, **kwargs: Any) -> _models.BatchAccountKeys: """Gets the account keys for the specified Batch account. This operation applies only to Batch accounts with allowedAuthenticationModes containing 'SharedKey'. If the Batch account doesn't contain 'SharedKey' in its allowedAuthenticationMode, clients cannot use shared keys to authenticate, and must use another allowedAuthenticationModes instead. In this case, getting the keys will fail. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: BatchAccountKeys or the result of cls(response) :rtype: ~azure.mgmt.batch.models.BatchAccountKeys :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.BatchAccountKeys] = kwargs.pop("cls", None) request = build_get_keys_request( resource_group_name=resource_group_name, account_name=account_name, subscription_id=self._config.subscription_id, api_version=api_version, template_url=self.get_keys.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize("BatchAccountKeys", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get_keys.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/listKeys" } @distributed_trace def list_detectors( self, resource_group_name: str, account_name: str, **kwargs: Any ) -> Iterable["_models.DetectorResponse"]: """Gets information about the detectors available for a given Batch account. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either DetectorResponse or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.batch.models.DetectorResponse] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.DetectorListResult] = kwargs.pop("cls", None) error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_detectors_request( resource_group_name=resource_group_name, account_name=account_name, subscription_id=self._config.subscription_id, api_version=api_version, template_url=self.list_detectors.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) else: # make call to next link with the client's api-version _parsed_next_link = urllib.parse.urlparse(next_link) _next_request_params = case_insensitive_dict( { key: [urllib.parse.quote(v) for v in value] for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) _next_request_params["api-version"] = self._config.api_version request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) request.url = self._client.format_url(request.url) request.method = "GET" return request def extract_data(pipeline_response): deserialized = self._deserialize("DetectorListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) # type: ignore return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return ItemPaged(get_next, extract_data) list_detectors.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/detectors" } @distributed_trace def get_detector( self, resource_group_name: str, account_name: str, detector_id: str, **kwargs: Any ) -> _models.DetectorResponse: """Gets information about the given detector for a given Batch account. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param detector_id: The name of the detector. Required. :type detector_id: str :keyword callable cls: A custom type or function that will be passed the direct response :return: DetectorResponse or the result of cls(response) :rtype: ~azure.mgmt.batch.models.DetectorResponse :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.DetectorResponse] = kwargs.pop("cls", None) request = build_get_detector_request( resource_group_name=resource_group_name, account_name=account_name, detector_id=detector_id, subscription_id=self._config.subscription_id, api_version=api_version, template_url=self.get_detector.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize("DetectorResponse", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get_detector.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/detectors/{detectorId}" } @distributed_trace def list_outbound_network_dependencies_endpoints( self, resource_group_name: str, account_name: str, **kwargs: Any ) -> Iterable["_models.OutboundEnvironmentEndpoint"]: """Lists the endpoints that a Batch Compute Node under this Batch Account may call as part of Batch service administration. If you are deploying a Pool inside of a virtual network that you specify, you must make sure your network allows outbound access to these endpoints. Failure to allow access to these endpoints may cause Batch to mark the affected nodes as unusable. For more information about creating a pool inside of a virtual network, see https://docs.microsoft.com/en-us/azure/batch/batch-virtual-network. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either OutboundEnvironmentEndpoint or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.batch.models.OutboundEnvironmentEndpoint] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.OutboundEnvironmentEndpointCollection] = kwargs.pop("cls", None) error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_outbound_network_dependencies_endpoints_request( resource_group_name=resource_group_name, account_name=account_name, subscription_id=self._config.subscription_id, api_version=api_version, template_url=self.list_outbound_network_dependencies_endpoints.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) else: # make call to next link with the client's api-version _parsed_next_link = urllib.parse.urlparse(next_link) _next_request_params = case_insensitive_dict( { key: [urllib.parse.quote(v) for v in value] for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) _next_request_params["api-version"] = self._config.api_version request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) request.url = self._client.format_url(request.url) request.method = "GET" return request def extract_data(pipeline_response): deserialized = self._deserialize("OutboundEnvironmentEndpointCollection", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) # type: ignore return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return ItemPaged(get_next, extract_data) list_outbound_network_dependencies_endpoints.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/outboundNetworkDependenciesEndpoints" }
0.776623
0.066934
from typing import Any, Callable, Dict, Iterable, Optional, TypeVar import urllib.parse from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, map_error, ) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models from .._serialization import Serializer from .._vendor import _convert_request, _format_url_section T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False def build_list_by_batch_account_request( resource_group_name: str, account_name: str, subscription_id: str, *, maxresults: Optional[int] = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-05-01")) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/privateLinkResources", ) # pylint: disable=line-too-long path_format_arguments = { "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), "accountName": _SERIALIZER.url( "account_name", account_name, "str", max_length=24, min_length=3, pattern=r"^[a-zA-Z0-9]+$" ), } _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if maxresults is not None: _params["maxresults"] = _SERIALIZER.query("maxresults", maxresults, "int") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_get_request( resource_group_name: str, account_name: str, private_link_resource_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-05-01")) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/privateLinkResources/{privateLinkResourceName}", ) # pylint: disable=line-too-long path_format_arguments = { "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), "accountName": _SERIALIZER.url( "account_name", account_name, "str", max_length=24, min_length=3, pattern=r"^[a-zA-Z0-9]+$" ), "privateLinkResourceName": _SERIALIZER.url( "private_link_resource_name", private_link_resource_name, "str", max_length=101, min_length=1, pattern=r"^[a-zA-Z0-9_-]+\.?[a-fA-F0-9-]*$", ), } _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) class PrivateLinkResourceOperations: """ .. warning:: **DO NOT** instantiate this class directly. Instead, you should access the following operations through :class:`~azure.mgmt.batch.BatchManagementClient`'s :attr:`private_link_resource` attribute. """ models = _models def __init__(self, *args, **kwargs): input_args = list(args) self._client = input_args.pop(0) if input_args else kwargs.pop("client") self._config = input_args.pop(0) if input_args else kwargs.pop("config") self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace def list_by_batch_account( self, resource_group_name: str, account_name: str, maxresults: Optional[int] = None, **kwargs: Any ) -> Iterable["_models.PrivateLinkResource"]: """Lists all of the private link resources in the specified account. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param maxresults: The maximum number of items to return in the response. Default value is None. :type maxresults: int :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either PrivateLinkResource or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.batch.models.PrivateLinkResource] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.ListPrivateLinkResourcesResult] = kwargs.pop("cls", None) error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_by_batch_account_request( resource_group_name=resource_group_name, account_name=account_name, subscription_id=self._config.subscription_id, maxresults=maxresults, api_version=api_version, template_url=self.list_by_batch_account.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) else: # make call to next link with the client's api-version _parsed_next_link = urllib.parse.urlparse(next_link) _next_request_params = case_insensitive_dict( { key: [urllib.parse.quote(v) for v in value] for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) _next_request_params["api-version"] = self._config.api_version request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) request.url = self._client.format_url(request.url) request.method = "GET" return request def extract_data(pipeline_response): deserialized = self._deserialize("ListPrivateLinkResourcesResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) # type: ignore return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return ItemPaged(get_next, extract_data) list_by_batch_account.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/privateLinkResources" } @distributed_trace def get( self, resource_group_name: str, account_name: str, private_link_resource_name: str, **kwargs: Any ) -> _models.PrivateLinkResource: """Gets information about the specified private link resource. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param private_link_resource_name: The private link resource name. This must be unique within the account. Required. :type private_link_resource_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: PrivateLinkResource or the result of cls(response) :rtype: ~azure.mgmt.batch.models.PrivateLinkResource :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.PrivateLinkResource] = kwargs.pop("cls", None) request = build_get_request( resource_group_name=resource_group_name, account_name=account_name, private_link_resource_name=private_link_resource_name, subscription_id=self._config.subscription_id, api_version=api_version, template_url=self.get.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize("PrivateLinkResource", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/privateLinkResources/{privateLinkResourceName}" }
azure-mgmt-batch
/azure_mgmt_batch-17.1.0-py3-none-any.whl/azure/mgmt/batch/operations/_private_link_resource_operations.py
_private_link_resource_operations.py
from typing import Any, Callable, Dict, Iterable, Optional, TypeVar import urllib.parse from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, map_error, ) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models from .._serialization import Serializer from .._vendor import _convert_request, _format_url_section T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False def build_list_by_batch_account_request( resource_group_name: str, account_name: str, subscription_id: str, *, maxresults: Optional[int] = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-05-01")) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/privateLinkResources", ) # pylint: disable=line-too-long path_format_arguments = { "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), "accountName": _SERIALIZER.url( "account_name", account_name, "str", max_length=24, min_length=3, pattern=r"^[a-zA-Z0-9]+$" ), } _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if maxresults is not None: _params["maxresults"] = _SERIALIZER.query("maxresults", maxresults, "int") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_get_request( resource_group_name: str, account_name: str, private_link_resource_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-05-01")) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/privateLinkResources/{privateLinkResourceName}", ) # pylint: disable=line-too-long path_format_arguments = { "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), "accountName": _SERIALIZER.url( "account_name", account_name, "str", max_length=24, min_length=3, pattern=r"^[a-zA-Z0-9]+$" ), "privateLinkResourceName": _SERIALIZER.url( "private_link_resource_name", private_link_resource_name, "str", max_length=101, min_length=1, pattern=r"^[a-zA-Z0-9_-]+\.?[a-fA-F0-9-]*$", ), } _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) class PrivateLinkResourceOperations: """ .. warning:: **DO NOT** instantiate this class directly. Instead, you should access the following operations through :class:`~azure.mgmt.batch.BatchManagementClient`'s :attr:`private_link_resource` attribute. """ models = _models def __init__(self, *args, **kwargs): input_args = list(args) self._client = input_args.pop(0) if input_args else kwargs.pop("client") self._config = input_args.pop(0) if input_args else kwargs.pop("config") self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace def list_by_batch_account( self, resource_group_name: str, account_name: str, maxresults: Optional[int] = None, **kwargs: Any ) -> Iterable["_models.PrivateLinkResource"]: """Lists all of the private link resources in the specified account. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param maxresults: The maximum number of items to return in the response. Default value is None. :type maxresults: int :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either PrivateLinkResource or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.batch.models.PrivateLinkResource] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.ListPrivateLinkResourcesResult] = kwargs.pop("cls", None) error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_by_batch_account_request( resource_group_name=resource_group_name, account_name=account_name, subscription_id=self._config.subscription_id, maxresults=maxresults, api_version=api_version, template_url=self.list_by_batch_account.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) else: # make call to next link with the client's api-version _parsed_next_link = urllib.parse.urlparse(next_link) _next_request_params = case_insensitive_dict( { key: [urllib.parse.quote(v) for v in value] for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) _next_request_params["api-version"] = self._config.api_version request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) request.url = self._client.format_url(request.url) request.method = "GET" return request def extract_data(pipeline_response): deserialized = self._deserialize("ListPrivateLinkResourcesResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) # type: ignore return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return ItemPaged(get_next, extract_data) list_by_batch_account.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/privateLinkResources" } @distributed_trace def get( self, resource_group_name: str, account_name: str, private_link_resource_name: str, **kwargs: Any ) -> _models.PrivateLinkResource: """Gets information about the specified private link resource. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param private_link_resource_name: The private link resource name. This must be unique within the account. Required. :type private_link_resource_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: PrivateLinkResource or the result of cls(response) :rtype: ~azure.mgmt.batch.models.PrivateLinkResource :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.PrivateLinkResource] = kwargs.pop("cls", None) request = build_get_request( resource_group_name=resource_group_name, account_name=account_name, private_link_resource_name=private_link_resource_name, subscription_id=self._config.subscription_id, api_version=api_version, template_url=self.get.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize("PrivateLinkResource", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/privateLinkResources/{privateLinkResourceName}" }
0.867836
0.074871
from io import IOBase from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, overload import urllib.parse from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, map_error, ) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models from .._serialization import Serializer from .._vendor import _convert_request, _format_url_section T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False def build_create_request( resource_group_name: str, account_name: str, application_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-05-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/applications/{applicationName}", ) # pylint: disable=line-too-long path_format_arguments = { "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), "accountName": _SERIALIZER.url( "account_name", account_name, "str", max_length=24, min_length=3, pattern=r"^[a-zA-Z0-9]+$" ), "applicationName": _SERIALIZER.url( "application_name", application_name, "str", max_length=64, min_length=1, pattern=r"^[a-zA-Z0-9_-]+$" ), "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers if content_type is not None: _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) def build_delete_request( resource_group_name: str, account_name: str, application_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-05-01")) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/applications/{applicationName}", ) # pylint: disable=line-too-long path_format_arguments = { "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), "accountName": _SERIALIZER.url( "account_name", account_name, "str", max_length=24, min_length=3, pattern=r"^[a-zA-Z0-9]+$" ), "applicationName": _SERIALIZER.url( "application_name", application_name, "str", max_length=64, min_length=1, pattern=r"^[a-zA-Z0-9_-]+$" ), "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) def build_get_request( resource_group_name: str, account_name: str, application_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-05-01")) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/applications/{applicationName}", ) # pylint: disable=line-too-long path_format_arguments = { "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), "accountName": _SERIALIZER.url( "account_name", account_name, "str", max_length=24, min_length=3, pattern=r"^[a-zA-Z0-9]+$" ), "applicationName": _SERIALIZER.url( "application_name", application_name, "str", max_length=64, min_length=1, pattern=r"^[a-zA-Z0-9_-]+$" ), "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_update_request( resource_group_name: str, account_name: str, application_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-05-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/applications/{applicationName}", ) # pylint: disable=line-too-long path_format_arguments = { "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), "accountName": _SERIALIZER.url( "account_name", account_name, "str", max_length=24, min_length=3, pattern=r"^[a-zA-Z0-9]+$" ), "applicationName": _SERIALIZER.url( "application_name", application_name, "str", max_length=64, min_length=1, pattern=r"^[a-zA-Z0-9_-]+$" ), "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers if content_type is not None: _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs) def build_list_request( resource_group_name: str, account_name: str, subscription_id: str, *, maxresults: Optional[int] = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-05-01")) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/applications", ) # pylint: disable=line-too-long path_format_arguments = { "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), "accountName": _SERIALIZER.url( "account_name", account_name, "str", max_length=24, min_length=3, pattern=r"^[a-zA-Z0-9]+$" ), "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # Construct parameters if maxresults is not None: _params["maxresults"] = _SERIALIZER.query("maxresults", maxresults, "int") _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) class ApplicationOperations: """ .. warning:: **DO NOT** instantiate this class directly. Instead, you should access the following operations through :class:`~azure.mgmt.batch.BatchManagementClient`'s :attr:`application` attribute. """ models = _models def __init__(self, *args, **kwargs): input_args = list(args) self._client = input_args.pop(0) if input_args else kwargs.pop("client") self._config = input_args.pop(0) if input_args else kwargs.pop("config") self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @overload def create( self, resource_group_name: str, account_name: str, application_name: str, parameters: Optional[_models.Application] = None, *, content_type: str = "application/json", **kwargs: Any ) -> _models.Application: """Adds an application to the specified Batch account. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param application_name: The name of the application. This must be unique within the account. Required. :type application_name: str :param parameters: The parameters for the request. Default value is None. :type parameters: ~azure.mgmt.batch.models.Application :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Application or the result of cls(response) :rtype: ~azure.mgmt.batch.models.Application :raises ~azure.core.exceptions.HttpResponseError: """ @overload def create( self, resource_group_name: str, account_name: str, application_name: str, parameters: Optional[IO] = None, *, content_type: str = "application/json", **kwargs: Any ) -> _models.Application: """Adds an application to the specified Batch account. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param application_name: The name of the application. This must be unique within the account. Required. :type application_name: str :param parameters: The parameters for the request. Default value is None. :type parameters: IO :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Application or the result of cls(response) :rtype: ~azure.mgmt.batch.models.Application :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace def create( self, resource_group_name: str, account_name: str, application_name: str, parameters: Optional[Union[_models.Application, IO]] = None, **kwargs: Any ) -> _models.Application: """Adds an application to the specified Batch account. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param application_name: The name of the application. This must be unique within the account. Required. :type application_name: str :param parameters: The parameters for the request. Is either a Application type or a IO type. Default value is None. :type parameters: ~azure.mgmt.batch.models.Application or IO :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. Default value is None. :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Application or the result of cls(response) :rtype: ~azure.mgmt.batch.models.Application :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.Application] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None if isinstance(parameters, (IOBase, bytes)): _content = parameters else: if parameters is not None: _json = self._serialize.body(parameters, "Application") else: _json = None request = build_create_request( resource_group_name=resource_group_name, account_name=account_name, application_name=application_name, subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, content=_content, template_url=self.create.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize("Application", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized create.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/applications/{applicationName}" } @distributed_trace def delete( # pylint: disable=inconsistent-return-statements self, resource_group_name: str, account_name: str, application_name: str, **kwargs: Any ) -> None: """Deletes an application. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param application_name: The name of the application. This must be unique within the account. Required. :type application_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: None or the result of cls(response) :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[None] = kwargs.pop("cls", None) request = build_delete_request( resource_group_name=resource_group_name, account_name=account_name, application_name=application_name, subscription_id=self._config.subscription_id, api_version=api_version, template_url=self.delete.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) delete.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/applications/{applicationName}" } @distributed_trace def get( self, resource_group_name: str, account_name: str, application_name: str, **kwargs: Any ) -> _models.Application: """Gets information about the specified application. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param application_name: The name of the application. This must be unique within the account. Required. :type application_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Application or the result of cls(response) :rtype: ~azure.mgmt.batch.models.Application :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.Application] = kwargs.pop("cls", None) request = build_get_request( resource_group_name=resource_group_name, account_name=account_name, application_name=application_name, subscription_id=self._config.subscription_id, api_version=api_version, template_url=self.get.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize("Application", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/applications/{applicationName}" } @overload def update( self, resource_group_name: str, account_name: str, application_name: str, parameters: _models.Application, *, content_type: str = "application/json", **kwargs: Any ) -> _models.Application: """Updates settings for the specified application. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param application_name: The name of the application. This must be unique within the account. Required. :type application_name: str :param parameters: The parameters for the request. Required. :type parameters: ~azure.mgmt.batch.models.Application :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Application or the result of cls(response) :rtype: ~azure.mgmt.batch.models.Application :raises ~azure.core.exceptions.HttpResponseError: """ @overload def update( self, resource_group_name: str, account_name: str, application_name: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any ) -> _models.Application: """Updates settings for the specified application. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param application_name: The name of the application. This must be unique within the account. Required. :type application_name: str :param parameters: The parameters for the request. Required. :type parameters: IO :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Application or the result of cls(response) :rtype: ~azure.mgmt.batch.models.Application :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace def update( self, resource_group_name: str, account_name: str, application_name: str, parameters: Union[_models.Application, IO], **kwargs: Any ) -> _models.Application: """Updates settings for the specified application. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param application_name: The name of the application. This must be unique within the account. Required. :type application_name: str :param parameters: The parameters for the request. Is either a Application type or a IO type. Required. :type parameters: ~azure.mgmt.batch.models.Application or IO :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. Default value is None. :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Application or the result of cls(response) :rtype: ~azure.mgmt.batch.models.Application :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.Application] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None if isinstance(parameters, (IOBase, bytes)): _content = parameters else: _json = self._serialize.body(parameters, "Application") request = build_update_request( resource_group_name=resource_group_name, account_name=account_name, application_name=application_name, subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, content=_content, template_url=self.update.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize("Application", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized update.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/applications/{applicationName}" } @distributed_trace def list( self, resource_group_name: str, account_name: str, maxresults: Optional[int] = None, **kwargs: Any ) -> Iterable["_models.Application"]: """Lists all of the applications in the specified account. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param maxresults: The maximum number of items to return in the response. Default value is None. :type maxresults: int :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either Application or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.batch.models.Application] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.ListApplicationsResult] = kwargs.pop("cls", None) error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_request( resource_group_name=resource_group_name, account_name=account_name, subscription_id=self._config.subscription_id, maxresults=maxresults, api_version=api_version, template_url=self.list.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) else: # make call to next link with the client's api-version _parsed_next_link = urllib.parse.urlparse(next_link) _next_request_params = case_insensitive_dict( { key: [urllib.parse.quote(v) for v in value] for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) _next_request_params["api-version"] = self._config.api_version request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) request.url = self._client.format_url(request.url) request.method = "GET" return request def extract_data(pipeline_response): deserialized = self._deserialize("ListApplicationsResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) # type: ignore return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return ItemPaged(get_next, extract_data) list.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/applications" }
azure-mgmt-batch
/azure_mgmt_batch-17.1.0-py3-none-any.whl/azure/mgmt/batch/operations/_application_operations.py
_application_operations.py
from io import IOBase from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, overload import urllib.parse from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, map_error, ) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models from .._serialization import Serializer from .._vendor import _convert_request, _format_url_section T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False def build_create_request( resource_group_name: str, account_name: str, application_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-05-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/applications/{applicationName}", ) # pylint: disable=line-too-long path_format_arguments = { "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), "accountName": _SERIALIZER.url( "account_name", account_name, "str", max_length=24, min_length=3, pattern=r"^[a-zA-Z0-9]+$" ), "applicationName": _SERIALIZER.url( "application_name", application_name, "str", max_length=64, min_length=1, pattern=r"^[a-zA-Z0-9_-]+$" ), "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers if content_type is not None: _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) def build_delete_request( resource_group_name: str, account_name: str, application_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-05-01")) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/applications/{applicationName}", ) # pylint: disable=line-too-long path_format_arguments = { "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), "accountName": _SERIALIZER.url( "account_name", account_name, "str", max_length=24, min_length=3, pattern=r"^[a-zA-Z0-9]+$" ), "applicationName": _SERIALIZER.url( "application_name", application_name, "str", max_length=64, min_length=1, pattern=r"^[a-zA-Z0-9_-]+$" ), "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) def build_get_request( resource_group_name: str, account_name: str, application_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-05-01")) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/applications/{applicationName}", ) # pylint: disable=line-too-long path_format_arguments = { "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), "accountName": _SERIALIZER.url( "account_name", account_name, "str", max_length=24, min_length=3, pattern=r"^[a-zA-Z0-9]+$" ), "applicationName": _SERIALIZER.url( "application_name", application_name, "str", max_length=64, min_length=1, pattern=r"^[a-zA-Z0-9_-]+$" ), "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_update_request( resource_group_name: str, account_name: str, application_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-05-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/applications/{applicationName}", ) # pylint: disable=line-too-long path_format_arguments = { "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), "accountName": _SERIALIZER.url( "account_name", account_name, "str", max_length=24, min_length=3, pattern=r"^[a-zA-Z0-9]+$" ), "applicationName": _SERIALIZER.url( "application_name", application_name, "str", max_length=64, min_length=1, pattern=r"^[a-zA-Z0-9_-]+$" ), "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers if content_type is not None: _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs) def build_list_request( resource_group_name: str, account_name: str, subscription_id: str, *, maxresults: Optional[int] = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-05-01")) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/applications", ) # pylint: disable=line-too-long path_format_arguments = { "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), "accountName": _SERIALIZER.url( "account_name", account_name, "str", max_length=24, min_length=3, pattern=r"^[a-zA-Z0-9]+$" ), "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # Construct parameters if maxresults is not None: _params["maxresults"] = _SERIALIZER.query("maxresults", maxresults, "int") _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) class ApplicationOperations: """ .. warning:: **DO NOT** instantiate this class directly. Instead, you should access the following operations through :class:`~azure.mgmt.batch.BatchManagementClient`'s :attr:`application` attribute. """ models = _models def __init__(self, *args, **kwargs): input_args = list(args) self._client = input_args.pop(0) if input_args else kwargs.pop("client") self._config = input_args.pop(0) if input_args else kwargs.pop("config") self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @overload def create( self, resource_group_name: str, account_name: str, application_name: str, parameters: Optional[_models.Application] = None, *, content_type: str = "application/json", **kwargs: Any ) -> _models.Application: """Adds an application to the specified Batch account. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param application_name: The name of the application. This must be unique within the account. Required. :type application_name: str :param parameters: The parameters for the request. Default value is None. :type parameters: ~azure.mgmt.batch.models.Application :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Application or the result of cls(response) :rtype: ~azure.mgmt.batch.models.Application :raises ~azure.core.exceptions.HttpResponseError: """ @overload def create( self, resource_group_name: str, account_name: str, application_name: str, parameters: Optional[IO] = None, *, content_type: str = "application/json", **kwargs: Any ) -> _models.Application: """Adds an application to the specified Batch account. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param application_name: The name of the application. This must be unique within the account. Required. :type application_name: str :param parameters: The parameters for the request. Default value is None. :type parameters: IO :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Application or the result of cls(response) :rtype: ~azure.mgmt.batch.models.Application :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace def create( self, resource_group_name: str, account_name: str, application_name: str, parameters: Optional[Union[_models.Application, IO]] = None, **kwargs: Any ) -> _models.Application: """Adds an application to the specified Batch account. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param application_name: The name of the application. This must be unique within the account. Required. :type application_name: str :param parameters: The parameters for the request. Is either a Application type or a IO type. Default value is None. :type parameters: ~azure.mgmt.batch.models.Application or IO :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. Default value is None. :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Application or the result of cls(response) :rtype: ~azure.mgmt.batch.models.Application :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.Application] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None if isinstance(parameters, (IOBase, bytes)): _content = parameters else: if parameters is not None: _json = self._serialize.body(parameters, "Application") else: _json = None request = build_create_request( resource_group_name=resource_group_name, account_name=account_name, application_name=application_name, subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, content=_content, template_url=self.create.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize("Application", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized create.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/applications/{applicationName}" } @distributed_trace def delete( # pylint: disable=inconsistent-return-statements self, resource_group_name: str, account_name: str, application_name: str, **kwargs: Any ) -> None: """Deletes an application. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param application_name: The name of the application. This must be unique within the account. Required. :type application_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: None or the result of cls(response) :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[None] = kwargs.pop("cls", None) request = build_delete_request( resource_group_name=resource_group_name, account_name=account_name, application_name=application_name, subscription_id=self._config.subscription_id, api_version=api_version, template_url=self.delete.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) delete.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/applications/{applicationName}" } @distributed_trace def get( self, resource_group_name: str, account_name: str, application_name: str, **kwargs: Any ) -> _models.Application: """Gets information about the specified application. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param application_name: The name of the application. This must be unique within the account. Required. :type application_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Application or the result of cls(response) :rtype: ~azure.mgmt.batch.models.Application :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.Application] = kwargs.pop("cls", None) request = build_get_request( resource_group_name=resource_group_name, account_name=account_name, application_name=application_name, subscription_id=self._config.subscription_id, api_version=api_version, template_url=self.get.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize("Application", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/applications/{applicationName}" } @overload def update( self, resource_group_name: str, account_name: str, application_name: str, parameters: _models.Application, *, content_type: str = "application/json", **kwargs: Any ) -> _models.Application: """Updates settings for the specified application. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param application_name: The name of the application. This must be unique within the account. Required. :type application_name: str :param parameters: The parameters for the request. Required. :type parameters: ~azure.mgmt.batch.models.Application :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Application or the result of cls(response) :rtype: ~azure.mgmt.batch.models.Application :raises ~azure.core.exceptions.HttpResponseError: """ @overload def update( self, resource_group_name: str, account_name: str, application_name: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any ) -> _models.Application: """Updates settings for the specified application. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param application_name: The name of the application. This must be unique within the account. Required. :type application_name: str :param parameters: The parameters for the request. Required. :type parameters: IO :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Application or the result of cls(response) :rtype: ~azure.mgmt.batch.models.Application :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace def update( self, resource_group_name: str, account_name: str, application_name: str, parameters: Union[_models.Application, IO], **kwargs: Any ) -> _models.Application: """Updates settings for the specified application. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param application_name: The name of the application. This must be unique within the account. Required. :type application_name: str :param parameters: The parameters for the request. Is either a Application type or a IO type. Required. :type parameters: ~azure.mgmt.batch.models.Application or IO :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. Default value is None. :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Application or the result of cls(response) :rtype: ~azure.mgmt.batch.models.Application :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.Application] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None if isinstance(parameters, (IOBase, bytes)): _content = parameters else: _json = self._serialize.body(parameters, "Application") request = build_update_request( resource_group_name=resource_group_name, account_name=account_name, application_name=application_name, subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, content=_content, template_url=self.update.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize("Application", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized update.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/applications/{applicationName}" } @distributed_trace def list( self, resource_group_name: str, account_name: str, maxresults: Optional[int] = None, **kwargs: Any ) -> Iterable["_models.Application"]: """Lists all of the applications in the specified account. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param maxresults: The maximum number of items to return in the response. Default value is None. :type maxresults: int :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either Application or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.batch.models.Application] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.ListApplicationsResult] = kwargs.pop("cls", None) error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_request( resource_group_name=resource_group_name, account_name=account_name, subscription_id=self._config.subscription_id, maxresults=maxresults, api_version=api_version, template_url=self.list.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) else: # make call to next link with the client's api-version _parsed_next_link = urllib.parse.urlparse(next_link) _next_request_params = case_insensitive_dict( { key: [urllib.parse.quote(v) for v in value] for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) _next_request_params["api-version"] = self._config.api_version request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) request.url = self._client.format_url(request.url) request.method = "GET" return request def extract_data(pipeline_response): deserialized = self._deserialize("ListApplicationsResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) # type: ignore return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return ItemPaged(get_next, extract_data) list.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/applications" }
0.793666
0.084078
from io import IOBase from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, overload import urllib.parse from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, map_error, ) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models from .._serialization import Serializer from .._vendor import _convert_request, _format_url_section T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False def build_activate_request( resource_group_name: str, account_name: str, application_name: str, version_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-05-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/applications/{applicationName}/versions/{versionName}/activate", ) # pylint: disable=line-too-long path_format_arguments = { "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), "accountName": _SERIALIZER.url( "account_name", account_name, "str", max_length=24, min_length=3, pattern=r"^[a-zA-Z0-9]+$" ), "applicationName": _SERIALIZER.url( "application_name", application_name, "str", max_length=64, min_length=1, pattern=r"^[a-zA-Z0-9_-]+$" ), "versionName": _SERIALIZER.url( "version_name", version_name, "str", max_length=64, min_length=1, pattern=r"^[a-zA-Z0-9_-][a-zA-Z0-9_.-]*$" ), "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers if content_type is not None: _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) def build_create_request( resource_group_name: str, account_name: str, application_name: str, version_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-05-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/applications/{applicationName}/versions/{versionName}", ) # pylint: disable=line-too-long path_format_arguments = { "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), "accountName": _SERIALIZER.url( "account_name", account_name, "str", max_length=24, min_length=3, pattern=r"^[a-zA-Z0-9]+$" ), "applicationName": _SERIALIZER.url( "application_name", application_name, "str", max_length=64, min_length=1, pattern=r"^[a-zA-Z0-9_-]+$" ), "versionName": _SERIALIZER.url( "version_name", version_name, "str", max_length=64, min_length=1, pattern=r"^[a-zA-Z0-9_-][a-zA-Z0-9_.-]*$" ), "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers if content_type is not None: _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) def build_delete_request( resource_group_name: str, account_name: str, application_name: str, version_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-05-01")) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/applications/{applicationName}/versions/{versionName}", ) # pylint: disable=line-too-long path_format_arguments = { "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), "accountName": _SERIALIZER.url( "account_name", account_name, "str", max_length=24, min_length=3, pattern=r"^[a-zA-Z0-9]+$" ), "applicationName": _SERIALIZER.url( "application_name", application_name, "str", max_length=64, min_length=1, pattern=r"^[a-zA-Z0-9_-]+$" ), "versionName": _SERIALIZER.url( "version_name", version_name, "str", max_length=64, min_length=1, pattern=r"^[a-zA-Z0-9_-][a-zA-Z0-9_.-]*$" ), "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) def build_get_request( resource_group_name: str, account_name: str, application_name: str, version_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-05-01")) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/applications/{applicationName}/versions/{versionName}", ) # pylint: disable=line-too-long path_format_arguments = { "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), "accountName": _SERIALIZER.url( "account_name", account_name, "str", max_length=24, min_length=3, pattern=r"^[a-zA-Z0-9]+$" ), "applicationName": _SERIALIZER.url( "application_name", application_name, "str", max_length=64, min_length=1, pattern=r"^[a-zA-Z0-9_-]+$" ), "versionName": _SERIALIZER.url( "version_name", version_name, "str", max_length=64, min_length=1, pattern=r"^[a-zA-Z0-9_-][a-zA-Z0-9_.-]*$" ), "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_list_request( resource_group_name: str, account_name: str, application_name: str, subscription_id: str, *, maxresults: Optional[int] = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-05-01")) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/applications/{applicationName}/versions", ) # pylint: disable=line-too-long path_format_arguments = { "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), "accountName": _SERIALIZER.url( "account_name", account_name, "str", max_length=24, min_length=3, pattern=r"^[a-zA-Z0-9]+$" ), "applicationName": _SERIALIZER.url( "application_name", application_name, "str", max_length=64, min_length=1, pattern=r"^[a-zA-Z0-9_-]+$" ), "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # Construct parameters if maxresults is not None: _params["maxresults"] = _SERIALIZER.query("maxresults", maxresults, "int") _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) class ApplicationPackageOperations: """ .. warning:: **DO NOT** instantiate this class directly. Instead, you should access the following operations through :class:`~azure.mgmt.batch.BatchManagementClient`'s :attr:`application_package` attribute. """ models = _models def __init__(self, *args, **kwargs): input_args = list(args) self._client = input_args.pop(0) if input_args else kwargs.pop("client") self._config = input_args.pop(0) if input_args else kwargs.pop("config") self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @overload def activate( self, resource_group_name: str, account_name: str, application_name: str, version_name: str, parameters: _models.ActivateApplicationPackageParameters, *, content_type: str = "application/json", **kwargs: Any ) -> _models.ApplicationPackage: """Activates the specified application package. This should be done after the ``ApplicationPackage`` was created and uploaded. This needs to be done before an ``ApplicationPackage`` can be used on Pools or Tasks. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param application_name: The name of the application. This must be unique within the account. Required. :type application_name: str :param version_name: The version of the application. Required. :type version_name: str :param parameters: The parameters for the request. Required. :type parameters: ~azure.mgmt.batch.models.ActivateApplicationPackageParameters :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: ApplicationPackage or the result of cls(response) :rtype: ~azure.mgmt.batch.models.ApplicationPackage :raises ~azure.core.exceptions.HttpResponseError: """ @overload def activate( self, resource_group_name: str, account_name: str, application_name: str, version_name: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any ) -> _models.ApplicationPackage: """Activates the specified application package. This should be done after the ``ApplicationPackage`` was created and uploaded. This needs to be done before an ``ApplicationPackage`` can be used on Pools or Tasks. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param application_name: The name of the application. This must be unique within the account. Required. :type application_name: str :param version_name: The version of the application. Required. :type version_name: str :param parameters: The parameters for the request. Required. :type parameters: IO :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: ApplicationPackage or the result of cls(response) :rtype: ~azure.mgmt.batch.models.ApplicationPackage :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace def activate( self, resource_group_name: str, account_name: str, application_name: str, version_name: str, parameters: Union[_models.ActivateApplicationPackageParameters, IO], **kwargs: Any ) -> _models.ApplicationPackage: """Activates the specified application package. This should be done after the ``ApplicationPackage`` was created and uploaded. This needs to be done before an ``ApplicationPackage`` can be used on Pools or Tasks. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param application_name: The name of the application. This must be unique within the account. Required. :type application_name: str :param version_name: The version of the application. Required. :type version_name: str :param parameters: The parameters for the request. Is either a ActivateApplicationPackageParameters type or a IO type. Required. :type parameters: ~azure.mgmt.batch.models.ActivateApplicationPackageParameters or IO :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. Default value is None. :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: ApplicationPackage or the result of cls(response) :rtype: ~azure.mgmt.batch.models.ApplicationPackage :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.ApplicationPackage] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None if isinstance(parameters, (IOBase, bytes)): _content = parameters else: _json = self._serialize.body(parameters, "ActivateApplicationPackageParameters") request = build_activate_request( resource_group_name=resource_group_name, account_name=account_name, application_name=application_name, version_name=version_name, subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, content=_content, template_url=self.activate.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize("ApplicationPackage", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized activate.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/applications/{applicationName}/versions/{versionName}/activate" } @overload def create( self, resource_group_name: str, account_name: str, application_name: str, version_name: str, parameters: Optional[_models.ApplicationPackage] = None, *, content_type: str = "application/json", **kwargs: Any ) -> _models.ApplicationPackage: """Creates an application package record. The record contains a storageUrl where the package should be uploaded to. Once it is uploaded the ``ApplicationPackage`` needs to be activated using ``ApplicationPackageActive`` before it can be used. If the auto storage account was configured to use storage keys, the URL returned will contain a SAS. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param application_name: The name of the application. This must be unique within the account. Required. :type application_name: str :param version_name: The version of the application. Required. :type version_name: str :param parameters: The parameters for the request. Default value is None. :type parameters: ~azure.mgmt.batch.models.ApplicationPackage :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: ApplicationPackage or the result of cls(response) :rtype: ~azure.mgmt.batch.models.ApplicationPackage :raises ~azure.core.exceptions.HttpResponseError: """ @overload def create( self, resource_group_name: str, account_name: str, application_name: str, version_name: str, parameters: Optional[IO] = None, *, content_type: str = "application/json", **kwargs: Any ) -> _models.ApplicationPackage: """Creates an application package record. The record contains a storageUrl where the package should be uploaded to. Once it is uploaded the ``ApplicationPackage`` needs to be activated using ``ApplicationPackageActive`` before it can be used. If the auto storage account was configured to use storage keys, the URL returned will contain a SAS. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param application_name: The name of the application. This must be unique within the account. Required. :type application_name: str :param version_name: The version of the application. Required. :type version_name: str :param parameters: The parameters for the request. Default value is None. :type parameters: IO :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: ApplicationPackage or the result of cls(response) :rtype: ~azure.mgmt.batch.models.ApplicationPackage :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace def create( self, resource_group_name: str, account_name: str, application_name: str, version_name: str, parameters: Optional[Union[_models.ApplicationPackage, IO]] = None, **kwargs: Any ) -> _models.ApplicationPackage: """Creates an application package record. The record contains a storageUrl where the package should be uploaded to. Once it is uploaded the ``ApplicationPackage`` needs to be activated using ``ApplicationPackageActive`` before it can be used. If the auto storage account was configured to use storage keys, the URL returned will contain a SAS. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param application_name: The name of the application. This must be unique within the account. Required. :type application_name: str :param version_name: The version of the application. Required. :type version_name: str :param parameters: The parameters for the request. Is either a ApplicationPackage type or a IO type. Default value is None. :type parameters: ~azure.mgmt.batch.models.ApplicationPackage or IO :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. Default value is None. :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: ApplicationPackage or the result of cls(response) :rtype: ~azure.mgmt.batch.models.ApplicationPackage :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.ApplicationPackage] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None if isinstance(parameters, (IOBase, bytes)): _content = parameters else: if parameters is not None: _json = self._serialize.body(parameters, "ApplicationPackage") else: _json = None request = build_create_request( resource_group_name=resource_group_name, account_name=account_name, application_name=application_name, version_name=version_name, subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, content=_content, template_url=self.create.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize("ApplicationPackage", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized create.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/applications/{applicationName}/versions/{versionName}" } @distributed_trace def delete( # pylint: disable=inconsistent-return-statements self, resource_group_name: str, account_name: str, application_name: str, version_name: str, **kwargs: Any ) -> None: """Deletes an application package record and its associated binary file. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param application_name: The name of the application. This must be unique within the account. Required. :type application_name: str :param version_name: The version of the application. Required. :type version_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: None or the result of cls(response) :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[None] = kwargs.pop("cls", None) request = build_delete_request( resource_group_name=resource_group_name, account_name=account_name, application_name=application_name, version_name=version_name, subscription_id=self._config.subscription_id, api_version=api_version, template_url=self.delete.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) delete.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/applications/{applicationName}/versions/{versionName}" } @distributed_trace def get( self, resource_group_name: str, account_name: str, application_name: str, version_name: str, **kwargs: Any ) -> _models.ApplicationPackage: """Gets information about the specified application package. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param application_name: The name of the application. This must be unique within the account. Required. :type application_name: str :param version_name: The version of the application. Required. :type version_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: ApplicationPackage or the result of cls(response) :rtype: ~azure.mgmt.batch.models.ApplicationPackage :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.ApplicationPackage] = kwargs.pop("cls", None) request = build_get_request( resource_group_name=resource_group_name, account_name=account_name, application_name=application_name, version_name=version_name, subscription_id=self._config.subscription_id, api_version=api_version, template_url=self.get.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize("ApplicationPackage", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/applications/{applicationName}/versions/{versionName}" } @distributed_trace def list( self, resource_group_name: str, account_name: str, application_name: str, maxresults: Optional[int] = None, **kwargs: Any ) -> Iterable["_models.ApplicationPackage"]: """Lists all of the application packages in the specified application. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param application_name: The name of the application. This must be unique within the account. Required. :type application_name: str :param maxresults: The maximum number of items to return in the response. Default value is None. :type maxresults: int :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ApplicationPackage or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.batch.models.ApplicationPackage] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.ListApplicationPackagesResult] = kwargs.pop("cls", None) error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_request( resource_group_name=resource_group_name, account_name=account_name, application_name=application_name, subscription_id=self._config.subscription_id, maxresults=maxresults, api_version=api_version, template_url=self.list.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) else: # make call to next link with the client's api-version _parsed_next_link = urllib.parse.urlparse(next_link) _next_request_params = case_insensitive_dict( { key: [urllib.parse.quote(v) for v in value] for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) _next_request_params["api-version"] = self._config.api_version request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) request.url = self._client.format_url(request.url) request.method = "GET" return request def extract_data(pipeline_response): deserialized = self._deserialize("ListApplicationPackagesResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) # type: ignore return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return ItemPaged(get_next, extract_data) list.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/applications/{applicationName}/versions" }
azure-mgmt-batch
/azure_mgmt_batch-17.1.0-py3-none-any.whl/azure/mgmt/batch/operations/_application_package_operations.py
_application_package_operations.py
from io import IOBase from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, overload import urllib.parse from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, map_error, ) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models from .._serialization import Serializer from .._vendor import _convert_request, _format_url_section T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False def build_activate_request( resource_group_name: str, account_name: str, application_name: str, version_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-05-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/applications/{applicationName}/versions/{versionName}/activate", ) # pylint: disable=line-too-long path_format_arguments = { "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), "accountName": _SERIALIZER.url( "account_name", account_name, "str", max_length=24, min_length=3, pattern=r"^[a-zA-Z0-9]+$" ), "applicationName": _SERIALIZER.url( "application_name", application_name, "str", max_length=64, min_length=1, pattern=r"^[a-zA-Z0-9_-]+$" ), "versionName": _SERIALIZER.url( "version_name", version_name, "str", max_length=64, min_length=1, pattern=r"^[a-zA-Z0-9_-][a-zA-Z0-9_.-]*$" ), "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers if content_type is not None: _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) def build_create_request( resource_group_name: str, account_name: str, application_name: str, version_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-05-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/applications/{applicationName}/versions/{versionName}", ) # pylint: disable=line-too-long path_format_arguments = { "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), "accountName": _SERIALIZER.url( "account_name", account_name, "str", max_length=24, min_length=3, pattern=r"^[a-zA-Z0-9]+$" ), "applicationName": _SERIALIZER.url( "application_name", application_name, "str", max_length=64, min_length=1, pattern=r"^[a-zA-Z0-9_-]+$" ), "versionName": _SERIALIZER.url( "version_name", version_name, "str", max_length=64, min_length=1, pattern=r"^[a-zA-Z0-9_-][a-zA-Z0-9_.-]*$" ), "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers if content_type is not None: _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) def build_delete_request( resource_group_name: str, account_name: str, application_name: str, version_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-05-01")) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/applications/{applicationName}/versions/{versionName}", ) # pylint: disable=line-too-long path_format_arguments = { "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), "accountName": _SERIALIZER.url( "account_name", account_name, "str", max_length=24, min_length=3, pattern=r"^[a-zA-Z0-9]+$" ), "applicationName": _SERIALIZER.url( "application_name", application_name, "str", max_length=64, min_length=1, pattern=r"^[a-zA-Z0-9_-]+$" ), "versionName": _SERIALIZER.url( "version_name", version_name, "str", max_length=64, min_length=1, pattern=r"^[a-zA-Z0-9_-][a-zA-Z0-9_.-]*$" ), "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) def build_get_request( resource_group_name: str, account_name: str, application_name: str, version_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-05-01")) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/applications/{applicationName}/versions/{versionName}", ) # pylint: disable=line-too-long path_format_arguments = { "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), "accountName": _SERIALIZER.url( "account_name", account_name, "str", max_length=24, min_length=3, pattern=r"^[a-zA-Z0-9]+$" ), "applicationName": _SERIALIZER.url( "application_name", application_name, "str", max_length=64, min_length=1, pattern=r"^[a-zA-Z0-9_-]+$" ), "versionName": _SERIALIZER.url( "version_name", version_name, "str", max_length=64, min_length=1, pattern=r"^[a-zA-Z0-9_-][a-zA-Z0-9_.-]*$" ), "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_list_request( resource_group_name: str, account_name: str, application_name: str, subscription_id: str, *, maxresults: Optional[int] = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-05-01")) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/applications/{applicationName}/versions", ) # pylint: disable=line-too-long path_format_arguments = { "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), "accountName": _SERIALIZER.url( "account_name", account_name, "str", max_length=24, min_length=3, pattern=r"^[a-zA-Z0-9]+$" ), "applicationName": _SERIALIZER.url( "application_name", application_name, "str", max_length=64, min_length=1, pattern=r"^[a-zA-Z0-9_-]+$" ), "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # Construct parameters if maxresults is not None: _params["maxresults"] = _SERIALIZER.query("maxresults", maxresults, "int") _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) class ApplicationPackageOperations: """ .. warning:: **DO NOT** instantiate this class directly. Instead, you should access the following operations through :class:`~azure.mgmt.batch.BatchManagementClient`'s :attr:`application_package` attribute. """ models = _models def __init__(self, *args, **kwargs): input_args = list(args) self._client = input_args.pop(0) if input_args else kwargs.pop("client") self._config = input_args.pop(0) if input_args else kwargs.pop("config") self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @overload def activate( self, resource_group_name: str, account_name: str, application_name: str, version_name: str, parameters: _models.ActivateApplicationPackageParameters, *, content_type: str = "application/json", **kwargs: Any ) -> _models.ApplicationPackage: """Activates the specified application package. This should be done after the ``ApplicationPackage`` was created and uploaded. This needs to be done before an ``ApplicationPackage`` can be used on Pools or Tasks. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param application_name: The name of the application. This must be unique within the account. Required. :type application_name: str :param version_name: The version of the application. Required. :type version_name: str :param parameters: The parameters for the request. Required. :type parameters: ~azure.mgmt.batch.models.ActivateApplicationPackageParameters :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: ApplicationPackage or the result of cls(response) :rtype: ~azure.mgmt.batch.models.ApplicationPackage :raises ~azure.core.exceptions.HttpResponseError: """ @overload def activate( self, resource_group_name: str, account_name: str, application_name: str, version_name: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any ) -> _models.ApplicationPackage: """Activates the specified application package. This should be done after the ``ApplicationPackage`` was created and uploaded. This needs to be done before an ``ApplicationPackage`` can be used on Pools or Tasks. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param application_name: The name of the application. This must be unique within the account. Required. :type application_name: str :param version_name: The version of the application. Required. :type version_name: str :param parameters: The parameters for the request. Required. :type parameters: IO :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: ApplicationPackage or the result of cls(response) :rtype: ~azure.mgmt.batch.models.ApplicationPackage :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace def activate( self, resource_group_name: str, account_name: str, application_name: str, version_name: str, parameters: Union[_models.ActivateApplicationPackageParameters, IO], **kwargs: Any ) -> _models.ApplicationPackage: """Activates the specified application package. This should be done after the ``ApplicationPackage`` was created and uploaded. This needs to be done before an ``ApplicationPackage`` can be used on Pools or Tasks. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param application_name: The name of the application. This must be unique within the account. Required. :type application_name: str :param version_name: The version of the application. Required. :type version_name: str :param parameters: The parameters for the request. Is either a ActivateApplicationPackageParameters type or a IO type. Required. :type parameters: ~azure.mgmt.batch.models.ActivateApplicationPackageParameters or IO :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. Default value is None. :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: ApplicationPackage or the result of cls(response) :rtype: ~azure.mgmt.batch.models.ApplicationPackage :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.ApplicationPackage] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None if isinstance(parameters, (IOBase, bytes)): _content = parameters else: _json = self._serialize.body(parameters, "ActivateApplicationPackageParameters") request = build_activate_request( resource_group_name=resource_group_name, account_name=account_name, application_name=application_name, version_name=version_name, subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, content=_content, template_url=self.activate.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize("ApplicationPackage", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized activate.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/applications/{applicationName}/versions/{versionName}/activate" } @overload def create( self, resource_group_name: str, account_name: str, application_name: str, version_name: str, parameters: Optional[_models.ApplicationPackage] = None, *, content_type: str = "application/json", **kwargs: Any ) -> _models.ApplicationPackage: """Creates an application package record. The record contains a storageUrl where the package should be uploaded to. Once it is uploaded the ``ApplicationPackage`` needs to be activated using ``ApplicationPackageActive`` before it can be used. If the auto storage account was configured to use storage keys, the URL returned will contain a SAS. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param application_name: The name of the application. This must be unique within the account. Required. :type application_name: str :param version_name: The version of the application. Required. :type version_name: str :param parameters: The parameters for the request. Default value is None. :type parameters: ~azure.mgmt.batch.models.ApplicationPackage :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: ApplicationPackage or the result of cls(response) :rtype: ~azure.mgmt.batch.models.ApplicationPackage :raises ~azure.core.exceptions.HttpResponseError: """ @overload def create( self, resource_group_name: str, account_name: str, application_name: str, version_name: str, parameters: Optional[IO] = None, *, content_type: str = "application/json", **kwargs: Any ) -> _models.ApplicationPackage: """Creates an application package record. The record contains a storageUrl where the package should be uploaded to. Once it is uploaded the ``ApplicationPackage`` needs to be activated using ``ApplicationPackageActive`` before it can be used. If the auto storage account was configured to use storage keys, the URL returned will contain a SAS. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param application_name: The name of the application. This must be unique within the account. Required. :type application_name: str :param version_name: The version of the application. Required. :type version_name: str :param parameters: The parameters for the request. Default value is None. :type parameters: IO :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: ApplicationPackage or the result of cls(response) :rtype: ~azure.mgmt.batch.models.ApplicationPackage :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace def create( self, resource_group_name: str, account_name: str, application_name: str, version_name: str, parameters: Optional[Union[_models.ApplicationPackage, IO]] = None, **kwargs: Any ) -> _models.ApplicationPackage: """Creates an application package record. The record contains a storageUrl where the package should be uploaded to. Once it is uploaded the ``ApplicationPackage`` needs to be activated using ``ApplicationPackageActive`` before it can be used. If the auto storage account was configured to use storage keys, the URL returned will contain a SAS. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param application_name: The name of the application. This must be unique within the account. Required. :type application_name: str :param version_name: The version of the application. Required. :type version_name: str :param parameters: The parameters for the request. Is either a ApplicationPackage type or a IO type. Default value is None. :type parameters: ~azure.mgmt.batch.models.ApplicationPackage or IO :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. Default value is None. :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: ApplicationPackage or the result of cls(response) :rtype: ~azure.mgmt.batch.models.ApplicationPackage :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.ApplicationPackage] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None if isinstance(parameters, (IOBase, bytes)): _content = parameters else: if parameters is not None: _json = self._serialize.body(parameters, "ApplicationPackage") else: _json = None request = build_create_request( resource_group_name=resource_group_name, account_name=account_name, application_name=application_name, version_name=version_name, subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, content=_content, template_url=self.create.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize("ApplicationPackage", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized create.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/applications/{applicationName}/versions/{versionName}" } @distributed_trace def delete( # pylint: disable=inconsistent-return-statements self, resource_group_name: str, account_name: str, application_name: str, version_name: str, **kwargs: Any ) -> None: """Deletes an application package record and its associated binary file. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param application_name: The name of the application. This must be unique within the account. Required. :type application_name: str :param version_name: The version of the application. Required. :type version_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: None or the result of cls(response) :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[None] = kwargs.pop("cls", None) request = build_delete_request( resource_group_name=resource_group_name, account_name=account_name, application_name=application_name, version_name=version_name, subscription_id=self._config.subscription_id, api_version=api_version, template_url=self.delete.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) delete.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/applications/{applicationName}/versions/{versionName}" } @distributed_trace def get( self, resource_group_name: str, account_name: str, application_name: str, version_name: str, **kwargs: Any ) -> _models.ApplicationPackage: """Gets information about the specified application package. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param application_name: The name of the application. This must be unique within the account. Required. :type application_name: str :param version_name: The version of the application. Required. :type version_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: ApplicationPackage or the result of cls(response) :rtype: ~azure.mgmt.batch.models.ApplicationPackage :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.ApplicationPackage] = kwargs.pop("cls", None) request = build_get_request( resource_group_name=resource_group_name, account_name=account_name, application_name=application_name, version_name=version_name, subscription_id=self._config.subscription_id, api_version=api_version, template_url=self.get.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize("ApplicationPackage", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/applications/{applicationName}/versions/{versionName}" } @distributed_trace def list( self, resource_group_name: str, account_name: str, application_name: str, maxresults: Optional[int] = None, **kwargs: Any ) -> Iterable["_models.ApplicationPackage"]: """Lists all of the application packages in the specified application. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param application_name: The name of the application. This must be unique within the account. Required. :type application_name: str :param maxresults: The maximum number of items to return in the response. Default value is None. :type maxresults: int :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ApplicationPackage or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.batch.models.ApplicationPackage] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.ListApplicationPackagesResult] = kwargs.pop("cls", None) error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_request( resource_group_name=resource_group_name, account_name=account_name, application_name=application_name, subscription_id=self._config.subscription_id, maxresults=maxresults, api_version=api_version, template_url=self.list.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) else: # make call to next link with the client's api-version _parsed_next_link = urllib.parse.urlparse(next_link) _next_request_params = case_insensitive_dict( { key: [urllib.parse.quote(v) for v in value] for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) _next_request_params["api-version"] = self._config.api_version request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) request.url = self._client.format_url(request.url) request.method = "GET" return request def extract_data(pipeline_response): deserialized = self._deserialize("ListApplicationPackagesResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) # type: ignore return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return ItemPaged(get_next, extract_data) list.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/applications/{applicationName}/versions" }
0.74382
0.07703
from io import IOBase from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, cast, overload import urllib.parse from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, map_error, ) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse from azure.core.polling import LROPoller, NoPolling, PollingMethod from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.arm_polling import ARMPolling from .. import models as _models from .._serialization import Serializer from .._vendor import _convert_request, _format_url_section T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False def build_list_by_batch_account_request( resource_group_name: str, account_name: str, subscription_id: str, *, maxresults: Optional[int] = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-05-01")) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/privateEndpointConnections", ) # pylint: disable=line-too-long path_format_arguments = { "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), "accountName": _SERIALIZER.url( "account_name", account_name, "str", max_length=24, min_length=3, pattern=r"^[a-zA-Z0-9]+$" ), } _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if maxresults is not None: _params["maxresults"] = _SERIALIZER.query("maxresults", maxresults, "int") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_get_request( resource_group_name: str, account_name: str, private_endpoint_connection_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-05-01")) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/privateEndpointConnections/{privateEndpointConnectionName}", ) # pylint: disable=line-too-long path_format_arguments = { "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), "accountName": _SERIALIZER.url( "account_name", account_name, "str", max_length=24, min_length=3, pattern=r"^[a-zA-Z0-9]+$" ), "privateEndpointConnectionName": _SERIALIZER.url( "private_endpoint_connection_name", private_endpoint_connection_name, "str", max_length=101, min_length=1, pattern=r"^[a-zA-Z0-9_-]+\.?[a-fA-F0-9-]*$", ), } _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_update_request( resource_group_name: str, account_name: str, private_endpoint_connection_name: str, subscription_id: str, *, if_match: Optional[str] = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-05-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/privateEndpointConnections/{privateEndpointConnectionName}", ) # pylint: disable=line-too-long path_format_arguments = { "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), "accountName": _SERIALIZER.url( "account_name", account_name, "str", max_length=24, min_length=3, pattern=r"^[a-zA-Z0-9]+$" ), "privateEndpointConnectionName": _SERIALIZER.url( "private_endpoint_connection_name", private_endpoint_connection_name, "str", max_length=101, min_length=1, pattern=r"^[a-zA-Z0-9_-]+\.?[a-fA-F0-9-]*$", ), } _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers if if_match is not None: _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") if content_type is not None: _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs) def build_delete_request( resource_group_name: str, account_name: str, private_endpoint_connection_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-05-01")) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/privateEndpointConnections/{privateEndpointConnectionName}", ) # pylint: disable=line-too-long path_format_arguments = { "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), "accountName": _SERIALIZER.url( "account_name", account_name, "str", max_length=24, min_length=3, pattern=r"^[a-zA-Z0-9]+$" ), "privateEndpointConnectionName": _SERIALIZER.url( "private_endpoint_connection_name", private_endpoint_connection_name, "str", max_length=101, min_length=1, pattern=r"^[a-zA-Z0-9_-]+\.?[a-fA-F0-9-]*$", ), } _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) class PrivateEndpointConnectionOperations: """ .. warning:: **DO NOT** instantiate this class directly. Instead, you should access the following operations through :class:`~azure.mgmt.batch.BatchManagementClient`'s :attr:`private_endpoint_connection` attribute. """ models = _models def __init__(self, *args, **kwargs): input_args = list(args) self._client = input_args.pop(0) if input_args else kwargs.pop("client") self._config = input_args.pop(0) if input_args else kwargs.pop("config") self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace def list_by_batch_account( self, resource_group_name: str, account_name: str, maxresults: Optional[int] = None, **kwargs: Any ) -> Iterable["_models.PrivateEndpointConnection"]: """Lists all of the private endpoint connections in the specified account. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param maxresults: The maximum number of items to return in the response. Default value is None. :type maxresults: int :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either PrivateEndpointConnection or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.batch.models.PrivateEndpointConnection] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.ListPrivateEndpointConnectionsResult] = kwargs.pop("cls", None) error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_by_batch_account_request( resource_group_name=resource_group_name, account_name=account_name, subscription_id=self._config.subscription_id, maxresults=maxresults, api_version=api_version, template_url=self.list_by_batch_account.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) else: # make call to next link with the client's api-version _parsed_next_link = urllib.parse.urlparse(next_link) _next_request_params = case_insensitive_dict( { key: [urllib.parse.quote(v) for v in value] for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) _next_request_params["api-version"] = self._config.api_version request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) request.url = self._client.format_url(request.url) request.method = "GET" return request def extract_data(pipeline_response): deserialized = self._deserialize("ListPrivateEndpointConnectionsResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) # type: ignore return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return ItemPaged(get_next, extract_data) list_by_batch_account.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/privateEndpointConnections" } @distributed_trace def get( self, resource_group_name: str, account_name: str, private_endpoint_connection_name: str, **kwargs: Any ) -> _models.PrivateEndpointConnection: """Gets information about the specified private endpoint connection. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param private_endpoint_connection_name: The private endpoint connection name. This must be unique within the account. Required. :type private_endpoint_connection_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: PrivateEndpointConnection or the result of cls(response) :rtype: ~azure.mgmt.batch.models.PrivateEndpointConnection :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.PrivateEndpointConnection] = kwargs.pop("cls", None) request = build_get_request( resource_group_name=resource_group_name, account_name=account_name, private_endpoint_connection_name=private_endpoint_connection_name, subscription_id=self._config.subscription_id, api_version=api_version, template_url=self.get.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize("PrivateEndpointConnection", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/privateEndpointConnections/{privateEndpointConnectionName}" } def _update_initial( self, resource_group_name: str, account_name: str, private_endpoint_connection_name: str, parameters: Union[_models.PrivateEndpointConnection, IO], if_match: Optional[str] = None, **kwargs: Any ) -> Optional[_models.PrivateEndpointConnection]: error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[Optional[_models.PrivateEndpointConnection]] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None if isinstance(parameters, (IOBase, bytes)): _content = parameters else: _json = self._serialize.body(parameters, "PrivateEndpointConnection") request = build_update_request( resource_group_name=resource_group_name, account_name=account_name, private_endpoint_connection_name=private_endpoint_connection_name, subscription_id=self._config.subscription_id, if_match=if_match, api_version=api_version, content_type=content_type, json=_json, content=_content, template_url=self._update_initial.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = None response_headers = {} if response.status_code == 200: deserialized = self._deserialize("PrivateEndpointConnection", pipeline_response) if response.status_code == 202: response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) if cls: return cls(pipeline_response, deserialized, response_headers) return deserialized _update_initial.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/privateEndpointConnections/{privateEndpointConnectionName}" } @overload def begin_update( self, resource_group_name: str, account_name: str, private_endpoint_connection_name: str, parameters: _models.PrivateEndpointConnection, if_match: Optional[str] = None, *, content_type: str = "application/json", **kwargs: Any ) -> LROPoller[_models.PrivateEndpointConnection]: """Updates the properties of an existing private endpoint connection. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param private_endpoint_connection_name: The private endpoint connection name. This must be unique within the account. Required. :type private_endpoint_connection_name: str :param parameters: PrivateEndpointConnection properties that should be updated. Properties that are supplied will be updated, any property not supplied will be unchanged. Required. :type parameters: ~azure.mgmt.batch.models.PrivateEndpointConnection :param if_match: The state (ETag) version of the private endpoint connection to update. This value can be omitted or set to "*" to apply the operation unconditionally. Default value is None. :type if_match: str :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.PollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of LROPoller that returns either PrivateEndpointConnection or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.batch.models.PrivateEndpointConnection] :raises ~azure.core.exceptions.HttpResponseError: """ @overload def begin_update( self, resource_group_name: str, account_name: str, private_endpoint_connection_name: str, parameters: IO, if_match: Optional[str] = None, *, content_type: str = "application/json", **kwargs: Any ) -> LROPoller[_models.PrivateEndpointConnection]: """Updates the properties of an existing private endpoint connection. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param private_endpoint_connection_name: The private endpoint connection name. This must be unique within the account. Required. :type private_endpoint_connection_name: str :param parameters: PrivateEndpointConnection properties that should be updated. Properties that are supplied will be updated, any property not supplied will be unchanged. Required. :type parameters: IO :param if_match: The state (ETag) version of the private endpoint connection to update. This value can be omitted or set to "*" to apply the operation unconditionally. Default value is None. :type if_match: str :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.PollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of LROPoller that returns either PrivateEndpointConnection or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.batch.models.PrivateEndpointConnection] :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace def begin_update( self, resource_group_name: str, account_name: str, private_endpoint_connection_name: str, parameters: Union[_models.PrivateEndpointConnection, IO], if_match: Optional[str] = None, **kwargs: Any ) -> LROPoller[_models.PrivateEndpointConnection]: """Updates the properties of an existing private endpoint connection. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param private_endpoint_connection_name: The private endpoint connection name. This must be unique within the account. Required. :type private_endpoint_connection_name: str :param parameters: PrivateEndpointConnection properties that should be updated. Properties that are supplied will be updated, any property not supplied will be unchanged. Is either a PrivateEndpointConnection type or a IO type. Required. :type parameters: ~azure.mgmt.batch.models.PrivateEndpointConnection or IO :param if_match: The state (ETag) version of the private endpoint connection to update. This value can be omitted or set to "*" to apply the operation unconditionally. Default value is None. :type if_match: str :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. Default value is None. :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.PollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of LROPoller that returns either PrivateEndpointConnection or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.batch.models.PrivateEndpointConnection] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.PrivateEndpointConnection] = kwargs.pop("cls", None) polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) cont_token: Optional[str] = kwargs.pop("continuation_token", None) if cont_token is None: raw_result = self._update_initial( resource_group_name=resource_group_name, account_name=account_name, private_endpoint_connection_name=private_endpoint_connection_name, parameters=parameters, if_match=if_match, api_version=api_version, content_type=content_type, cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): deserialized = self._deserialize("PrivateEndpointConnection", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized if polling is True: polling_method: PollingMethod = cast( PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs) ) elif polling is False: polling_method = cast(PollingMethod, NoPolling()) else: polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) return LROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore begin_update.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/privateEndpointConnections/{privateEndpointConnectionName}" } def _delete_initial( # pylint: disable=inconsistent-return-statements self, resource_group_name: str, account_name: str, private_endpoint_connection_name: str, **kwargs: Any ) -> None: error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[None] = kwargs.pop("cls", None) request = build_delete_request( resource_group_name=resource_group_name, account_name=account_name, private_endpoint_connection_name=private_endpoint_connection_name, subscription_id=self._config.subscription_id, api_version=api_version, template_url=self._delete_initial.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [202, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) response_headers = {} if response.status_code == 202: response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) if cls: return cls(pipeline_response, None, response_headers) _delete_initial.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/privateEndpointConnections/{privateEndpointConnectionName}" } @distributed_trace def begin_delete( self, resource_group_name: str, account_name: str, private_endpoint_connection_name: str, **kwargs: Any ) -> LROPoller[None]: """Deletes the specified private endpoint connection. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param private_endpoint_connection_name: The private endpoint connection name. This must be unique within the account. Required. :type private_endpoint_connection_name: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.PollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of LROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[None] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[None] = kwargs.pop("cls", None) polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) cont_token: Optional[str] = kwargs.pop("continuation_token", None) if cont_token is None: raw_result = self._delete_initial( # type: ignore resource_group_name=resource_group_name, account_name=account_name, private_endpoint_connection_name=private_endpoint_connection_name, api_version=api_version, cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) if polling is True: polling_method: PollingMethod = cast( PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs) ) elif polling is False: polling_method = cast(PollingMethod, NoPolling()) else: polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) return LROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore begin_delete.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/privateEndpointConnections/{privateEndpointConnectionName}" }
azure-mgmt-batch
/azure_mgmt_batch-17.1.0-py3-none-any.whl/azure/mgmt/batch/operations/_private_endpoint_connection_operations.py
_private_endpoint_connection_operations.py
from io import IOBase from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, cast, overload import urllib.parse from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, map_error, ) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse from azure.core.polling import LROPoller, NoPolling, PollingMethod from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.arm_polling import ARMPolling from .. import models as _models from .._serialization import Serializer from .._vendor import _convert_request, _format_url_section T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False def build_list_by_batch_account_request( resource_group_name: str, account_name: str, subscription_id: str, *, maxresults: Optional[int] = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-05-01")) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/privateEndpointConnections", ) # pylint: disable=line-too-long path_format_arguments = { "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), "accountName": _SERIALIZER.url( "account_name", account_name, "str", max_length=24, min_length=3, pattern=r"^[a-zA-Z0-9]+$" ), } _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if maxresults is not None: _params["maxresults"] = _SERIALIZER.query("maxresults", maxresults, "int") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_get_request( resource_group_name: str, account_name: str, private_endpoint_connection_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-05-01")) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/privateEndpointConnections/{privateEndpointConnectionName}", ) # pylint: disable=line-too-long path_format_arguments = { "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), "accountName": _SERIALIZER.url( "account_name", account_name, "str", max_length=24, min_length=3, pattern=r"^[a-zA-Z0-9]+$" ), "privateEndpointConnectionName": _SERIALIZER.url( "private_endpoint_connection_name", private_endpoint_connection_name, "str", max_length=101, min_length=1, pattern=r"^[a-zA-Z0-9_-]+\.?[a-fA-F0-9-]*$", ), } _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_update_request( resource_group_name: str, account_name: str, private_endpoint_connection_name: str, subscription_id: str, *, if_match: Optional[str] = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-05-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/privateEndpointConnections/{privateEndpointConnectionName}", ) # pylint: disable=line-too-long path_format_arguments = { "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), "accountName": _SERIALIZER.url( "account_name", account_name, "str", max_length=24, min_length=3, pattern=r"^[a-zA-Z0-9]+$" ), "privateEndpointConnectionName": _SERIALIZER.url( "private_endpoint_connection_name", private_endpoint_connection_name, "str", max_length=101, min_length=1, pattern=r"^[a-zA-Z0-9_-]+\.?[a-fA-F0-9-]*$", ), } _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers if if_match is not None: _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") if content_type is not None: _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs) def build_delete_request( resource_group_name: str, account_name: str, private_endpoint_connection_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-05-01")) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/privateEndpointConnections/{privateEndpointConnectionName}", ) # pylint: disable=line-too-long path_format_arguments = { "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), "accountName": _SERIALIZER.url( "account_name", account_name, "str", max_length=24, min_length=3, pattern=r"^[a-zA-Z0-9]+$" ), "privateEndpointConnectionName": _SERIALIZER.url( "private_endpoint_connection_name", private_endpoint_connection_name, "str", max_length=101, min_length=1, pattern=r"^[a-zA-Z0-9_-]+\.?[a-fA-F0-9-]*$", ), } _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) class PrivateEndpointConnectionOperations: """ .. warning:: **DO NOT** instantiate this class directly. Instead, you should access the following operations through :class:`~azure.mgmt.batch.BatchManagementClient`'s :attr:`private_endpoint_connection` attribute. """ models = _models def __init__(self, *args, **kwargs): input_args = list(args) self._client = input_args.pop(0) if input_args else kwargs.pop("client") self._config = input_args.pop(0) if input_args else kwargs.pop("config") self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace def list_by_batch_account( self, resource_group_name: str, account_name: str, maxresults: Optional[int] = None, **kwargs: Any ) -> Iterable["_models.PrivateEndpointConnection"]: """Lists all of the private endpoint connections in the specified account. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param maxresults: The maximum number of items to return in the response. Default value is None. :type maxresults: int :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either PrivateEndpointConnection or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.batch.models.PrivateEndpointConnection] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.ListPrivateEndpointConnectionsResult] = kwargs.pop("cls", None) error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_by_batch_account_request( resource_group_name=resource_group_name, account_name=account_name, subscription_id=self._config.subscription_id, maxresults=maxresults, api_version=api_version, template_url=self.list_by_batch_account.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) else: # make call to next link with the client's api-version _parsed_next_link = urllib.parse.urlparse(next_link) _next_request_params = case_insensitive_dict( { key: [urllib.parse.quote(v) for v in value] for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) _next_request_params["api-version"] = self._config.api_version request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) request.url = self._client.format_url(request.url) request.method = "GET" return request def extract_data(pipeline_response): deserialized = self._deserialize("ListPrivateEndpointConnectionsResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) # type: ignore return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return ItemPaged(get_next, extract_data) list_by_batch_account.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/privateEndpointConnections" } @distributed_trace def get( self, resource_group_name: str, account_name: str, private_endpoint_connection_name: str, **kwargs: Any ) -> _models.PrivateEndpointConnection: """Gets information about the specified private endpoint connection. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param private_endpoint_connection_name: The private endpoint connection name. This must be unique within the account. Required. :type private_endpoint_connection_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: PrivateEndpointConnection or the result of cls(response) :rtype: ~azure.mgmt.batch.models.PrivateEndpointConnection :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.PrivateEndpointConnection] = kwargs.pop("cls", None) request = build_get_request( resource_group_name=resource_group_name, account_name=account_name, private_endpoint_connection_name=private_endpoint_connection_name, subscription_id=self._config.subscription_id, api_version=api_version, template_url=self.get.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize("PrivateEndpointConnection", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/privateEndpointConnections/{privateEndpointConnectionName}" } def _update_initial( self, resource_group_name: str, account_name: str, private_endpoint_connection_name: str, parameters: Union[_models.PrivateEndpointConnection, IO], if_match: Optional[str] = None, **kwargs: Any ) -> Optional[_models.PrivateEndpointConnection]: error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[Optional[_models.PrivateEndpointConnection]] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None if isinstance(parameters, (IOBase, bytes)): _content = parameters else: _json = self._serialize.body(parameters, "PrivateEndpointConnection") request = build_update_request( resource_group_name=resource_group_name, account_name=account_name, private_endpoint_connection_name=private_endpoint_connection_name, subscription_id=self._config.subscription_id, if_match=if_match, api_version=api_version, content_type=content_type, json=_json, content=_content, template_url=self._update_initial.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = None response_headers = {} if response.status_code == 200: deserialized = self._deserialize("PrivateEndpointConnection", pipeline_response) if response.status_code == 202: response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) if cls: return cls(pipeline_response, deserialized, response_headers) return deserialized _update_initial.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/privateEndpointConnections/{privateEndpointConnectionName}" } @overload def begin_update( self, resource_group_name: str, account_name: str, private_endpoint_connection_name: str, parameters: _models.PrivateEndpointConnection, if_match: Optional[str] = None, *, content_type: str = "application/json", **kwargs: Any ) -> LROPoller[_models.PrivateEndpointConnection]: """Updates the properties of an existing private endpoint connection. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param private_endpoint_connection_name: The private endpoint connection name. This must be unique within the account. Required. :type private_endpoint_connection_name: str :param parameters: PrivateEndpointConnection properties that should be updated. Properties that are supplied will be updated, any property not supplied will be unchanged. Required. :type parameters: ~azure.mgmt.batch.models.PrivateEndpointConnection :param if_match: The state (ETag) version of the private endpoint connection to update. This value can be omitted or set to "*" to apply the operation unconditionally. Default value is None. :type if_match: str :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.PollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of LROPoller that returns either PrivateEndpointConnection or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.batch.models.PrivateEndpointConnection] :raises ~azure.core.exceptions.HttpResponseError: """ @overload def begin_update( self, resource_group_name: str, account_name: str, private_endpoint_connection_name: str, parameters: IO, if_match: Optional[str] = None, *, content_type: str = "application/json", **kwargs: Any ) -> LROPoller[_models.PrivateEndpointConnection]: """Updates the properties of an existing private endpoint connection. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param private_endpoint_connection_name: The private endpoint connection name. This must be unique within the account. Required. :type private_endpoint_connection_name: str :param parameters: PrivateEndpointConnection properties that should be updated. Properties that are supplied will be updated, any property not supplied will be unchanged. Required. :type parameters: IO :param if_match: The state (ETag) version of the private endpoint connection to update. This value can be omitted or set to "*" to apply the operation unconditionally. Default value is None. :type if_match: str :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.PollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of LROPoller that returns either PrivateEndpointConnection or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.batch.models.PrivateEndpointConnection] :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace def begin_update( self, resource_group_name: str, account_name: str, private_endpoint_connection_name: str, parameters: Union[_models.PrivateEndpointConnection, IO], if_match: Optional[str] = None, **kwargs: Any ) -> LROPoller[_models.PrivateEndpointConnection]: """Updates the properties of an existing private endpoint connection. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param private_endpoint_connection_name: The private endpoint connection name. This must be unique within the account. Required. :type private_endpoint_connection_name: str :param parameters: PrivateEndpointConnection properties that should be updated. Properties that are supplied will be updated, any property not supplied will be unchanged. Is either a PrivateEndpointConnection type or a IO type. Required. :type parameters: ~azure.mgmt.batch.models.PrivateEndpointConnection or IO :param if_match: The state (ETag) version of the private endpoint connection to update. This value can be omitted or set to "*" to apply the operation unconditionally. Default value is None. :type if_match: str :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. Default value is None. :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.PollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of LROPoller that returns either PrivateEndpointConnection or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.batch.models.PrivateEndpointConnection] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.PrivateEndpointConnection] = kwargs.pop("cls", None) polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) cont_token: Optional[str] = kwargs.pop("continuation_token", None) if cont_token is None: raw_result = self._update_initial( resource_group_name=resource_group_name, account_name=account_name, private_endpoint_connection_name=private_endpoint_connection_name, parameters=parameters, if_match=if_match, api_version=api_version, content_type=content_type, cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): deserialized = self._deserialize("PrivateEndpointConnection", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized if polling is True: polling_method: PollingMethod = cast( PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs) ) elif polling is False: polling_method = cast(PollingMethod, NoPolling()) else: polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) return LROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore begin_update.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/privateEndpointConnections/{privateEndpointConnectionName}" } def _delete_initial( # pylint: disable=inconsistent-return-statements self, resource_group_name: str, account_name: str, private_endpoint_connection_name: str, **kwargs: Any ) -> None: error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[None] = kwargs.pop("cls", None) request = build_delete_request( resource_group_name=resource_group_name, account_name=account_name, private_endpoint_connection_name=private_endpoint_connection_name, subscription_id=self._config.subscription_id, api_version=api_version, template_url=self._delete_initial.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [202, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) response_headers = {} if response.status_code == 202: response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) if cls: return cls(pipeline_response, None, response_headers) _delete_initial.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/privateEndpointConnections/{privateEndpointConnectionName}" } @distributed_trace def begin_delete( self, resource_group_name: str, account_name: str, private_endpoint_connection_name: str, **kwargs: Any ) -> LROPoller[None]: """Deletes the specified private endpoint connection. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param private_endpoint_connection_name: The private endpoint connection name. This must be unique within the account. Required. :type private_endpoint_connection_name: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.PollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of LROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[None] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[None] = kwargs.pop("cls", None) polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) cont_token: Optional[str] = kwargs.pop("continuation_token", None) if cont_token is None: raw_result = self._delete_initial( # type: ignore resource_group_name=resource_group_name, account_name=account_name, private_endpoint_connection_name=private_endpoint_connection_name, api_version=api_version, cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) if polling is True: polling_method: PollingMethod = cast( PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs) ) elif polling is False: polling_method = cast(PollingMethod, NoPolling()) else: polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) return LROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore begin_delete.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/privateEndpointConnections/{privateEndpointConnectionName}" }
0.798029
0.082809
from io import IOBase from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, overload import urllib.parse from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, map_error, ) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models from .._serialization import Serializer from .._vendor import _convert_request, _format_url_section T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False def build_get_quotas_request(location_name: str, subscription_id: str, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-05-01")) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Batch/locations/{locationName}/quotas" ) # pylint: disable=line-too-long path_format_arguments = { "locationName": _SERIALIZER.url("location_name", location_name, "str"), "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_list_supported_virtual_machine_skus_request( location_name: str, subscription_id: str, *, maxresults: Optional[int] = None, filter: Optional[str] = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-05-01")) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Batch/locations/{locationName}/virtualMachineSkus", ) # pylint: disable=line-too-long path_format_arguments = { "locationName": _SERIALIZER.url("location_name", location_name, "str"), "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # Construct parameters if maxresults is not None: _params["maxresults"] = _SERIALIZER.query("maxresults", maxresults, "int") if filter is not None: _params["$filter"] = _SERIALIZER.query("filter", filter, "str") _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_list_supported_cloud_service_skus_request( location_name: str, subscription_id: str, *, maxresults: Optional[int] = None, filter: Optional[str] = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-05-01")) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Batch/locations/{locationName}/cloudServiceSkus", ) # pylint: disable=line-too-long path_format_arguments = { "locationName": _SERIALIZER.url("location_name", location_name, "str"), "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # Construct parameters if maxresults is not None: _params["maxresults"] = _SERIALIZER.query("maxresults", maxresults, "int") if filter is not None: _params["$filter"] = _SERIALIZER.query("filter", filter, "str") _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_check_name_availability_request(location_name: str, subscription_id: str, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-05-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Batch/locations/{locationName}/checkNameAvailability", ) # pylint: disable=line-too-long path_format_arguments = { "locationName": _SERIALIZER.url("location_name", location_name, "str"), "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers if content_type is not None: _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) class LocationOperations: """ .. warning:: **DO NOT** instantiate this class directly. Instead, you should access the following operations through :class:`~azure.mgmt.batch.BatchManagementClient`'s :attr:`location` attribute. """ models = _models def __init__(self, *args, **kwargs): input_args = list(args) self._client = input_args.pop(0) if input_args else kwargs.pop("client") self._config = input_args.pop(0) if input_args else kwargs.pop("config") self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace def get_quotas(self, location_name: str, **kwargs: Any) -> _models.BatchLocationQuota: """Gets the Batch service quotas for the specified subscription at the given location. :param location_name: The region for which to retrieve Batch service quotas. Required. :type location_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: BatchLocationQuota or the result of cls(response) :rtype: ~azure.mgmt.batch.models.BatchLocationQuota :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.BatchLocationQuota] = kwargs.pop("cls", None) request = build_get_quotas_request( location_name=location_name, subscription_id=self._config.subscription_id, api_version=api_version, template_url=self.get_quotas.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize("BatchLocationQuota", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get_quotas.metadata = { "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Batch/locations/{locationName}/quotas" } @distributed_trace def list_supported_virtual_machine_skus( self, location_name: str, maxresults: Optional[int] = None, filter: Optional[str] = None, **kwargs: Any ) -> Iterable["_models.SupportedSku"]: """Gets the list of Batch supported Virtual Machine VM sizes available at the given location. :param location_name: The region for which to retrieve Batch service supported SKUs. Required. :type location_name: str :param maxresults: The maximum number of items to return in the response. Default value is None. :type maxresults: int :param filter: OData filter expression. Valid properties for filtering are "familyName". Default value is None. :type filter: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either SupportedSku or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.batch.models.SupportedSku] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.SupportedSkusResult] = kwargs.pop("cls", None) error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_supported_virtual_machine_skus_request( location_name=location_name, subscription_id=self._config.subscription_id, maxresults=maxresults, filter=filter, api_version=api_version, template_url=self.list_supported_virtual_machine_skus.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) else: # make call to next link with the client's api-version _parsed_next_link = urllib.parse.urlparse(next_link) _next_request_params = case_insensitive_dict( { key: [urllib.parse.quote(v) for v in value] for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) _next_request_params["api-version"] = self._config.api_version request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) request.url = self._client.format_url(request.url) request.method = "GET" return request def extract_data(pipeline_response): deserialized = self._deserialize("SupportedSkusResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) # type: ignore return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return ItemPaged(get_next, extract_data) list_supported_virtual_machine_skus.metadata = { "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Batch/locations/{locationName}/virtualMachineSkus" } @distributed_trace def list_supported_cloud_service_skus( self, location_name: str, maxresults: Optional[int] = None, filter: Optional[str] = None, **kwargs: Any ) -> Iterable["_models.SupportedSku"]: """Gets the list of Batch supported Cloud Service VM sizes available at the given location. :param location_name: The region for which to retrieve Batch service supported SKUs. Required. :type location_name: str :param maxresults: The maximum number of items to return in the response. Default value is None. :type maxresults: int :param filter: OData filter expression. Valid properties for filtering are "familyName". Default value is None. :type filter: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either SupportedSku or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.batch.models.SupportedSku] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.SupportedSkusResult] = kwargs.pop("cls", None) error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_supported_cloud_service_skus_request( location_name=location_name, subscription_id=self._config.subscription_id, maxresults=maxresults, filter=filter, api_version=api_version, template_url=self.list_supported_cloud_service_skus.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) else: # make call to next link with the client's api-version _parsed_next_link = urllib.parse.urlparse(next_link) _next_request_params = case_insensitive_dict( { key: [urllib.parse.quote(v) for v in value] for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) _next_request_params["api-version"] = self._config.api_version request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) request.url = self._client.format_url(request.url) request.method = "GET" return request def extract_data(pipeline_response): deserialized = self._deserialize("SupportedSkusResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) # type: ignore return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return ItemPaged(get_next, extract_data) list_supported_cloud_service_skus.metadata = { "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Batch/locations/{locationName}/cloudServiceSkus" } @overload def check_name_availability( self, location_name: str, parameters: _models.CheckNameAvailabilityParameters, *, content_type: str = "application/json", **kwargs: Any ) -> _models.CheckNameAvailabilityResult: """Checks whether the Batch account name is available in the specified region. :param location_name: The desired region for the name check. Required. :type location_name: str :param parameters: Properties needed to check the availability of a name. Required. :type parameters: ~azure.mgmt.batch.models.CheckNameAvailabilityParameters :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: CheckNameAvailabilityResult or the result of cls(response) :rtype: ~azure.mgmt.batch.models.CheckNameAvailabilityResult :raises ~azure.core.exceptions.HttpResponseError: """ @overload def check_name_availability( self, location_name: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any ) -> _models.CheckNameAvailabilityResult: """Checks whether the Batch account name is available in the specified region. :param location_name: The desired region for the name check. Required. :type location_name: str :param parameters: Properties needed to check the availability of a name. Required. :type parameters: IO :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: CheckNameAvailabilityResult or the result of cls(response) :rtype: ~azure.mgmt.batch.models.CheckNameAvailabilityResult :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace def check_name_availability( self, location_name: str, parameters: Union[_models.CheckNameAvailabilityParameters, IO], **kwargs: Any ) -> _models.CheckNameAvailabilityResult: """Checks whether the Batch account name is available in the specified region. :param location_name: The desired region for the name check. Required. :type location_name: str :param parameters: Properties needed to check the availability of a name. Is either a CheckNameAvailabilityParameters type or a IO type. Required. :type parameters: ~azure.mgmt.batch.models.CheckNameAvailabilityParameters or IO :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. Default value is None. :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: CheckNameAvailabilityResult or the result of cls(response) :rtype: ~azure.mgmt.batch.models.CheckNameAvailabilityResult :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.CheckNameAvailabilityResult] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None if isinstance(parameters, (IOBase, bytes)): _content = parameters else: _json = self._serialize.body(parameters, "CheckNameAvailabilityParameters") request = build_check_name_availability_request( location_name=location_name, subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, content=_content, template_url=self.check_name_availability.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize("CheckNameAvailabilityResult", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized check_name_availability.metadata = { "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Batch/locations/{locationName}/checkNameAvailability" }
azure-mgmt-batch
/azure_mgmt_batch-17.1.0-py3-none-any.whl/azure/mgmt/batch/operations/_location_operations.py
_location_operations.py
from io import IOBase from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, overload import urllib.parse from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, map_error, ) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models from .._serialization import Serializer from .._vendor import _convert_request, _format_url_section T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False def build_get_quotas_request(location_name: str, subscription_id: str, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-05-01")) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Batch/locations/{locationName}/quotas" ) # pylint: disable=line-too-long path_format_arguments = { "locationName": _SERIALIZER.url("location_name", location_name, "str"), "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_list_supported_virtual_machine_skus_request( location_name: str, subscription_id: str, *, maxresults: Optional[int] = None, filter: Optional[str] = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-05-01")) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Batch/locations/{locationName}/virtualMachineSkus", ) # pylint: disable=line-too-long path_format_arguments = { "locationName": _SERIALIZER.url("location_name", location_name, "str"), "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # Construct parameters if maxresults is not None: _params["maxresults"] = _SERIALIZER.query("maxresults", maxresults, "int") if filter is not None: _params["$filter"] = _SERIALIZER.query("filter", filter, "str") _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_list_supported_cloud_service_skus_request( location_name: str, subscription_id: str, *, maxresults: Optional[int] = None, filter: Optional[str] = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-05-01")) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Batch/locations/{locationName}/cloudServiceSkus", ) # pylint: disable=line-too-long path_format_arguments = { "locationName": _SERIALIZER.url("location_name", location_name, "str"), "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # Construct parameters if maxresults is not None: _params["maxresults"] = _SERIALIZER.query("maxresults", maxresults, "int") if filter is not None: _params["$filter"] = _SERIALIZER.query("filter", filter, "str") _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_check_name_availability_request(location_name: str, subscription_id: str, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-05-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Batch/locations/{locationName}/checkNameAvailability", ) # pylint: disable=line-too-long path_format_arguments = { "locationName": _SERIALIZER.url("location_name", location_name, "str"), "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers if content_type is not None: _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) class LocationOperations: """ .. warning:: **DO NOT** instantiate this class directly. Instead, you should access the following operations through :class:`~azure.mgmt.batch.BatchManagementClient`'s :attr:`location` attribute. """ models = _models def __init__(self, *args, **kwargs): input_args = list(args) self._client = input_args.pop(0) if input_args else kwargs.pop("client") self._config = input_args.pop(0) if input_args else kwargs.pop("config") self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace def get_quotas(self, location_name: str, **kwargs: Any) -> _models.BatchLocationQuota: """Gets the Batch service quotas for the specified subscription at the given location. :param location_name: The region for which to retrieve Batch service quotas. Required. :type location_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: BatchLocationQuota or the result of cls(response) :rtype: ~azure.mgmt.batch.models.BatchLocationQuota :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.BatchLocationQuota] = kwargs.pop("cls", None) request = build_get_quotas_request( location_name=location_name, subscription_id=self._config.subscription_id, api_version=api_version, template_url=self.get_quotas.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize("BatchLocationQuota", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get_quotas.metadata = { "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Batch/locations/{locationName}/quotas" } @distributed_trace def list_supported_virtual_machine_skus( self, location_name: str, maxresults: Optional[int] = None, filter: Optional[str] = None, **kwargs: Any ) -> Iterable["_models.SupportedSku"]: """Gets the list of Batch supported Virtual Machine VM sizes available at the given location. :param location_name: The region for which to retrieve Batch service supported SKUs. Required. :type location_name: str :param maxresults: The maximum number of items to return in the response. Default value is None. :type maxresults: int :param filter: OData filter expression. Valid properties for filtering are "familyName". Default value is None. :type filter: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either SupportedSku or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.batch.models.SupportedSku] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.SupportedSkusResult] = kwargs.pop("cls", None) error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_supported_virtual_machine_skus_request( location_name=location_name, subscription_id=self._config.subscription_id, maxresults=maxresults, filter=filter, api_version=api_version, template_url=self.list_supported_virtual_machine_skus.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) else: # make call to next link with the client's api-version _parsed_next_link = urllib.parse.urlparse(next_link) _next_request_params = case_insensitive_dict( { key: [urllib.parse.quote(v) for v in value] for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) _next_request_params["api-version"] = self._config.api_version request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) request.url = self._client.format_url(request.url) request.method = "GET" return request def extract_data(pipeline_response): deserialized = self._deserialize("SupportedSkusResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) # type: ignore return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return ItemPaged(get_next, extract_data) list_supported_virtual_machine_skus.metadata = { "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Batch/locations/{locationName}/virtualMachineSkus" } @distributed_trace def list_supported_cloud_service_skus( self, location_name: str, maxresults: Optional[int] = None, filter: Optional[str] = None, **kwargs: Any ) -> Iterable["_models.SupportedSku"]: """Gets the list of Batch supported Cloud Service VM sizes available at the given location. :param location_name: The region for which to retrieve Batch service supported SKUs. Required. :type location_name: str :param maxresults: The maximum number of items to return in the response. Default value is None. :type maxresults: int :param filter: OData filter expression. Valid properties for filtering are "familyName". Default value is None. :type filter: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either SupportedSku or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.batch.models.SupportedSku] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.SupportedSkusResult] = kwargs.pop("cls", None) error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_supported_cloud_service_skus_request( location_name=location_name, subscription_id=self._config.subscription_id, maxresults=maxresults, filter=filter, api_version=api_version, template_url=self.list_supported_cloud_service_skus.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) else: # make call to next link with the client's api-version _parsed_next_link = urllib.parse.urlparse(next_link) _next_request_params = case_insensitive_dict( { key: [urllib.parse.quote(v) for v in value] for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) _next_request_params["api-version"] = self._config.api_version request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) request.url = self._client.format_url(request.url) request.method = "GET" return request def extract_data(pipeline_response): deserialized = self._deserialize("SupportedSkusResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) # type: ignore return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return ItemPaged(get_next, extract_data) list_supported_cloud_service_skus.metadata = { "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Batch/locations/{locationName}/cloudServiceSkus" } @overload def check_name_availability( self, location_name: str, parameters: _models.CheckNameAvailabilityParameters, *, content_type: str = "application/json", **kwargs: Any ) -> _models.CheckNameAvailabilityResult: """Checks whether the Batch account name is available in the specified region. :param location_name: The desired region for the name check. Required. :type location_name: str :param parameters: Properties needed to check the availability of a name. Required. :type parameters: ~azure.mgmt.batch.models.CheckNameAvailabilityParameters :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: CheckNameAvailabilityResult or the result of cls(response) :rtype: ~azure.mgmt.batch.models.CheckNameAvailabilityResult :raises ~azure.core.exceptions.HttpResponseError: """ @overload def check_name_availability( self, location_name: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any ) -> _models.CheckNameAvailabilityResult: """Checks whether the Batch account name is available in the specified region. :param location_name: The desired region for the name check. Required. :type location_name: str :param parameters: Properties needed to check the availability of a name. Required. :type parameters: IO :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: CheckNameAvailabilityResult or the result of cls(response) :rtype: ~azure.mgmt.batch.models.CheckNameAvailabilityResult :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace def check_name_availability( self, location_name: str, parameters: Union[_models.CheckNameAvailabilityParameters, IO], **kwargs: Any ) -> _models.CheckNameAvailabilityResult: """Checks whether the Batch account name is available in the specified region. :param location_name: The desired region for the name check. Required. :type location_name: str :param parameters: Properties needed to check the availability of a name. Is either a CheckNameAvailabilityParameters type or a IO type. Required. :type parameters: ~azure.mgmt.batch.models.CheckNameAvailabilityParameters or IO :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. Default value is None. :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: CheckNameAvailabilityResult or the result of cls(response) :rtype: ~azure.mgmt.batch.models.CheckNameAvailabilityResult :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.CheckNameAvailabilityResult] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None if isinstance(parameters, (IOBase, bytes)): _content = parameters else: _json = self._serialize.body(parameters, "CheckNameAvailabilityParameters") request = build_check_name_availability_request( location_name=location_name, subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, content=_content, template_url=self.check_name_availability.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize("CheckNameAvailabilityResult", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized check_name_availability.metadata = { "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Batch/locations/{locationName}/checkNameAvailability" }
0.795102
0.069226
from typing import Any, Callable, Dict, Iterable, Optional, TypeVar import urllib.parse from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, map_error, ) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models from .._serialization import Serializer from .._vendor import _convert_request T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False def build_list_request(**kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-05-01")) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop("template_url", "/providers/Microsoft.Batch/operations") # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) class Operations: """ .. warning:: **DO NOT** instantiate this class directly. Instead, you should access the following operations through :class:`~azure.mgmt.batch.BatchManagementClient`'s :attr:`operations` attribute. """ models = _models def __init__(self, *args, **kwargs): input_args = list(args) self._client = input_args.pop(0) if input_args else kwargs.pop("client") self._config = input_args.pop(0) if input_args else kwargs.pop("config") self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace def list(self, **kwargs: Any) -> Iterable["_models.Operation"]: """Lists available operations for the Microsoft.Batch provider. :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either Operation or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.batch.models.Operation] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.OperationListResult] = kwargs.pop("cls", None) error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_request( api_version=api_version, template_url=self.list.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) else: # make call to next link with the client's api-version _parsed_next_link = urllib.parse.urlparse(next_link) _next_request_params = case_insensitive_dict( { key: [urllib.parse.quote(v) for v in value] for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) _next_request_params["api-version"] = self._config.api_version request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) request.url = self._client.format_url(request.url) request.method = "GET" return request def extract_data(pipeline_response): deserialized = self._deserialize("OperationListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) # type: ignore return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return ItemPaged(get_next, extract_data) list.metadata = {"url": "/providers/Microsoft.Batch/operations"}
azure-mgmt-batch
/azure_mgmt_batch-17.1.0-py3-none-any.whl/azure/mgmt/batch/operations/_operations.py
_operations.py
from typing import Any, Callable, Dict, Iterable, Optional, TypeVar import urllib.parse from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, map_error, ) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models from .._serialization import Serializer from .._vendor import _convert_request T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False def build_list_request(**kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-05-01")) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop("template_url", "/providers/Microsoft.Batch/operations") # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) class Operations: """ .. warning:: **DO NOT** instantiate this class directly. Instead, you should access the following operations through :class:`~azure.mgmt.batch.BatchManagementClient`'s :attr:`operations` attribute. """ models = _models def __init__(self, *args, **kwargs): input_args = list(args) self._client = input_args.pop(0) if input_args else kwargs.pop("client") self._config = input_args.pop(0) if input_args else kwargs.pop("config") self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace def list(self, **kwargs: Any) -> Iterable["_models.Operation"]: """Lists available operations for the Microsoft.Batch provider. :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either Operation or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.batch.models.Operation] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.OperationListResult] = kwargs.pop("cls", None) error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_request( api_version=api_version, template_url=self.list.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) else: # make call to next link with the client's api-version _parsed_next_link = urllib.parse.urlparse(next_link) _next_request_params = case_insensitive_dict( { key: [urllib.parse.quote(v) for v in value] for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) _next_request_params["api-version"] = self._config.api_version request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) request.url = self._client.format_url(request.url) request.method = "GET" return request def extract_data(pipeline_response): deserialized = self._deserialize("OperationListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) # type: ignore return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return ItemPaged(get_next, extract_data) list.metadata = {"url": "/providers/Microsoft.Batch/operations"}
0.836888
0.078607
from io import IOBase from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, cast, overload import urllib.parse from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, map_error, ) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse from azure.core.polling import LROPoller, NoPolling, PollingMethod from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.arm_polling import ARMPolling from .. import models as _models from .._serialization import Serializer from .._vendor import _convert_request, _format_url_section T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False def build_list_by_batch_account_request( resource_group_name: str, account_name: str, subscription_id: str, *, maxresults: Optional[int] = None, select: Optional[str] = None, filter: Optional[str] = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-05-01")) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/certificates", ) # pylint: disable=line-too-long path_format_arguments = { "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), "accountName": _SERIALIZER.url( "account_name", account_name, "str", max_length=24, min_length=3, pattern=r"^[a-zA-Z0-9]+$" ), "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # Construct parameters if maxresults is not None: _params["maxresults"] = _SERIALIZER.query("maxresults", maxresults, "int") if select is not None: _params["$select"] = _SERIALIZER.query("select", select, "str") if filter is not None: _params["$filter"] = _SERIALIZER.query("filter", filter, "str") _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_create_request( resource_group_name: str, account_name: str, certificate_name: str, subscription_id: str, *, if_match: Optional[str] = None, if_none_match: Optional[str] = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-05-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/certificates/{certificateName}", ) # pylint: disable=line-too-long path_format_arguments = { "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), "accountName": _SERIALIZER.url( "account_name", account_name, "str", max_length=24, min_length=3, pattern=r"^[a-zA-Z0-9]+$" ), "certificateName": _SERIALIZER.url( "certificate_name", certificate_name, "str", max_length=45, min_length=5, pattern=r"^[\w]+-[\w]+$" ), "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers if if_match is not None: _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") if if_none_match is not None: _headers["If-None-Match"] = _SERIALIZER.header("if_none_match", if_none_match, "str") if content_type is not None: _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) def build_update_request( resource_group_name: str, account_name: str, certificate_name: str, subscription_id: str, *, if_match: Optional[str] = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-05-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/certificates/{certificateName}", ) # pylint: disable=line-too-long path_format_arguments = { "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), "accountName": _SERIALIZER.url( "account_name", account_name, "str", max_length=24, min_length=3, pattern=r"^[a-zA-Z0-9]+$" ), "certificateName": _SERIALIZER.url( "certificate_name", certificate_name, "str", max_length=45, min_length=5, pattern=r"^[\w]+-[\w]+$" ), "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers if if_match is not None: _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") if content_type is not None: _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs) def build_delete_request( resource_group_name: str, account_name: str, certificate_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-05-01")) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/certificates/{certificateName}", ) # pylint: disable=line-too-long path_format_arguments = { "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), "accountName": _SERIALIZER.url( "account_name", account_name, "str", max_length=24, min_length=3, pattern=r"^[a-zA-Z0-9]+$" ), "certificateName": _SERIALIZER.url( "certificate_name", certificate_name, "str", max_length=45, min_length=5, pattern=r"^[\w]+-[\w]+$" ), "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) def build_get_request( resource_group_name: str, account_name: str, certificate_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-05-01")) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/certificates/{certificateName}", ) # pylint: disable=line-too-long path_format_arguments = { "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), "accountName": _SERIALIZER.url( "account_name", account_name, "str", max_length=24, min_length=3, pattern=r"^[a-zA-Z0-9]+$" ), "certificateName": _SERIALIZER.url( "certificate_name", certificate_name, "str", max_length=45, min_length=5, pattern=r"^[\w]+-[\w]+$" ), "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_cancel_deletion_request( resource_group_name: str, account_name: str, certificate_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-05-01")) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/certificates/{certificateName}/cancelDelete", ) # pylint: disable=line-too-long path_format_arguments = { "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), "accountName": _SERIALIZER.url( "account_name", account_name, "str", max_length=24, min_length=3, pattern=r"^[a-zA-Z0-9]+$" ), "certificateName": _SERIALIZER.url( "certificate_name", certificate_name, "str", max_length=45, min_length=5, pattern=r"^[\w]+-[\w]+$" ), "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) class CertificateOperations: """ .. warning:: **DO NOT** instantiate this class directly. Instead, you should access the following operations through :class:`~azure.mgmt.batch.BatchManagementClient`'s :attr:`certificate` attribute. """ models = _models def __init__(self, *args, **kwargs): input_args = list(args) self._client = input_args.pop(0) if input_args else kwargs.pop("client") self._config = input_args.pop(0) if input_args else kwargs.pop("config") self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace def list_by_batch_account( self, resource_group_name: str, account_name: str, maxresults: Optional[int] = None, select: Optional[str] = None, filter: Optional[str] = None, **kwargs: Any ) -> Iterable["_models.Certificate"]: """Lists all of the certificates in the specified account. Warning: This operation is deprecated and will be removed after February, 2024. Please use the `Azure KeyVault Extension <https://learn.microsoft.com/azure/batch/batch-certificate-migration-guide>`_ instead. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param maxresults: The maximum number of items to return in the response. Default value is None. :type maxresults: int :param select: Comma separated list of properties that should be returned. e.g. "properties/provisioningState". Only top level properties under properties/ are valid for selection. Default value is None. :type select: str :param filter: OData filter expression. Valid properties for filtering are "properties/provisioningState", "properties/provisioningStateTransitionTime", "name". Default value is None. :type filter: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either Certificate or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.batch.models.Certificate] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.ListCertificatesResult] = kwargs.pop("cls", None) error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_by_batch_account_request( resource_group_name=resource_group_name, account_name=account_name, subscription_id=self._config.subscription_id, maxresults=maxresults, select=select, filter=filter, api_version=api_version, template_url=self.list_by_batch_account.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) else: # make call to next link with the client's api-version _parsed_next_link = urllib.parse.urlparse(next_link) _next_request_params = case_insensitive_dict( { key: [urllib.parse.quote(v) for v in value] for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) _next_request_params["api-version"] = self._config.api_version request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) request.url = self._client.format_url(request.url) request.method = "GET" return request def extract_data(pipeline_response): deserialized = self._deserialize("ListCertificatesResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) # type: ignore return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return ItemPaged(get_next, extract_data) list_by_batch_account.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/certificates" } @overload def create( self, resource_group_name: str, account_name: str, certificate_name: str, parameters: _models.CertificateCreateOrUpdateParameters, if_match: Optional[str] = None, if_none_match: Optional[str] = None, *, content_type: str = "application/json", **kwargs: Any ) -> _models.Certificate: """Creates a new certificate inside the specified account. Warning: This operation is deprecated and will be removed after February, 2024. Please use the `Azure KeyVault Extension <https://learn.microsoft.com/azure/batch/batch-certificate-migration-guide>`_ instead. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param certificate_name: The identifier for the certificate. This must be made up of algorithm and thumbprint separated by a dash, and must match the certificate data in the request. For example SHA1-a3d1c5. Required. :type certificate_name: str :param parameters: Additional parameters for certificate creation. Required. :type parameters: ~azure.mgmt.batch.models.CertificateCreateOrUpdateParameters :param if_match: The entity state (ETag) version of the certificate to update. A value of "*" can be used to apply the operation only if the certificate already exists. If omitted, this operation will always be applied. Default value is None. :type if_match: str :param if_none_match: Set to '*' to allow a new certificate to be created, but to prevent updating an existing certificate. Other values will be ignored. Default value is None. :type if_none_match: str :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Certificate or the result of cls(response) :rtype: ~azure.mgmt.batch.models.Certificate :raises ~azure.core.exceptions.HttpResponseError: """ @overload def create( self, resource_group_name: str, account_name: str, certificate_name: str, parameters: IO, if_match: Optional[str] = None, if_none_match: Optional[str] = None, *, content_type: str = "application/json", **kwargs: Any ) -> _models.Certificate: """Creates a new certificate inside the specified account. Warning: This operation is deprecated and will be removed after February, 2024. Please use the `Azure KeyVault Extension <https://learn.microsoft.com/azure/batch/batch-certificate-migration-guide>`_ instead. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param certificate_name: The identifier for the certificate. This must be made up of algorithm and thumbprint separated by a dash, and must match the certificate data in the request. For example SHA1-a3d1c5. Required. :type certificate_name: str :param parameters: Additional parameters for certificate creation. Required. :type parameters: IO :param if_match: The entity state (ETag) version of the certificate to update. A value of "*" can be used to apply the operation only if the certificate already exists. If omitted, this operation will always be applied. Default value is None. :type if_match: str :param if_none_match: Set to '*' to allow a new certificate to be created, but to prevent updating an existing certificate. Other values will be ignored. Default value is None. :type if_none_match: str :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Certificate or the result of cls(response) :rtype: ~azure.mgmt.batch.models.Certificate :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace def create( self, resource_group_name: str, account_name: str, certificate_name: str, parameters: Union[_models.CertificateCreateOrUpdateParameters, IO], if_match: Optional[str] = None, if_none_match: Optional[str] = None, **kwargs: Any ) -> _models.Certificate: """Creates a new certificate inside the specified account. Warning: This operation is deprecated and will be removed after February, 2024. Please use the `Azure KeyVault Extension <https://learn.microsoft.com/azure/batch/batch-certificate-migration-guide>`_ instead. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param certificate_name: The identifier for the certificate. This must be made up of algorithm and thumbprint separated by a dash, and must match the certificate data in the request. For example SHA1-a3d1c5. Required. :type certificate_name: str :param parameters: Additional parameters for certificate creation. Is either a CertificateCreateOrUpdateParameters type or a IO type. Required. :type parameters: ~azure.mgmt.batch.models.CertificateCreateOrUpdateParameters or IO :param if_match: The entity state (ETag) version of the certificate to update. A value of "*" can be used to apply the operation only if the certificate already exists. If omitted, this operation will always be applied. Default value is None. :type if_match: str :param if_none_match: Set to '*' to allow a new certificate to be created, but to prevent updating an existing certificate. Other values will be ignored. Default value is None. :type if_none_match: str :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. Default value is None. :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Certificate or the result of cls(response) :rtype: ~azure.mgmt.batch.models.Certificate :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.Certificate] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None if isinstance(parameters, (IOBase, bytes)): _content = parameters else: _json = self._serialize.body(parameters, "CertificateCreateOrUpdateParameters") request = build_create_request( resource_group_name=resource_group_name, account_name=account_name, certificate_name=certificate_name, subscription_id=self._config.subscription_id, if_match=if_match, if_none_match=if_none_match, api_version=api_version, content_type=content_type, json=_json, content=_content, template_url=self.create.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) response_headers = {} response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) deserialized = self._deserialize("Certificate", pipeline_response) if cls: return cls(pipeline_response, deserialized, response_headers) return deserialized create.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/certificates/{certificateName}" } @overload def update( self, resource_group_name: str, account_name: str, certificate_name: str, parameters: _models.CertificateCreateOrUpdateParameters, if_match: Optional[str] = None, *, content_type: str = "application/json", **kwargs: Any ) -> _models.Certificate: """Updates the properties of an existing certificate. Warning: This operation is deprecated and will be removed after February, 2024. Please use the `Azure KeyVault Extension <https://learn.microsoft.com/azure/batch/batch-certificate-migration-guide>`_ instead. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param certificate_name: The identifier for the certificate. This must be made up of algorithm and thumbprint separated by a dash, and must match the certificate data in the request. For example SHA1-a3d1c5. Required. :type certificate_name: str :param parameters: Certificate entity to update. Required. :type parameters: ~azure.mgmt.batch.models.CertificateCreateOrUpdateParameters :param if_match: The entity state (ETag) version of the certificate to update. This value can be omitted or set to "*" to apply the operation unconditionally. Default value is None. :type if_match: str :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Certificate or the result of cls(response) :rtype: ~azure.mgmt.batch.models.Certificate :raises ~azure.core.exceptions.HttpResponseError: """ @overload def update( self, resource_group_name: str, account_name: str, certificate_name: str, parameters: IO, if_match: Optional[str] = None, *, content_type: str = "application/json", **kwargs: Any ) -> _models.Certificate: """Updates the properties of an existing certificate. Warning: This operation is deprecated and will be removed after February, 2024. Please use the `Azure KeyVault Extension <https://learn.microsoft.com/azure/batch/batch-certificate-migration-guide>`_ instead. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param certificate_name: The identifier for the certificate. This must be made up of algorithm and thumbprint separated by a dash, and must match the certificate data in the request. For example SHA1-a3d1c5. Required. :type certificate_name: str :param parameters: Certificate entity to update. Required. :type parameters: IO :param if_match: The entity state (ETag) version of the certificate to update. This value can be omitted or set to "*" to apply the operation unconditionally. Default value is None. :type if_match: str :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Certificate or the result of cls(response) :rtype: ~azure.mgmt.batch.models.Certificate :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace def update( self, resource_group_name: str, account_name: str, certificate_name: str, parameters: Union[_models.CertificateCreateOrUpdateParameters, IO], if_match: Optional[str] = None, **kwargs: Any ) -> _models.Certificate: """Updates the properties of an existing certificate. Warning: This operation is deprecated and will be removed after February, 2024. Please use the `Azure KeyVault Extension <https://learn.microsoft.com/azure/batch/batch-certificate-migration-guide>`_ instead. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param certificate_name: The identifier for the certificate. This must be made up of algorithm and thumbprint separated by a dash, and must match the certificate data in the request. For example SHA1-a3d1c5. Required. :type certificate_name: str :param parameters: Certificate entity to update. Is either a CertificateCreateOrUpdateParameters type or a IO type. Required. :type parameters: ~azure.mgmt.batch.models.CertificateCreateOrUpdateParameters or IO :param if_match: The entity state (ETag) version of the certificate to update. This value can be omitted or set to "*" to apply the operation unconditionally. Default value is None. :type if_match: str :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. Default value is None. :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Certificate or the result of cls(response) :rtype: ~azure.mgmt.batch.models.Certificate :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.Certificate] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None if isinstance(parameters, (IOBase, bytes)): _content = parameters else: _json = self._serialize.body(parameters, "CertificateCreateOrUpdateParameters") request = build_update_request( resource_group_name=resource_group_name, account_name=account_name, certificate_name=certificate_name, subscription_id=self._config.subscription_id, if_match=if_match, api_version=api_version, content_type=content_type, json=_json, content=_content, template_url=self.update.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) response_headers = {} response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) deserialized = self._deserialize("Certificate", pipeline_response) if cls: return cls(pipeline_response, deserialized, response_headers) return deserialized update.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/certificates/{certificateName}" } def _delete_initial( # pylint: disable=inconsistent-return-statements self, resource_group_name: str, account_name: str, certificate_name: str, **kwargs: Any ) -> None: error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[None] = kwargs.pop("cls", None) request = build_delete_request( resource_group_name=resource_group_name, account_name=account_name, certificate_name=certificate_name, subscription_id=self._config.subscription_id, api_version=api_version, template_url=self._delete_initial.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) response_headers = {} if response.status_code == 202: response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) if cls: return cls(pipeline_response, None, response_headers) _delete_initial.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/certificates/{certificateName}" } @distributed_trace def begin_delete( self, resource_group_name: str, account_name: str, certificate_name: str, **kwargs: Any ) -> LROPoller[None]: """Deletes the specified certificate. Warning: This operation is deprecated and will be removed after February, 2024. Please use the `Azure KeyVault Extension <https://learn.microsoft.com/azure/batch/batch-certificate-migration-guide>`_ instead. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param certificate_name: The identifier for the certificate. This must be made up of algorithm and thumbprint separated by a dash, and must match the certificate data in the request. For example SHA1-a3d1c5. Required. :type certificate_name: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.PollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of LROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[None] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[None] = kwargs.pop("cls", None) polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) cont_token: Optional[str] = kwargs.pop("continuation_token", None) if cont_token is None: raw_result = self._delete_initial( # type: ignore resource_group_name=resource_group_name, account_name=account_name, certificate_name=certificate_name, api_version=api_version, cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) if polling is True: polling_method: PollingMethod = cast( PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) ) elif polling is False: polling_method = cast(PollingMethod, NoPolling()) else: polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) return LROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore begin_delete.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/certificates/{certificateName}" } @distributed_trace def get( self, resource_group_name: str, account_name: str, certificate_name: str, **kwargs: Any ) -> _models.Certificate: """Gets information about the specified certificate. Warning: This operation is deprecated and will be removed after February, 2024. Please use the `Azure KeyVault Extension <https://learn.microsoft.com/azure/batch/batch-certificate-migration-guide>`_ instead. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param certificate_name: The identifier for the certificate. This must be made up of algorithm and thumbprint separated by a dash, and must match the certificate data in the request. For example SHA1-a3d1c5. Required. :type certificate_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Certificate or the result of cls(response) :rtype: ~azure.mgmt.batch.models.Certificate :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.Certificate] = kwargs.pop("cls", None) request = build_get_request( resource_group_name=resource_group_name, account_name=account_name, certificate_name=certificate_name, subscription_id=self._config.subscription_id, api_version=api_version, template_url=self.get.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) response_headers = {} response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) deserialized = self._deserialize("Certificate", pipeline_response) if cls: return cls(pipeline_response, deserialized, response_headers) return deserialized get.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/certificates/{certificateName}" } @distributed_trace def cancel_deletion( self, resource_group_name: str, account_name: str, certificate_name: str, **kwargs: Any ) -> _models.Certificate: """Cancels a failed deletion of a certificate from the specified account. If you try to delete a certificate that is being used by a pool or compute node, the status of the certificate changes to deleteFailed. If you decide that you want to continue using the certificate, you can use this operation to set the status of the certificate back to active. If you intend to delete the certificate, you do not need to run this operation after the deletion failed. You must make sure that the certificate is not being used by any resources, and then you can try again to delete the certificate. Warning: This operation is deprecated and will be removed after February, 2024. Please use the `Azure KeyVault Extension <https://learn.microsoft.com/azure/batch/batch-certificate-migration-guide>`_ instead. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param certificate_name: The identifier for the certificate. This must be made up of algorithm and thumbprint separated by a dash, and must match the certificate data in the request. For example SHA1-a3d1c5. Required. :type certificate_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Certificate or the result of cls(response) :rtype: ~azure.mgmt.batch.models.Certificate :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.Certificate] = kwargs.pop("cls", None) request = build_cancel_deletion_request( resource_group_name=resource_group_name, account_name=account_name, certificate_name=certificate_name, subscription_id=self._config.subscription_id, api_version=api_version, template_url=self.cancel_deletion.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) response_headers = {} response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) deserialized = self._deserialize("Certificate", pipeline_response) if cls: return cls(pipeline_response, deserialized, response_headers) return deserialized cancel_deletion.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/certificates/{certificateName}/cancelDelete" }
azure-mgmt-batch
/azure_mgmt_batch-17.1.0-py3-none-any.whl/azure/mgmt/batch/operations/_certificate_operations.py
_certificate_operations.py
from io import IOBase from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, cast, overload import urllib.parse from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, map_error, ) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse from azure.core.polling import LROPoller, NoPolling, PollingMethod from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.arm_polling import ARMPolling from .. import models as _models from .._serialization import Serializer from .._vendor import _convert_request, _format_url_section T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False def build_list_by_batch_account_request( resource_group_name: str, account_name: str, subscription_id: str, *, maxresults: Optional[int] = None, select: Optional[str] = None, filter: Optional[str] = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-05-01")) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/certificates", ) # pylint: disable=line-too-long path_format_arguments = { "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), "accountName": _SERIALIZER.url( "account_name", account_name, "str", max_length=24, min_length=3, pattern=r"^[a-zA-Z0-9]+$" ), "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # Construct parameters if maxresults is not None: _params["maxresults"] = _SERIALIZER.query("maxresults", maxresults, "int") if select is not None: _params["$select"] = _SERIALIZER.query("select", select, "str") if filter is not None: _params["$filter"] = _SERIALIZER.query("filter", filter, "str") _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_create_request( resource_group_name: str, account_name: str, certificate_name: str, subscription_id: str, *, if_match: Optional[str] = None, if_none_match: Optional[str] = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-05-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/certificates/{certificateName}", ) # pylint: disable=line-too-long path_format_arguments = { "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), "accountName": _SERIALIZER.url( "account_name", account_name, "str", max_length=24, min_length=3, pattern=r"^[a-zA-Z0-9]+$" ), "certificateName": _SERIALIZER.url( "certificate_name", certificate_name, "str", max_length=45, min_length=5, pattern=r"^[\w]+-[\w]+$" ), "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers if if_match is not None: _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") if if_none_match is not None: _headers["If-None-Match"] = _SERIALIZER.header("if_none_match", if_none_match, "str") if content_type is not None: _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) def build_update_request( resource_group_name: str, account_name: str, certificate_name: str, subscription_id: str, *, if_match: Optional[str] = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-05-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/certificates/{certificateName}", ) # pylint: disable=line-too-long path_format_arguments = { "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), "accountName": _SERIALIZER.url( "account_name", account_name, "str", max_length=24, min_length=3, pattern=r"^[a-zA-Z0-9]+$" ), "certificateName": _SERIALIZER.url( "certificate_name", certificate_name, "str", max_length=45, min_length=5, pattern=r"^[\w]+-[\w]+$" ), "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers if if_match is not None: _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") if content_type is not None: _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs) def build_delete_request( resource_group_name: str, account_name: str, certificate_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-05-01")) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/certificates/{certificateName}", ) # pylint: disable=line-too-long path_format_arguments = { "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), "accountName": _SERIALIZER.url( "account_name", account_name, "str", max_length=24, min_length=3, pattern=r"^[a-zA-Z0-9]+$" ), "certificateName": _SERIALIZER.url( "certificate_name", certificate_name, "str", max_length=45, min_length=5, pattern=r"^[\w]+-[\w]+$" ), "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) def build_get_request( resource_group_name: str, account_name: str, certificate_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-05-01")) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/certificates/{certificateName}", ) # pylint: disable=line-too-long path_format_arguments = { "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), "accountName": _SERIALIZER.url( "account_name", account_name, "str", max_length=24, min_length=3, pattern=r"^[a-zA-Z0-9]+$" ), "certificateName": _SERIALIZER.url( "certificate_name", certificate_name, "str", max_length=45, min_length=5, pattern=r"^[\w]+-[\w]+$" ), "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_cancel_deletion_request( resource_group_name: str, account_name: str, certificate_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-05-01")) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/certificates/{certificateName}/cancelDelete", ) # pylint: disable=line-too-long path_format_arguments = { "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), "accountName": _SERIALIZER.url( "account_name", account_name, "str", max_length=24, min_length=3, pattern=r"^[a-zA-Z0-9]+$" ), "certificateName": _SERIALIZER.url( "certificate_name", certificate_name, "str", max_length=45, min_length=5, pattern=r"^[\w]+-[\w]+$" ), "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) class CertificateOperations: """ .. warning:: **DO NOT** instantiate this class directly. Instead, you should access the following operations through :class:`~azure.mgmt.batch.BatchManagementClient`'s :attr:`certificate` attribute. """ models = _models def __init__(self, *args, **kwargs): input_args = list(args) self._client = input_args.pop(0) if input_args else kwargs.pop("client") self._config = input_args.pop(0) if input_args else kwargs.pop("config") self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace def list_by_batch_account( self, resource_group_name: str, account_name: str, maxresults: Optional[int] = None, select: Optional[str] = None, filter: Optional[str] = None, **kwargs: Any ) -> Iterable["_models.Certificate"]: """Lists all of the certificates in the specified account. Warning: This operation is deprecated and will be removed after February, 2024. Please use the `Azure KeyVault Extension <https://learn.microsoft.com/azure/batch/batch-certificate-migration-guide>`_ instead. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param maxresults: The maximum number of items to return in the response. Default value is None. :type maxresults: int :param select: Comma separated list of properties that should be returned. e.g. "properties/provisioningState". Only top level properties under properties/ are valid for selection. Default value is None. :type select: str :param filter: OData filter expression. Valid properties for filtering are "properties/provisioningState", "properties/provisioningStateTransitionTime", "name". Default value is None. :type filter: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either Certificate or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.batch.models.Certificate] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.ListCertificatesResult] = kwargs.pop("cls", None) error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_by_batch_account_request( resource_group_name=resource_group_name, account_name=account_name, subscription_id=self._config.subscription_id, maxresults=maxresults, select=select, filter=filter, api_version=api_version, template_url=self.list_by_batch_account.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) else: # make call to next link with the client's api-version _parsed_next_link = urllib.parse.urlparse(next_link) _next_request_params = case_insensitive_dict( { key: [urllib.parse.quote(v) for v in value] for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) _next_request_params["api-version"] = self._config.api_version request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) request.url = self._client.format_url(request.url) request.method = "GET" return request def extract_data(pipeline_response): deserialized = self._deserialize("ListCertificatesResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) # type: ignore return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return ItemPaged(get_next, extract_data) list_by_batch_account.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/certificates" } @overload def create( self, resource_group_name: str, account_name: str, certificate_name: str, parameters: _models.CertificateCreateOrUpdateParameters, if_match: Optional[str] = None, if_none_match: Optional[str] = None, *, content_type: str = "application/json", **kwargs: Any ) -> _models.Certificate: """Creates a new certificate inside the specified account. Warning: This operation is deprecated and will be removed after February, 2024. Please use the `Azure KeyVault Extension <https://learn.microsoft.com/azure/batch/batch-certificate-migration-guide>`_ instead. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param certificate_name: The identifier for the certificate. This must be made up of algorithm and thumbprint separated by a dash, and must match the certificate data in the request. For example SHA1-a3d1c5. Required. :type certificate_name: str :param parameters: Additional parameters for certificate creation. Required. :type parameters: ~azure.mgmt.batch.models.CertificateCreateOrUpdateParameters :param if_match: The entity state (ETag) version of the certificate to update. A value of "*" can be used to apply the operation only if the certificate already exists. If omitted, this operation will always be applied. Default value is None. :type if_match: str :param if_none_match: Set to '*' to allow a new certificate to be created, but to prevent updating an existing certificate. Other values will be ignored. Default value is None. :type if_none_match: str :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Certificate or the result of cls(response) :rtype: ~azure.mgmt.batch.models.Certificate :raises ~azure.core.exceptions.HttpResponseError: """ @overload def create( self, resource_group_name: str, account_name: str, certificate_name: str, parameters: IO, if_match: Optional[str] = None, if_none_match: Optional[str] = None, *, content_type: str = "application/json", **kwargs: Any ) -> _models.Certificate: """Creates a new certificate inside the specified account. Warning: This operation is deprecated and will be removed after February, 2024. Please use the `Azure KeyVault Extension <https://learn.microsoft.com/azure/batch/batch-certificate-migration-guide>`_ instead. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param certificate_name: The identifier for the certificate. This must be made up of algorithm and thumbprint separated by a dash, and must match the certificate data in the request. For example SHA1-a3d1c5. Required. :type certificate_name: str :param parameters: Additional parameters for certificate creation. Required. :type parameters: IO :param if_match: The entity state (ETag) version of the certificate to update. A value of "*" can be used to apply the operation only if the certificate already exists. If omitted, this operation will always be applied. Default value is None. :type if_match: str :param if_none_match: Set to '*' to allow a new certificate to be created, but to prevent updating an existing certificate. Other values will be ignored. Default value is None. :type if_none_match: str :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Certificate or the result of cls(response) :rtype: ~azure.mgmt.batch.models.Certificate :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace def create( self, resource_group_name: str, account_name: str, certificate_name: str, parameters: Union[_models.CertificateCreateOrUpdateParameters, IO], if_match: Optional[str] = None, if_none_match: Optional[str] = None, **kwargs: Any ) -> _models.Certificate: """Creates a new certificate inside the specified account. Warning: This operation is deprecated and will be removed after February, 2024. Please use the `Azure KeyVault Extension <https://learn.microsoft.com/azure/batch/batch-certificate-migration-guide>`_ instead. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param certificate_name: The identifier for the certificate. This must be made up of algorithm and thumbprint separated by a dash, and must match the certificate data in the request. For example SHA1-a3d1c5. Required. :type certificate_name: str :param parameters: Additional parameters for certificate creation. Is either a CertificateCreateOrUpdateParameters type or a IO type. Required. :type parameters: ~azure.mgmt.batch.models.CertificateCreateOrUpdateParameters or IO :param if_match: The entity state (ETag) version of the certificate to update. A value of "*" can be used to apply the operation only if the certificate already exists. If omitted, this operation will always be applied. Default value is None. :type if_match: str :param if_none_match: Set to '*' to allow a new certificate to be created, but to prevent updating an existing certificate. Other values will be ignored. Default value is None. :type if_none_match: str :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. Default value is None. :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Certificate or the result of cls(response) :rtype: ~azure.mgmt.batch.models.Certificate :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.Certificate] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None if isinstance(parameters, (IOBase, bytes)): _content = parameters else: _json = self._serialize.body(parameters, "CertificateCreateOrUpdateParameters") request = build_create_request( resource_group_name=resource_group_name, account_name=account_name, certificate_name=certificate_name, subscription_id=self._config.subscription_id, if_match=if_match, if_none_match=if_none_match, api_version=api_version, content_type=content_type, json=_json, content=_content, template_url=self.create.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) response_headers = {} response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) deserialized = self._deserialize("Certificate", pipeline_response) if cls: return cls(pipeline_response, deserialized, response_headers) return deserialized create.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/certificates/{certificateName}" } @overload def update( self, resource_group_name: str, account_name: str, certificate_name: str, parameters: _models.CertificateCreateOrUpdateParameters, if_match: Optional[str] = None, *, content_type: str = "application/json", **kwargs: Any ) -> _models.Certificate: """Updates the properties of an existing certificate. Warning: This operation is deprecated and will be removed after February, 2024. Please use the `Azure KeyVault Extension <https://learn.microsoft.com/azure/batch/batch-certificate-migration-guide>`_ instead. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param certificate_name: The identifier for the certificate. This must be made up of algorithm and thumbprint separated by a dash, and must match the certificate data in the request. For example SHA1-a3d1c5. Required. :type certificate_name: str :param parameters: Certificate entity to update. Required. :type parameters: ~azure.mgmt.batch.models.CertificateCreateOrUpdateParameters :param if_match: The entity state (ETag) version of the certificate to update. This value can be omitted or set to "*" to apply the operation unconditionally. Default value is None. :type if_match: str :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Certificate or the result of cls(response) :rtype: ~azure.mgmt.batch.models.Certificate :raises ~azure.core.exceptions.HttpResponseError: """ @overload def update( self, resource_group_name: str, account_name: str, certificate_name: str, parameters: IO, if_match: Optional[str] = None, *, content_type: str = "application/json", **kwargs: Any ) -> _models.Certificate: """Updates the properties of an existing certificate. Warning: This operation is deprecated and will be removed after February, 2024. Please use the `Azure KeyVault Extension <https://learn.microsoft.com/azure/batch/batch-certificate-migration-guide>`_ instead. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param certificate_name: The identifier for the certificate. This must be made up of algorithm and thumbprint separated by a dash, and must match the certificate data in the request. For example SHA1-a3d1c5. Required. :type certificate_name: str :param parameters: Certificate entity to update. Required. :type parameters: IO :param if_match: The entity state (ETag) version of the certificate to update. This value can be omitted or set to "*" to apply the operation unconditionally. Default value is None. :type if_match: str :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Certificate or the result of cls(response) :rtype: ~azure.mgmt.batch.models.Certificate :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace def update( self, resource_group_name: str, account_name: str, certificate_name: str, parameters: Union[_models.CertificateCreateOrUpdateParameters, IO], if_match: Optional[str] = None, **kwargs: Any ) -> _models.Certificate: """Updates the properties of an existing certificate. Warning: This operation is deprecated and will be removed after February, 2024. Please use the `Azure KeyVault Extension <https://learn.microsoft.com/azure/batch/batch-certificate-migration-guide>`_ instead. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param certificate_name: The identifier for the certificate. This must be made up of algorithm and thumbprint separated by a dash, and must match the certificate data in the request. For example SHA1-a3d1c5. Required. :type certificate_name: str :param parameters: Certificate entity to update. Is either a CertificateCreateOrUpdateParameters type or a IO type. Required. :type parameters: ~azure.mgmt.batch.models.CertificateCreateOrUpdateParameters or IO :param if_match: The entity state (ETag) version of the certificate to update. This value can be omitted or set to "*" to apply the operation unconditionally. Default value is None. :type if_match: str :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. Default value is None. :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Certificate or the result of cls(response) :rtype: ~azure.mgmt.batch.models.Certificate :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.Certificate] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None if isinstance(parameters, (IOBase, bytes)): _content = parameters else: _json = self._serialize.body(parameters, "CertificateCreateOrUpdateParameters") request = build_update_request( resource_group_name=resource_group_name, account_name=account_name, certificate_name=certificate_name, subscription_id=self._config.subscription_id, if_match=if_match, api_version=api_version, content_type=content_type, json=_json, content=_content, template_url=self.update.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) response_headers = {} response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) deserialized = self._deserialize("Certificate", pipeline_response) if cls: return cls(pipeline_response, deserialized, response_headers) return deserialized update.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/certificates/{certificateName}" } def _delete_initial( # pylint: disable=inconsistent-return-statements self, resource_group_name: str, account_name: str, certificate_name: str, **kwargs: Any ) -> None: error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[None] = kwargs.pop("cls", None) request = build_delete_request( resource_group_name=resource_group_name, account_name=account_name, certificate_name=certificate_name, subscription_id=self._config.subscription_id, api_version=api_version, template_url=self._delete_initial.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) response_headers = {} if response.status_code == 202: response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) if cls: return cls(pipeline_response, None, response_headers) _delete_initial.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/certificates/{certificateName}" } @distributed_trace def begin_delete( self, resource_group_name: str, account_name: str, certificate_name: str, **kwargs: Any ) -> LROPoller[None]: """Deletes the specified certificate. Warning: This operation is deprecated and will be removed after February, 2024. Please use the `Azure KeyVault Extension <https://learn.microsoft.com/azure/batch/batch-certificate-migration-guide>`_ instead. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param certificate_name: The identifier for the certificate. This must be made up of algorithm and thumbprint separated by a dash, and must match the certificate data in the request. For example SHA1-a3d1c5. Required. :type certificate_name: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.PollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of LROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[None] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[None] = kwargs.pop("cls", None) polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) cont_token: Optional[str] = kwargs.pop("continuation_token", None) if cont_token is None: raw_result = self._delete_initial( # type: ignore resource_group_name=resource_group_name, account_name=account_name, certificate_name=certificate_name, api_version=api_version, cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) if polling is True: polling_method: PollingMethod = cast( PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) ) elif polling is False: polling_method = cast(PollingMethod, NoPolling()) else: polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) return LROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore begin_delete.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/certificates/{certificateName}" } @distributed_trace def get( self, resource_group_name: str, account_name: str, certificate_name: str, **kwargs: Any ) -> _models.Certificate: """Gets information about the specified certificate. Warning: This operation is deprecated and will be removed after February, 2024. Please use the `Azure KeyVault Extension <https://learn.microsoft.com/azure/batch/batch-certificate-migration-guide>`_ instead. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param certificate_name: The identifier for the certificate. This must be made up of algorithm and thumbprint separated by a dash, and must match the certificate data in the request. For example SHA1-a3d1c5. Required. :type certificate_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Certificate or the result of cls(response) :rtype: ~azure.mgmt.batch.models.Certificate :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.Certificate] = kwargs.pop("cls", None) request = build_get_request( resource_group_name=resource_group_name, account_name=account_name, certificate_name=certificate_name, subscription_id=self._config.subscription_id, api_version=api_version, template_url=self.get.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) response_headers = {} response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) deserialized = self._deserialize("Certificate", pipeline_response) if cls: return cls(pipeline_response, deserialized, response_headers) return deserialized get.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/certificates/{certificateName}" } @distributed_trace def cancel_deletion( self, resource_group_name: str, account_name: str, certificate_name: str, **kwargs: Any ) -> _models.Certificate: """Cancels a failed deletion of a certificate from the specified account. If you try to delete a certificate that is being used by a pool or compute node, the status of the certificate changes to deleteFailed. If you decide that you want to continue using the certificate, you can use this operation to set the status of the certificate back to active. If you intend to delete the certificate, you do not need to run this operation after the deletion failed. You must make sure that the certificate is not being used by any resources, and then you can try again to delete the certificate. Warning: This operation is deprecated and will be removed after February, 2024. Please use the `Azure KeyVault Extension <https://learn.microsoft.com/azure/batch/batch-certificate-migration-guide>`_ instead. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param certificate_name: The identifier for the certificate. This must be made up of algorithm and thumbprint separated by a dash, and must match the certificate data in the request. For example SHA1-a3d1c5. Required. :type certificate_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Certificate or the result of cls(response) :rtype: ~azure.mgmt.batch.models.Certificate :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.Certificate] = kwargs.pop("cls", None) request = build_cancel_deletion_request( resource_group_name=resource_group_name, account_name=account_name, certificate_name=certificate_name, subscription_id=self._config.subscription_id, api_version=api_version, template_url=self.cancel_deletion.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) response_headers = {} response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) deserialized = self._deserialize("Certificate", pipeline_response) if cls: return cls(pipeline_response, deserialized, response_headers) return deserialized cancel_deletion.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/certificates/{certificateName}/cancelDelete" }
0.787237
0.080394
from copy import deepcopy from typing import Any, Awaitable, TYPE_CHECKING from azure.core.rest import AsyncHttpResponse, HttpRequest from azure.mgmt.core import AsyncARMPipelineClient from .. import models as _models from .._serialization import Deserializer, Serializer from ._configuration import BatchManagementClientConfiguration from .operations import ( ApplicationOperations, ApplicationPackageOperations, BatchAccountOperations, CertificateOperations, LocationOperations, Operations, PoolOperations, PrivateEndpointConnectionOperations, PrivateLinkResourceOperations, ) if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential class BatchManagementClient: # pylint: disable=client-accepts-api-version-keyword,too-many-instance-attributes """Batch Client. :ivar batch_account: BatchAccountOperations operations :vartype batch_account: azure.mgmt.batch.aio.operations.BatchAccountOperations :ivar application_package: ApplicationPackageOperations operations :vartype application_package: azure.mgmt.batch.aio.operations.ApplicationPackageOperations :ivar application: ApplicationOperations operations :vartype application: azure.mgmt.batch.aio.operations.ApplicationOperations :ivar location: LocationOperations operations :vartype location: azure.mgmt.batch.aio.operations.LocationOperations :ivar operations: Operations operations :vartype operations: azure.mgmt.batch.aio.operations.Operations :ivar certificate: CertificateOperations operations :vartype certificate: azure.mgmt.batch.aio.operations.CertificateOperations :ivar private_link_resource: PrivateLinkResourceOperations operations :vartype private_link_resource: azure.mgmt.batch.aio.operations.PrivateLinkResourceOperations :ivar private_endpoint_connection: PrivateEndpointConnectionOperations operations :vartype private_endpoint_connection: azure.mgmt.batch.aio.operations.PrivateEndpointConnectionOperations :ivar pool: PoolOperations operations :vartype pool: azure.mgmt.batch.aio.operations.PoolOperations :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials_async.AsyncTokenCredential :param subscription_id: The Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000). Required. :type subscription_id: str :param base_url: Service URL. Default value is "https://management.azure.com". :type base_url: str :keyword api_version: Api Version. Default value is "2023-05-01". Note that overriding this default value may result in unsupported behavior. :paramtype api_version: str :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. """ def __init__( self, credential: "AsyncTokenCredential", subscription_id: str, base_url: str = "https://management.azure.com", **kwargs: Any ) -> None: self._config = BatchManagementClientConfiguration( credential=credential, subscription_id=subscription_id, **kwargs ) self._client: AsyncARMPipelineClient = AsyncARMPipelineClient(base_url=base_url, config=self._config, **kwargs) client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)} self._serialize = Serializer(client_models) self._deserialize = Deserializer(client_models) self._serialize.client_side_validation = False self.batch_account = BatchAccountOperations(self._client, self._config, self._serialize, self._deserialize) self.application_package = ApplicationPackageOperations( self._client, self._config, self._serialize, self._deserialize ) self.application = ApplicationOperations(self._client, self._config, self._serialize, self._deserialize) self.location = LocationOperations(self._client, self._config, self._serialize, self._deserialize) self.operations = Operations(self._client, self._config, self._serialize, self._deserialize) self.certificate = CertificateOperations(self._client, self._config, self._serialize, self._deserialize) self.private_link_resource = PrivateLinkResourceOperations( self._client, self._config, self._serialize, self._deserialize ) self.private_endpoint_connection = PrivateEndpointConnectionOperations( self._client, self._config, self._serialize, self._deserialize ) self.pool = PoolOperations(self._client, self._config, self._serialize, self._deserialize) def _send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]: """Runs the network request through the client's chained policies. >>> from azure.core.rest import HttpRequest >>> request = HttpRequest("GET", "https://www.example.org/") <HttpRequest [GET], url: 'https://www.example.org/'> >>> response = await client._send_request(request) <AsyncHttpResponse: 200 OK> For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request :param request: The network request you want to make. Required. :type request: ~azure.core.rest.HttpRequest :keyword bool stream: Whether the response payload will be streamed. Defaults to False. :return: The response of your network call. Does not do error handling on your response. :rtype: ~azure.core.rest.AsyncHttpResponse """ request_copy = deepcopy(request) request_copy.url = self._client.format_url(request_copy.url) return self._client.send_request(request_copy, **kwargs) async def close(self) -> None: await self._client.close() async def __aenter__(self) -> "BatchManagementClient": await self._client.__aenter__() return self async def __aexit__(self, *exc_details: Any) -> None: await self._client.__aexit__(*exc_details)
azure-mgmt-batch
/azure_mgmt_batch-17.1.0-py3-none-any.whl/azure/mgmt/batch/aio/_batch_management_client.py
_batch_management_client.py
from copy import deepcopy from typing import Any, Awaitable, TYPE_CHECKING from azure.core.rest import AsyncHttpResponse, HttpRequest from azure.mgmt.core import AsyncARMPipelineClient from .. import models as _models from .._serialization import Deserializer, Serializer from ._configuration import BatchManagementClientConfiguration from .operations import ( ApplicationOperations, ApplicationPackageOperations, BatchAccountOperations, CertificateOperations, LocationOperations, Operations, PoolOperations, PrivateEndpointConnectionOperations, PrivateLinkResourceOperations, ) if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential class BatchManagementClient: # pylint: disable=client-accepts-api-version-keyword,too-many-instance-attributes """Batch Client. :ivar batch_account: BatchAccountOperations operations :vartype batch_account: azure.mgmt.batch.aio.operations.BatchAccountOperations :ivar application_package: ApplicationPackageOperations operations :vartype application_package: azure.mgmt.batch.aio.operations.ApplicationPackageOperations :ivar application: ApplicationOperations operations :vartype application: azure.mgmt.batch.aio.operations.ApplicationOperations :ivar location: LocationOperations operations :vartype location: azure.mgmt.batch.aio.operations.LocationOperations :ivar operations: Operations operations :vartype operations: azure.mgmt.batch.aio.operations.Operations :ivar certificate: CertificateOperations operations :vartype certificate: azure.mgmt.batch.aio.operations.CertificateOperations :ivar private_link_resource: PrivateLinkResourceOperations operations :vartype private_link_resource: azure.mgmt.batch.aio.operations.PrivateLinkResourceOperations :ivar private_endpoint_connection: PrivateEndpointConnectionOperations operations :vartype private_endpoint_connection: azure.mgmt.batch.aio.operations.PrivateEndpointConnectionOperations :ivar pool: PoolOperations operations :vartype pool: azure.mgmt.batch.aio.operations.PoolOperations :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials_async.AsyncTokenCredential :param subscription_id: The Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000). Required. :type subscription_id: str :param base_url: Service URL. Default value is "https://management.azure.com". :type base_url: str :keyword api_version: Api Version. Default value is "2023-05-01". Note that overriding this default value may result in unsupported behavior. :paramtype api_version: str :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. """ def __init__( self, credential: "AsyncTokenCredential", subscription_id: str, base_url: str = "https://management.azure.com", **kwargs: Any ) -> None: self._config = BatchManagementClientConfiguration( credential=credential, subscription_id=subscription_id, **kwargs ) self._client: AsyncARMPipelineClient = AsyncARMPipelineClient(base_url=base_url, config=self._config, **kwargs) client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)} self._serialize = Serializer(client_models) self._deserialize = Deserializer(client_models) self._serialize.client_side_validation = False self.batch_account = BatchAccountOperations(self._client, self._config, self._serialize, self._deserialize) self.application_package = ApplicationPackageOperations( self._client, self._config, self._serialize, self._deserialize ) self.application = ApplicationOperations(self._client, self._config, self._serialize, self._deserialize) self.location = LocationOperations(self._client, self._config, self._serialize, self._deserialize) self.operations = Operations(self._client, self._config, self._serialize, self._deserialize) self.certificate = CertificateOperations(self._client, self._config, self._serialize, self._deserialize) self.private_link_resource = PrivateLinkResourceOperations( self._client, self._config, self._serialize, self._deserialize ) self.private_endpoint_connection = PrivateEndpointConnectionOperations( self._client, self._config, self._serialize, self._deserialize ) self.pool = PoolOperations(self._client, self._config, self._serialize, self._deserialize) def _send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]: """Runs the network request through the client's chained policies. >>> from azure.core.rest import HttpRequest >>> request = HttpRequest("GET", "https://www.example.org/") <HttpRequest [GET], url: 'https://www.example.org/'> >>> response = await client._send_request(request) <AsyncHttpResponse: 200 OK> For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request :param request: The network request you want to make. Required. :type request: ~azure.core.rest.HttpRequest :keyword bool stream: Whether the response payload will be streamed. Defaults to False. :return: The response of your network call. Does not do error handling on your response. :rtype: ~azure.core.rest.AsyncHttpResponse """ request_copy = deepcopy(request) request_copy.url = self._client.format_url(request_copy.url) return self._client.send_request(request_copy, **kwargs) async def close(self) -> None: await self._client.close() async def __aenter__(self) -> "BatchManagementClient": await self._client.__aenter__() return self async def __aexit__(self, *exc_details: Any) -> None: await self._client.__aexit__(*exc_details)
0.833426
0.096748
from typing import Any, TYPE_CHECKING from azure.core.configuration import Configuration from azure.core.pipeline import policies from azure.mgmt.core.policies import ARMHttpLoggingPolicy, AsyncARMChallengeAuthenticationPolicy from .._version import VERSION if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential class BatchManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes """Configuration for BatchManagementClient. Note that all parameters used to create this instance are saved as instance attributes. :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials_async.AsyncTokenCredential :param subscription_id: The Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000). Required. :type subscription_id: str :keyword api_version: Api Version. Default value is "2023-05-01". Note that overriding this default value may result in unsupported behavior. :paramtype api_version: str """ def __init__(self, credential: "AsyncTokenCredential", subscription_id: str, **kwargs: Any) -> None: super(BatchManagementClientConfiguration, self).__init__(**kwargs) api_version: str = kwargs.pop("api_version", "2023-05-01") if credential is None: raise ValueError("Parameter 'credential' must not be None.") if subscription_id is None: raise ValueError("Parameter 'subscription_id' must not be None.") self.credential = credential self.subscription_id = subscription_id self.api_version = api_version self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) kwargs.setdefault("sdk_moniker", "mgmt-batch/{}".format(VERSION)) self._configure(**kwargs) def _configure(self, **kwargs: Any) -> None: self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) self.retry_policy = kwargs.get("retry_policy") or policies.AsyncRetryPolicy(**kwargs) self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) self.redirect_policy = kwargs.get("redirect_policy") or policies.AsyncRedirectPolicy(**kwargs) self.authentication_policy = kwargs.get("authentication_policy") if self.credential and not self.authentication_policy: self.authentication_policy = AsyncARMChallengeAuthenticationPolicy( self.credential, *self.credential_scopes, **kwargs )
azure-mgmt-batch
/azure_mgmt_batch-17.1.0-py3-none-any.whl/azure/mgmt/batch/aio/_configuration.py
_configuration.py
from typing import Any, TYPE_CHECKING from azure.core.configuration import Configuration from azure.core.pipeline import policies from azure.mgmt.core.policies import ARMHttpLoggingPolicy, AsyncARMChallengeAuthenticationPolicy from .._version import VERSION if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential class BatchManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes """Configuration for BatchManagementClient. Note that all parameters used to create this instance are saved as instance attributes. :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials_async.AsyncTokenCredential :param subscription_id: The Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000). Required. :type subscription_id: str :keyword api_version: Api Version. Default value is "2023-05-01". Note that overriding this default value may result in unsupported behavior. :paramtype api_version: str """ def __init__(self, credential: "AsyncTokenCredential", subscription_id: str, **kwargs: Any) -> None: super(BatchManagementClientConfiguration, self).__init__(**kwargs) api_version: str = kwargs.pop("api_version", "2023-05-01") if credential is None: raise ValueError("Parameter 'credential' must not be None.") if subscription_id is None: raise ValueError("Parameter 'subscription_id' must not be None.") self.credential = credential self.subscription_id = subscription_id self.api_version = api_version self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) kwargs.setdefault("sdk_moniker", "mgmt-batch/{}".format(VERSION)) self._configure(**kwargs) def _configure(self, **kwargs: Any) -> None: self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) self.retry_policy = kwargs.get("retry_policy") or policies.AsyncRetryPolicy(**kwargs) self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) self.redirect_policy = kwargs.get("redirect_policy") or policies.AsyncRedirectPolicy(**kwargs) self.authentication_policy = kwargs.get("authentication_policy") if self.credential and not self.authentication_policy: self.authentication_policy = AsyncARMChallengeAuthenticationPolicy( self.credential, *self.credential_scopes, **kwargs )
0.844056
0.096535
from io import IOBase from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload import urllib.parse from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, map_error, ) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling from ... import models as _models from ..._vendor import _convert_request from ...operations._pool_operations import ( build_create_request, build_delete_request, build_disable_auto_scale_request, build_get_request, build_list_by_batch_account_request, build_stop_resize_request, build_update_request, ) T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] class PoolOperations: """ .. warning:: **DO NOT** instantiate this class directly. Instead, you should access the following operations through :class:`~azure.mgmt.batch.aio.BatchManagementClient`'s :attr:`pool` attribute. """ models = _models def __init__(self, *args, **kwargs) -> None: input_args = list(args) self._client = input_args.pop(0) if input_args else kwargs.pop("client") self._config = input_args.pop(0) if input_args else kwargs.pop("config") self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace def list_by_batch_account( self, resource_group_name: str, account_name: str, maxresults: Optional[int] = None, select: Optional[str] = None, filter: Optional[str] = None, **kwargs: Any ) -> AsyncIterable["_models.Pool"]: """Lists all of the pools in the specified account. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param maxresults: The maximum number of items to return in the response. Default value is None. :type maxresults: int :param select: Comma separated list of properties that should be returned. e.g. "properties/provisioningState". Only top level properties under properties/ are valid for selection. Default value is None. :type select: str :param filter: OData filter expression. Valid properties for filtering are: name properties/allocationState properties/allocationStateTransitionTime properties/creationTime properties/provisioningState properties/provisioningStateTransitionTime properties/lastModified properties/vmSize properties/interNodeCommunication properties/scaleSettings/autoScale properties/scaleSettings/fixedScale. Default value is None. :type filter: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either Pool or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.batch.models.Pool] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.ListPoolsResult] = kwargs.pop("cls", None) error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_by_batch_account_request( resource_group_name=resource_group_name, account_name=account_name, subscription_id=self._config.subscription_id, maxresults=maxresults, select=select, filter=filter, api_version=api_version, template_url=self.list_by_batch_account.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) else: # make call to next link with the client's api-version _parsed_next_link = urllib.parse.urlparse(next_link) _next_request_params = case_insensitive_dict( { key: [urllib.parse.quote(v) for v in value] for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) _next_request_params["api-version"] = self._config.api_version request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) request.url = self._client.format_url(request.url) request.method = "GET" return request async def extract_data(pipeline_response): deserialized = self._deserialize("ListPoolsResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) # type: ignore return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged(get_next, extract_data) list_by_batch_account.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/pools" } @overload async def create( self, resource_group_name: str, account_name: str, pool_name: str, parameters: _models.Pool, if_match: Optional[str] = None, if_none_match: Optional[str] = None, *, content_type: str = "application/json", **kwargs: Any ) -> _models.Pool: """Creates a new pool inside the specified account. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param pool_name: The pool name. This must be unique within the account. Required. :type pool_name: str :param parameters: Additional parameters for pool creation. Required. :type parameters: ~azure.mgmt.batch.models.Pool :param if_match: The entity state (ETag) version of the pool to update. A value of "*" can be used to apply the operation only if the pool already exists. If omitted, this operation will always be applied. Default value is None. :type if_match: str :param if_none_match: Set to '*' to allow a new pool to be created, but to prevent updating an existing pool. Other values will be ignored. Default value is None. :type if_none_match: str :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Pool or the result of cls(response) :rtype: ~azure.mgmt.batch.models.Pool :raises ~azure.core.exceptions.HttpResponseError: """ @overload async def create( self, resource_group_name: str, account_name: str, pool_name: str, parameters: IO, if_match: Optional[str] = None, if_none_match: Optional[str] = None, *, content_type: str = "application/json", **kwargs: Any ) -> _models.Pool: """Creates a new pool inside the specified account. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param pool_name: The pool name. This must be unique within the account. Required. :type pool_name: str :param parameters: Additional parameters for pool creation. Required. :type parameters: IO :param if_match: The entity state (ETag) version of the pool to update. A value of "*" can be used to apply the operation only if the pool already exists. If omitted, this operation will always be applied. Default value is None. :type if_match: str :param if_none_match: Set to '*' to allow a new pool to be created, but to prevent updating an existing pool. Other values will be ignored. Default value is None. :type if_none_match: str :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Pool or the result of cls(response) :rtype: ~azure.mgmt.batch.models.Pool :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace_async async def create( self, resource_group_name: str, account_name: str, pool_name: str, parameters: Union[_models.Pool, IO], if_match: Optional[str] = None, if_none_match: Optional[str] = None, **kwargs: Any ) -> _models.Pool: """Creates a new pool inside the specified account. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param pool_name: The pool name. This must be unique within the account. Required. :type pool_name: str :param parameters: Additional parameters for pool creation. Is either a Pool type or a IO type. Required. :type parameters: ~azure.mgmt.batch.models.Pool or IO :param if_match: The entity state (ETag) version of the pool to update. A value of "*" can be used to apply the operation only if the pool already exists. If omitted, this operation will always be applied. Default value is None. :type if_match: str :param if_none_match: Set to '*' to allow a new pool to be created, but to prevent updating an existing pool. Other values will be ignored. Default value is None. :type if_none_match: str :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. Default value is None. :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Pool or the result of cls(response) :rtype: ~azure.mgmt.batch.models.Pool :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.Pool] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None if isinstance(parameters, (IOBase, bytes)): _content = parameters else: _json = self._serialize.body(parameters, "Pool") request = build_create_request( resource_group_name=resource_group_name, account_name=account_name, pool_name=pool_name, subscription_id=self._config.subscription_id, if_match=if_match, if_none_match=if_none_match, api_version=api_version, content_type=content_type, json=_json, content=_content, template_url=self.create.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) response_headers = {} response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) deserialized = self._deserialize("Pool", pipeline_response) if cls: return cls(pipeline_response, deserialized, response_headers) return deserialized create.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/pools/{poolName}" } @overload async def update( self, resource_group_name: str, account_name: str, pool_name: str, parameters: _models.Pool, if_match: Optional[str] = None, *, content_type: str = "application/json", **kwargs: Any ) -> _models.Pool: """Updates the properties of an existing pool. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param pool_name: The pool name. This must be unique within the account. Required. :type pool_name: str :param parameters: Pool properties that should be updated. Properties that are supplied will be updated, any property not supplied will be unchanged. Required. :type parameters: ~azure.mgmt.batch.models.Pool :param if_match: The entity state (ETag) version of the pool to update. This value can be omitted or set to "*" to apply the operation unconditionally. Default value is None. :type if_match: str :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Pool or the result of cls(response) :rtype: ~azure.mgmt.batch.models.Pool :raises ~azure.core.exceptions.HttpResponseError: """ @overload async def update( self, resource_group_name: str, account_name: str, pool_name: str, parameters: IO, if_match: Optional[str] = None, *, content_type: str = "application/json", **kwargs: Any ) -> _models.Pool: """Updates the properties of an existing pool. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param pool_name: The pool name. This must be unique within the account. Required. :type pool_name: str :param parameters: Pool properties that should be updated. Properties that are supplied will be updated, any property not supplied will be unchanged. Required. :type parameters: IO :param if_match: The entity state (ETag) version of the pool to update. This value can be omitted or set to "*" to apply the operation unconditionally. Default value is None. :type if_match: str :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Pool or the result of cls(response) :rtype: ~azure.mgmt.batch.models.Pool :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace_async async def update( self, resource_group_name: str, account_name: str, pool_name: str, parameters: Union[_models.Pool, IO], if_match: Optional[str] = None, **kwargs: Any ) -> _models.Pool: """Updates the properties of an existing pool. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param pool_name: The pool name. This must be unique within the account. Required. :type pool_name: str :param parameters: Pool properties that should be updated. Properties that are supplied will be updated, any property not supplied will be unchanged. Is either a Pool type or a IO type. Required. :type parameters: ~azure.mgmt.batch.models.Pool or IO :param if_match: The entity state (ETag) version of the pool to update. This value can be omitted or set to "*" to apply the operation unconditionally. Default value is None. :type if_match: str :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. Default value is None. :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Pool or the result of cls(response) :rtype: ~azure.mgmt.batch.models.Pool :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.Pool] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None if isinstance(parameters, (IOBase, bytes)): _content = parameters else: _json = self._serialize.body(parameters, "Pool") request = build_update_request( resource_group_name=resource_group_name, account_name=account_name, pool_name=pool_name, subscription_id=self._config.subscription_id, if_match=if_match, api_version=api_version, content_type=content_type, json=_json, content=_content, template_url=self.update.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) response_headers = {} response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) deserialized = self._deserialize("Pool", pipeline_response) if cls: return cls(pipeline_response, deserialized, response_headers) return deserialized update.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/pools/{poolName}" } async def _delete_initial( # pylint: disable=inconsistent-return-statements self, resource_group_name: str, account_name: str, pool_name: str, **kwargs: Any ) -> None: error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[None] = kwargs.pop("cls", None) request = build_delete_request( resource_group_name=resource_group_name, account_name=account_name, pool_name=pool_name, subscription_id=self._config.subscription_id, api_version=api_version, template_url=self._delete_initial.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) response_headers = {} if response.status_code == 202: response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) if cls: return cls(pipeline_response, None, response_headers) _delete_initial.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/pools/{poolName}" } @distributed_trace_async async def begin_delete( self, resource_group_name: str, account_name: str, pool_name: str, **kwargs: Any ) -> AsyncLROPoller[None]: """Deletes the specified pool. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param pool_name: The pool name. This must be unique within the account. Required. :type pool_name: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[None] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[None] = kwargs.pop("cls", None) polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) cont_token: Optional[str] = kwargs.pop("continuation_token", None) if cont_token is None: raw_result = await self._delete_initial( # type: ignore resource_group_name=resource_group_name, account_name=account_name, pool_name=pool_name, api_version=api_version, cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) if polling is True: polling_method: AsyncPollingMethod = cast( AsyncPollingMethod, AsyncARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) ) elif polling is False: polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) else: polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore begin_delete.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/pools/{poolName}" } @distributed_trace_async async def get(self, resource_group_name: str, account_name: str, pool_name: str, **kwargs: Any) -> _models.Pool: """Gets information about the specified pool. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param pool_name: The pool name. This must be unique within the account. Required. :type pool_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Pool or the result of cls(response) :rtype: ~azure.mgmt.batch.models.Pool :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.Pool] = kwargs.pop("cls", None) request = build_get_request( resource_group_name=resource_group_name, account_name=account_name, pool_name=pool_name, subscription_id=self._config.subscription_id, api_version=api_version, template_url=self.get.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) response_headers = {} response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) deserialized = self._deserialize("Pool", pipeline_response) if cls: return cls(pipeline_response, deserialized, response_headers) return deserialized get.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/pools/{poolName}" } @distributed_trace_async async def disable_auto_scale( self, resource_group_name: str, account_name: str, pool_name: str, **kwargs: Any ) -> _models.Pool: """Disables automatic scaling for a pool. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param pool_name: The pool name. This must be unique within the account. Required. :type pool_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Pool or the result of cls(response) :rtype: ~azure.mgmt.batch.models.Pool :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.Pool] = kwargs.pop("cls", None) request = build_disable_auto_scale_request( resource_group_name=resource_group_name, account_name=account_name, pool_name=pool_name, subscription_id=self._config.subscription_id, api_version=api_version, template_url=self.disable_auto_scale.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) response_headers = {} response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) deserialized = self._deserialize("Pool", pipeline_response) if cls: return cls(pipeline_response, deserialized, response_headers) return deserialized disable_auto_scale.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/pools/{poolName}/disableAutoScale" } @distributed_trace_async async def stop_resize( self, resource_group_name: str, account_name: str, pool_name: str, **kwargs: Any ) -> _models.Pool: """Stops an ongoing resize operation on the pool. This does not restore the pool to its previous state before the resize operation: it only stops any further changes being made, and the pool maintains its current state. After stopping, the pool stabilizes at the number of nodes it was at when the stop operation was done. During the stop operation, the pool allocation state changes first to stopping and then to steady. A resize operation need not be an explicit resize pool request; this API can also be used to halt the initial sizing of the pool when it is created. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param pool_name: The pool name. This must be unique within the account. Required. :type pool_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Pool or the result of cls(response) :rtype: ~azure.mgmt.batch.models.Pool :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.Pool] = kwargs.pop("cls", None) request = build_stop_resize_request( resource_group_name=resource_group_name, account_name=account_name, pool_name=pool_name, subscription_id=self._config.subscription_id, api_version=api_version, template_url=self.stop_resize.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) response_headers = {} response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) deserialized = self._deserialize("Pool", pipeline_response) if cls: return cls(pipeline_response, deserialized, response_headers) return deserialized stop_resize.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/pools/{poolName}/stopResize" }
azure-mgmt-batch
/azure_mgmt_batch-17.1.0-py3-none-any.whl/azure/mgmt/batch/aio/operations/_pool_operations.py
_pool_operations.py
from io import IOBase from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload import urllib.parse from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, map_error, ) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling from ... import models as _models from ..._vendor import _convert_request from ...operations._pool_operations import ( build_create_request, build_delete_request, build_disable_auto_scale_request, build_get_request, build_list_by_batch_account_request, build_stop_resize_request, build_update_request, ) T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] class PoolOperations: """ .. warning:: **DO NOT** instantiate this class directly. Instead, you should access the following operations through :class:`~azure.mgmt.batch.aio.BatchManagementClient`'s :attr:`pool` attribute. """ models = _models def __init__(self, *args, **kwargs) -> None: input_args = list(args) self._client = input_args.pop(0) if input_args else kwargs.pop("client") self._config = input_args.pop(0) if input_args else kwargs.pop("config") self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace def list_by_batch_account( self, resource_group_name: str, account_name: str, maxresults: Optional[int] = None, select: Optional[str] = None, filter: Optional[str] = None, **kwargs: Any ) -> AsyncIterable["_models.Pool"]: """Lists all of the pools in the specified account. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param maxresults: The maximum number of items to return in the response. Default value is None. :type maxresults: int :param select: Comma separated list of properties that should be returned. e.g. "properties/provisioningState". Only top level properties under properties/ are valid for selection. Default value is None. :type select: str :param filter: OData filter expression. Valid properties for filtering are: name properties/allocationState properties/allocationStateTransitionTime properties/creationTime properties/provisioningState properties/provisioningStateTransitionTime properties/lastModified properties/vmSize properties/interNodeCommunication properties/scaleSettings/autoScale properties/scaleSettings/fixedScale. Default value is None. :type filter: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either Pool or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.batch.models.Pool] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.ListPoolsResult] = kwargs.pop("cls", None) error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_by_batch_account_request( resource_group_name=resource_group_name, account_name=account_name, subscription_id=self._config.subscription_id, maxresults=maxresults, select=select, filter=filter, api_version=api_version, template_url=self.list_by_batch_account.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) else: # make call to next link with the client's api-version _parsed_next_link = urllib.parse.urlparse(next_link) _next_request_params = case_insensitive_dict( { key: [urllib.parse.quote(v) for v in value] for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) _next_request_params["api-version"] = self._config.api_version request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) request.url = self._client.format_url(request.url) request.method = "GET" return request async def extract_data(pipeline_response): deserialized = self._deserialize("ListPoolsResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) # type: ignore return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged(get_next, extract_data) list_by_batch_account.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/pools" } @overload async def create( self, resource_group_name: str, account_name: str, pool_name: str, parameters: _models.Pool, if_match: Optional[str] = None, if_none_match: Optional[str] = None, *, content_type: str = "application/json", **kwargs: Any ) -> _models.Pool: """Creates a new pool inside the specified account. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param pool_name: The pool name. This must be unique within the account. Required. :type pool_name: str :param parameters: Additional parameters for pool creation. Required. :type parameters: ~azure.mgmt.batch.models.Pool :param if_match: The entity state (ETag) version of the pool to update. A value of "*" can be used to apply the operation only if the pool already exists. If omitted, this operation will always be applied. Default value is None. :type if_match: str :param if_none_match: Set to '*' to allow a new pool to be created, but to prevent updating an existing pool. Other values will be ignored. Default value is None. :type if_none_match: str :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Pool or the result of cls(response) :rtype: ~azure.mgmt.batch.models.Pool :raises ~azure.core.exceptions.HttpResponseError: """ @overload async def create( self, resource_group_name: str, account_name: str, pool_name: str, parameters: IO, if_match: Optional[str] = None, if_none_match: Optional[str] = None, *, content_type: str = "application/json", **kwargs: Any ) -> _models.Pool: """Creates a new pool inside the specified account. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param pool_name: The pool name. This must be unique within the account. Required. :type pool_name: str :param parameters: Additional parameters for pool creation. Required. :type parameters: IO :param if_match: The entity state (ETag) version of the pool to update. A value of "*" can be used to apply the operation only if the pool already exists. If omitted, this operation will always be applied. Default value is None. :type if_match: str :param if_none_match: Set to '*' to allow a new pool to be created, but to prevent updating an existing pool. Other values will be ignored. Default value is None. :type if_none_match: str :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Pool or the result of cls(response) :rtype: ~azure.mgmt.batch.models.Pool :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace_async async def create( self, resource_group_name: str, account_name: str, pool_name: str, parameters: Union[_models.Pool, IO], if_match: Optional[str] = None, if_none_match: Optional[str] = None, **kwargs: Any ) -> _models.Pool: """Creates a new pool inside the specified account. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param pool_name: The pool name. This must be unique within the account. Required. :type pool_name: str :param parameters: Additional parameters for pool creation. Is either a Pool type or a IO type. Required. :type parameters: ~azure.mgmt.batch.models.Pool or IO :param if_match: The entity state (ETag) version of the pool to update. A value of "*" can be used to apply the operation only if the pool already exists. If omitted, this operation will always be applied. Default value is None. :type if_match: str :param if_none_match: Set to '*' to allow a new pool to be created, but to prevent updating an existing pool. Other values will be ignored. Default value is None. :type if_none_match: str :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. Default value is None. :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Pool or the result of cls(response) :rtype: ~azure.mgmt.batch.models.Pool :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.Pool] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None if isinstance(parameters, (IOBase, bytes)): _content = parameters else: _json = self._serialize.body(parameters, "Pool") request = build_create_request( resource_group_name=resource_group_name, account_name=account_name, pool_name=pool_name, subscription_id=self._config.subscription_id, if_match=if_match, if_none_match=if_none_match, api_version=api_version, content_type=content_type, json=_json, content=_content, template_url=self.create.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) response_headers = {} response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) deserialized = self._deserialize("Pool", pipeline_response) if cls: return cls(pipeline_response, deserialized, response_headers) return deserialized create.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/pools/{poolName}" } @overload async def update( self, resource_group_name: str, account_name: str, pool_name: str, parameters: _models.Pool, if_match: Optional[str] = None, *, content_type: str = "application/json", **kwargs: Any ) -> _models.Pool: """Updates the properties of an existing pool. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param pool_name: The pool name. This must be unique within the account. Required. :type pool_name: str :param parameters: Pool properties that should be updated. Properties that are supplied will be updated, any property not supplied will be unchanged. Required. :type parameters: ~azure.mgmt.batch.models.Pool :param if_match: The entity state (ETag) version of the pool to update. This value can be omitted or set to "*" to apply the operation unconditionally. Default value is None. :type if_match: str :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Pool or the result of cls(response) :rtype: ~azure.mgmt.batch.models.Pool :raises ~azure.core.exceptions.HttpResponseError: """ @overload async def update( self, resource_group_name: str, account_name: str, pool_name: str, parameters: IO, if_match: Optional[str] = None, *, content_type: str = "application/json", **kwargs: Any ) -> _models.Pool: """Updates the properties of an existing pool. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param pool_name: The pool name. This must be unique within the account. Required. :type pool_name: str :param parameters: Pool properties that should be updated. Properties that are supplied will be updated, any property not supplied will be unchanged. Required. :type parameters: IO :param if_match: The entity state (ETag) version of the pool to update. This value can be omitted or set to "*" to apply the operation unconditionally. Default value is None. :type if_match: str :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Pool or the result of cls(response) :rtype: ~azure.mgmt.batch.models.Pool :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace_async async def update( self, resource_group_name: str, account_name: str, pool_name: str, parameters: Union[_models.Pool, IO], if_match: Optional[str] = None, **kwargs: Any ) -> _models.Pool: """Updates the properties of an existing pool. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param pool_name: The pool name. This must be unique within the account. Required. :type pool_name: str :param parameters: Pool properties that should be updated. Properties that are supplied will be updated, any property not supplied will be unchanged. Is either a Pool type or a IO type. Required. :type parameters: ~azure.mgmt.batch.models.Pool or IO :param if_match: The entity state (ETag) version of the pool to update. This value can be omitted or set to "*" to apply the operation unconditionally. Default value is None. :type if_match: str :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. Default value is None. :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Pool or the result of cls(response) :rtype: ~azure.mgmt.batch.models.Pool :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.Pool] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None if isinstance(parameters, (IOBase, bytes)): _content = parameters else: _json = self._serialize.body(parameters, "Pool") request = build_update_request( resource_group_name=resource_group_name, account_name=account_name, pool_name=pool_name, subscription_id=self._config.subscription_id, if_match=if_match, api_version=api_version, content_type=content_type, json=_json, content=_content, template_url=self.update.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) response_headers = {} response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) deserialized = self._deserialize("Pool", pipeline_response) if cls: return cls(pipeline_response, deserialized, response_headers) return deserialized update.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/pools/{poolName}" } async def _delete_initial( # pylint: disable=inconsistent-return-statements self, resource_group_name: str, account_name: str, pool_name: str, **kwargs: Any ) -> None: error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[None] = kwargs.pop("cls", None) request = build_delete_request( resource_group_name=resource_group_name, account_name=account_name, pool_name=pool_name, subscription_id=self._config.subscription_id, api_version=api_version, template_url=self._delete_initial.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) response_headers = {} if response.status_code == 202: response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) if cls: return cls(pipeline_response, None, response_headers) _delete_initial.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/pools/{poolName}" } @distributed_trace_async async def begin_delete( self, resource_group_name: str, account_name: str, pool_name: str, **kwargs: Any ) -> AsyncLROPoller[None]: """Deletes the specified pool. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param pool_name: The pool name. This must be unique within the account. Required. :type pool_name: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[None] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[None] = kwargs.pop("cls", None) polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) cont_token: Optional[str] = kwargs.pop("continuation_token", None) if cont_token is None: raw_result = await self._delete_initial( # type: ignore resource_group_name=resource_group_name, account_name=account_name, pool_name=pool_name, api_version=api_version, cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) if polling is True: polling_method: AsyncPollingMethod = cast( AsyncPollingMethod, AsyncARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) ) elif polling is False: polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) else: polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore begin_delete.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/pools/{poolName}" } @distributed_trace_async async def get(self, resource_group_name: str, account_name: str, pool_name: str, **kwargs: Any) -> _models.Pool: """Gets information about the specified pool. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param pool_name: The pool name. This must be unique within the account. Required. :type pool_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Pool or the result of cls(response) :rtype: ~azure.mgmt.batch.models.Pool :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.Pool] = kwargs.pop("cls", None) request = build_get_request( resource_group_name=resource_group_name, account_name=account_name, pool_name=pool_name, subscription_id=self._config.subscription_id, api_version=api_version, template_url=self.get.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) response_headers = {} response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) deserialized = self._deserialize("Pool", pipeline_response) if cls: return cls(pipeline_response, deserialized, response_headers) return deserialized get.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/pools/{poolName}" } @distributed_trace_async async def disable_auto_scale( self, resource_group_name: str, account_name: str, pool_name: str, **kwargs: Any ) -> _models.Pool: """Disables automatic scaling for a pool. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param pool_name: The pool name. This must be unique within the account. Required. :type pool_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Pool or the result of cls(response) :rtype: ~azure.mgmt.batch.models.Pool :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.Pool] = kwargs.pop("cls", None) request = build_disable_auto_scale_request( resource_group_name=resource_group_name, account_name=account_name, pool_name=pool_name, subscription_id=self._config.subscription_id, api_version=api_version, template_url=self.disable_auto_scale.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) response_headers = {} response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) deserialized = self._deserialize("Pool", pipeline_response) if cls: return cls(pipeline_response, deserialized, response_headers) return deserialized disable_auto_scale.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/pools/{poolName}/disableAutoScale" } @distributed_trace_async async def stop_resize( self, resource_group_name: str, account_name: str, pool_name: str, **kwargs: Any ) -> _models.Pool: """Stops an ongoing resize operation on the pool. This does not restore the pool to its previous state before the resize operation: it only stops any further changes being made, and the pool maintains its current state. After stopping, the pool stabilizes at the number of nodes it was at when the stop operation was done. During the stop operation, the pool allocation state changes first to stopping and then to steady. A resize operation need not be an explicit resize pool request; this API can also be used to halt the initial sizing of the pool when it is created. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param pool_name: The pool name. This must be unique within the account. Required. :type pool_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Pool or the result of cls(response) :rtype: ~azure.mgmt.batch.models.Pool :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.Pool] = kwargs.pop("cls", None) request = build_stop_resize_request( resource_group_name=resource_group_name, account_name=account_name, pool_name=pool_name, subscription_id=self._config.subscription_id, api_version=api_version, template_url=self.stop_resize.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) response_headers = {} response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) deserialized = self._deserialize("Pool", pipeline_response) if cls: return cls(pipeline_response, deserialized, response_headers) return deserialized stop_resize.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/pools/{poolName}/stopResize" }
0.897413
0.082365
from io import IOBase from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload import urllib.parse from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, map_error, ) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling from ... import models as _models from ..._vendor import _convert_request from ...operations._batch_account_operations import ( build_create_request, build_delete_request, build_get_detector_request, build_get_keys_request, build_get_request, build_list_by_resource_group_request, build_list_detectors_request, build_list_outbound_network_dependencies_endpoints_request, build_list_request, build_regenerate_key_request, build_synchronize_auto_storage_keys_request, build_update_request, ) T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] class BatchAccountOperations: """ .. warning:: **DO NOT** instantiate this class directly. Instead, you should access the following operations through :class:`~azure.mgmt.batch.aio.BatchManagementClient`'s :attr:`batch_account` attribute. """ models = _models def __init__(self, *args, **kwargs) -> None: input_args = list(args) self._client = input_args.pop(0) if input_args else kwargs.pop("client") self._config = input_args.pop(0) if input_args else kwargs.pop("config") self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") async def _create_initial( self, resource_group_name: str, account_name: str, parameters: Union[_models.BatchAccountCreateParameters, IO], **kwargs: Any ) -> Optional[_models.BatchAccount]: error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[Optional[_models.BatchAccount]] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None if isinstance(parameters, (IOBase, bytes)): _content = parameters else: _json = self._serialize.body(parameters, "BatchAccountCreateParameters") request = build_create_request( resource_group_name=resource_group_name, account_name=account_name, subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, content=_content, template_url=self._create_initial.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = None response_headers = {} if response.status_code == 200: deserialized = self._deserialize("BatchAccount", pipeline_response) if response.status_code == 202: response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) if cls: return cls(pipeline_response, deserialized, response_headers) return deserialized _create_initial.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}" } @overload async def begin_create( self, resource_group_name: str, account_name: str, parameters: _models.BatchAccountCreateParameters, *, content_type: str = "application/json", **kwargs: Any ) -> AsyncLROPoller[_models.BatchAccount]: """Creates a new Batch account with the specified parameters. Existing accounts cannot be updated with this API and should instead be updated with the Update Batch Account API. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: A name for the Batch account which must be unique within the region. Batch account names must be between 3 and 24 characters in length and must use only numbers and lowercase letters. This name is used as part of the DNS name that is used to access the Batch service in the region in which the account is created. For example: http://accountname.region.batch.azure.com/. Required. :type account_name: str :param parameters: Additional parameters for account creation. Required. :type parameters: ~azure.mgmt.batch.models.BatchAccountCreateParameters :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of AsyncLROPoller that returns either BatchAccount or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.batch.models.BatchAccount] :raises ~azure.core.exceptions.HttpResponseError: """ @overload async def begin_create( self, resource_group_name: str, account_name: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any ) -> AsyncLROPoller[_models.BatchAccount]: """Creates a new Batch account with the specified parameters. Existing accounts cannot be updated with this API and should instead be updated with the Update Batch Account API. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: A name for the Batch account which must be unique within the region. Batch account names must be between 3 and 24 characters in length and must use only numbers and lowercase letters. This name is used as part of the DNS name that is used to access the Batch service in the region in which the account is created. For example: http://accountname.region.batch.azure.com/. Required. :type account_name: str :param parameters: Additional parameters for account creation. Required. :type parameters: IO :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of AsyncLROPoller that returns either BatchAccount or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.batch.models.BatchAccount] :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace_async async def begin_create( self, resource_group_name: str, account_name: str, parameters: Union[_models.BatchAccountCreateParameters, IO], **kwargs: Any ) -> AsyncLROPoller[_models.BatchAccount]: """Creates a new Batch account with the specified parameters. Existing accounts cannot be updated with this API and should instead be updated with the Update Batch Account API. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: A name for the Batch account which must be unique within the region. Batch account names must be between 3 and 24 characters in length and must use only numbers and lowercase letters. This name is used as part of the DNS name that is used to access the Batch service in the region in which the account is created. For example: http://accountname.region.batch.azure.com/. Required. :type account_name: str :param parameters: Additional parameters for account creation. Is either a BatchAccountCreateParameters type or a IO type. Required. :type parameters: ~azure.mgmt.batch.models.BatchAccountCreateParameters or IO :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. Default value is None. :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of AsyncLROPoller that returns either BatchAccount or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.batch.models.BatchAccount] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.BatchAccount] = kwargs.pop("cls", None) polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) cont_token: Optional[str] = kwargs.pop("continuation_token", None) if cont_token is None: raw_result = await self._create_initial( resource_group_name=resource_group_name, account_name=account_name, parameters=parameters, api_version=api_version, content_type=content_type, cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): deserialized = self._deserialize("BatchAccount", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized if polling is True: polling_method: AsyncPollingMethod = cast( AsyncPollingMethod, AsyncARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) ) elif polling is False: polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) else: polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore begin_create.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}" } @overload async def update( self, resource_group_name: str, account_name: str, parameters: _models.BatchAccountUpdateParameters, *, content_type: str = "application/json", **kwargs: Any ) -> _models.BatchAccount: """Updates the properties of an existing Batch account. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param parameters: Additional parameters for account update. Required. :type parameters: ~azure.mgmt.batch.models.BatchAccountUpdateParameters :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: BatchAccount or the result of cls(response) :rtype: ~azure.mgmt.batch.models.BatchAccount :raises ~azure.core.exceptions.HttpResponseError: """ @overload async def update( self, resource_group_name: str, account_name: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any ) -> _models.BatchAccount: """Updates the properties of an existing Batch account. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param parameters: Additional parameters for account update. Required. :type parameters: IO :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: BatchAccount or the result of cls(response) :rtype: ~azure.mgmt.batch.models.BatchAccount :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace_async async def update( self, resource_group_name: str, account_name: str, parameters: Union[_models.BatchAccountUpdateParameters, IO], **kwargs: Any ) -> _models.BatchAccount: """Updates the properties of an existing Batch account. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param parameters: Additional parameters for account update. Is either a BatchAccountUpdateParameters type or a IO type. Required. :type parameters: ~azure.mgmt.batch.models.BatchAccountUpdateParameters or IO :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. Default value is None. :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: BatchAccount or the result of cls(response) :rtype: ~azure.mgmt.batch.models.BatchAccount :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.BatchAccount] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None if isinstance(parameters, (IOBase, bytes)): _content = parameters else: _json = self._serialize.body(parameters, "BatchAccountUpdateParameters") request = build_update_request( resource_group_name=resource_group_name, account_name=account_name, subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, content=_content, template_url=self.update.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize("BatchAccount", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized update.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}" } async def _delete_initial( # pylint: disable=inconsistent-return-statements self, resource_group_name: str, account_name: str, **kwargs: Any ) -> None: error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[None] = kwargs.pop("cls", None) request = build_delete_request( resource_group_name=resource_group_name, account_name=account_name, subscription_id=self._config.subscription_id, api_version=api_version, template_url=self._delete_initial.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) response_headers = {} if response.status_code == 202: response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) if cls: return cls(pipeline_response, None, response_headers) _delete_initial.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}" } @distributed_trace_async async def begin_delete(self, resource_group_name: str, account_name: str, **kwargs: Any) -> AsyncLROPoller[None]: """Deletes the specified Batch account. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[None] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[None] = kwargs.pop("cls", None) polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) cont_token: Optional[str] = kwargs.pop("continuation_token", None) if cont_token is None: raw_result = await self._delete_initial( # type: ignore resource_group_name=resource_group_name, account_name=account_name, api_version=api_version, cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) if polling is True: polling_method: AsyncPollingMethod = cast( AsyncPollingMethod, AsyncARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) ) elif polling is False: polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) else: polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore begin_delete.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}" } @distributed_trace_async async def get(self, resource_group_name: str, account_name: str, **kwargs: Any) -> _models.BatchAccount: """Gets information about the specified Batch account. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: BatchAccount or the result of cls(response) :rtype: ~azure.mgmt.batch.models.BatchAccount :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.BatchAccount] = kwargs.pop("cls", None) request = build_get_request( resource_group_name=resource_group_name, account_name=account_name, subscription_id=self._config.subscription_id, api_version=api_version, template_url=self.get.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize("BatchAccount", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}" } @distributed_trace def list(self, **kwargs: Any) -> AsyncIterable["_models.BatchAccount"]: """Gets information about the Batch accounts associated with the subscription. :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either BatchAccount or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.batch.models.BatchAccount] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.BatchAccountListResult] = kwargs.pop("cls", None) error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_request( subscription_id=self._config.subscription_id, api_version=api_version, template_url=self.list.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) else: # make call to next link with the client's api-version _parsed_next_link = urllib.parse.urlparse(next_link) _next_request_params = case_insensitive_dict( { key: [urllib.parse.quote(v) for v in value] for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) _next_request_params["api-version"] = self._config.api_version request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) request.url = self._client.format_url(request.url) request.method = "GET" return request async def extract_data(pipeline_response): deserialized = self._deserialize("BatchAccountListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) # type: ignore return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged(get_next, extract_data) list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Batch/batchAccounts"} @distributed_trace def list_by_resource_group(self, resource_group_name: str, **kwargs: Any) -> AsyncIterable["_models.BatchAccount"]: """Gets information about the Batch accounts associated with the specified resource group. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either BatchAccount or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.batch.models.BatchAccount] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.BatchAccountListResult] = kwargs.pop("cls", None) error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_by_resource_group_request( resource_group_name=resource_group_name, subscription_id=self._config.subscription_id, api_version=api_version, template_url=self.list_by_resource_group.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) else: # make call to next link with the client's api-version _parsed_next_link = urllib.parse.urlparse(next_link) _next_request_params = case_insensitive_dict( { key: [urllib.parse.quote(v) for v in value] for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) _next_request_params["api-version"] = self._config.api_version request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) request.url = self._client.format_url(request.url) request.method = "GET" return request async def extract_data(pipeline_response): deserialized = self._deserialize("BatchAccountListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) # type: ignore return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged(get_next, extract_data) list_by_resource_group.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts" } @distributed_trace_async async def synchronize_auto_storage_keys( # pylint: disable=inconsistent-return-statements self, resource_group_name: str, account_name: str, **kwargs: Any ) -> None: """Synchronizes access keys for the auto-storage account configured for the specified Batch account, only if storage key authentication is being used. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: None or the result of cls(response) :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[None] = kwargs.pop("cls", None) request = build_synchronize_auto_storage_keys_request( resource_group_name=resource_group_name, account_name=account_name, subscription_id=self._config.subscription_id, api_version=api_version, template_url=self.synchronize_auto_storage_keys.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [204]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) synchronize_auto_storage_keys.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/syncAutoStorageKeys" } @overload async def regenerate_key( self, resource_group_name: str, account_name: str, parameters: _models.BatchAccountRegenerateKeyParameters, *, content_type: str = "application/json", **kwargs: Any ) -> _models.BatchAccountKeys: """Regenerates the specified account key for the Batch account. This operation applies only to Batch accounts with allowedAuthenticationModes containing 'SharedKey'. If the Batch account doesn't contain 'SharedKey' in its allowedAuthenticationMode, clients cannot use shared keys to authenticate, and must use another allowedAuthenticationModes instead. In this case, regenerating the keys will fail. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param parameters: The type of key to regenerate. Required. :type parameters: ~azure.mgmt.batch.models.BatchAccountRegenerateKeyParameters :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: BatchAccountKeys or the result of cls(response) :rtype: ~azure.mgmt.batch.models.BatchAccountKeys :raises ~azure.core.exceptions.HttpResponseError: """ @overload async def regenerate_key( self, resource_group_name: str, account_name: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any ) -> _models.BatchAccountKeys: """Regenerates the specified account key for the Batch account. This operation applies only to Batch accounts with allowedAuthenticationModes containing 'SharedKey'. If the Batch account doesn't contain 'SharedKey' in its allowedAuthenticationMode, clients cannot use shared keys to authenticate, and must use another allowedAuthenticationModes instead. In this case, regenerating the keys will fail. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param parameters: The type of key to regenerate. Required. :type parameters: IO :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: BatchAccountKeys or the result of cls(response) :rtype: ~azure.mgmt.batch.models.BatchAccountKeys :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace_async async def regenerate_key( self, resource_group_name: str, account_name: str, parameters: Union[_models.BatchAccountRegenerateKeyParameters, IO], **kwargs: Any ) -> _models.BatchAccountKeys: """Regenerates the specified account key for the Batch account. This operation applies only to Batch accounts with allowedAuthenticationModes containing 'SharedKey'. If the Batch account doesn't contain 'SharedKey' in its allowedAuthenticationMode, clients cannot use shared keys to authenticate, and must use another allowedAuthenticationModes instead. In this case, regenerating the keys will fail. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param parameters: The type of key to regenerate. Is either a BatchAccountRegenerateKeyParameters type or a IO type. Required. :type parameters: ~azure.mgmt.batch.models.BatchAccountRegenerateKeyParameters or IO :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. Default value is None. :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: BatchAccountKeys or the result of cls(response) :rtype: ~azure.mgmt.batch.models.BatchAccountKeys :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.BatchAccountKeys] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None if isinstance(parameters, (IOBase, bytes)): _content = parameters else: _json = self._serialize.body(parameters, "BatchAccountRegenerateKeyParameters") request = build_regenerate_key_request( resource_group_name=resource_group_name, account_name=account_name, subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, content=_content, template_url=self.regenerate_key.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize("BatchAccountKeys", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized regenerate_key.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/regenerateKeys" } @distributed_trace_async async def get_keys(self, resource_group_name: str, account_name: str, **kwargs: Any) -> _models.BatchAccountKeys: """Gets the account keys for the specified Batch account. This operation applies only to Batch accounts with allowedAuthenticationModes containing 'SharedKey'. If the Batch account doesn't contain 'SharedKey' in its allowedAuthenticationMode, clients cannot use shared keys to authenticate, and must use another allowedAuthenticationModes instead. In this case, getting the keys will fail. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: BatchAccountKeys or the result of cls(response) :rtype: ~azure.mgmt.batch.models.BatchAccountKeys :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.BatchAccountKeys] = kwargs.pop("cls", None) request = build_get_keys_request( resource_group_name=resource_group_name, account_name=account_name, subscription_id=self._config.subscription_id, api_version=api_version, template_url=self.get_keys.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize("BatchAccountKeys", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get_keys.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/listKeys" } @distributed_trace def list_detectors( self, resource_group_name: str, account_name: str, **kwargs: Any ) -> AsyncIterable["_models.DetectorResponse"]: """Gets information about the detectors available for a given Batch account. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either DetectorResponse or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.batch.models.DetectorResponse] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.DetectorListResult] = kwargs.pop("cls", None) error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_detectors_request( resource_group_name=resource_group_name, account_name=account_name, subscription_id=self._config.subscription_id, api_version=api_version, template_url=self.list_detectors.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) else: # make call to next link with the client's api-version _parsed_next_link = urllib.parse.urlparse(next_link) _next_request_params = case_insensitive_dict( { key: [urllib.parse.quote(v) for v in value] for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) _next_request_params["api-version"] = self._config.api_version request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) request.url = self._client.format_url(request.url) request.method = "GET" return request async def extract_data(pipeline_response): deserialized = self._deserialize("DetectorListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) # type: ignore return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged(get_next, extract_data) list_detectors.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/detectors" } @distributed_trace_async async def get_detector( self, resource_group_name: str, account_name: str, detector_id: str, **kwargs: Any ) -> _models.DetectorResponse: """Gets information about the given detector for a given Batch account. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param detector_id: The name of the detector. Required. :type detector_id: str :keyword callable cls: A custom type or function that will be passed the direct response :return: DetectorResponse or the result of cls(response) :rtype: ~azure.mgmt.batch.models.DetectorResponse :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.DetectorResponse] = kwargs.pop("cls", None) request = build_get_detector_request( resource_group_name=resource_group_name, account_name=account_name, detector_id=detector_id, subscription_id=self._config.subscription_id, api_version=api_version, template_url=self.get_detector.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize("DetectorResponse", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get_detector.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/detectors/{detectorId}" } @distributed_trace def list_outbound_network_dependencies_endpoints( self, resource_group_name: str, account_name: str, **kwargs: Any ) -> AsyncIterable["_models.OutboundEnvironmentEndpoint"]: """Lists the endpoints that a Batch Compute Node under this Batch Account may call as part of Batch service administration. If you are deploying a Pool inside of a virtual network that you specify, you must make sure your network allows outbound access to these endpoints. Failure to allow access to these endpoints may cause Batch to mark the affected nodes as unusable. For more information about creating a pool inside of a virtual network, see https://docs.microsoft.com/en-us/azure/batch/batch-virtual-network. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either OutboundEnvironmentEndpoint or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.batch.models.OutboundEnvironmentEndpoint] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.OutboundEnvironmentEndpointCollection] = kwargs.pop("cls", None) error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_outbound_network_dependencies_endpoints_request( resource_group_name=resource_group_name, account_name=account_name, subscription_id=self._config.subscription_id, api_version=api_version, template_url=self.list_outbound_network_dependencies_endpoints.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) else: # make call to next link with the client's api-version _parsed_next_link = urllib.parse.urlparse(next_link) _next_request_params = case_insensitive_dict( { key: [urllib.parse.quote(v) for v in value] for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) _next_request_params["api-version"] = self._config.api_version request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) request.url = self._client.format_url(request.url) request.method = "GET" return request async def extract_data(pipeline_response): deserialized = self._deserialize("OutboundEnvironmentEndpointCollection", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) # type: ignore return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged(get_next, extract_data) list_outbound_network_dependencies_endpoints.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/outboundNetworkDependenciesEndpoints" }
azure-mgmt-batch
/azure_mgmt_batch-17.1.0-py3-none-any.whl/azure/mgmt/batch/aio/operations/_batch_account_operations.py
_batch_account_operations.py
from io import IOBase from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload import urllib.parse from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, map_error, ) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling from ... import models as _models from ..._vendor import _convert_request from ...operations._batch_account_operations import ( build_create_request, build_delete_request, build_get_detector_request, build_get_keys_request, build_get_request, build_list_by_resource_group_request, build_list_detectors_request, build_list_outbound_network_dependencies_endpoints_request, build_list_request, build_regenerate_key_request, build_synchronize_auto_storage_keys_request, build_update_request, ) T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] class BatchAccountOperations: """ .. warning:: **DO NOT** instantiate this class directly. Instead, you should access the following operations through :class:`~azure.mgmt.batch.aio.BatchManagementClient`'s :attr:`batch_account` attribute. """ models = _models def __init__(self, *args, **kwargs) -> None: input_args = list(args) self._client = input_args.pop(0) if input_args else kwargs.pop("client") self._config = input_args.pop(0) if input_args else kwargs.pop("config") self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") async def _create_initial( self, resource_group_name: str, account_name: str, parameters: Union[_models.BatchAccountCreateParameters, IO], **kwargs: Any ) -> Optional[_models.BatchAccount]: error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[Optional[_models.BatchAccount]] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None if isinstance(parameters, (IOBase, bytes)): _content = parameters else: _json = self._serialize.body(parameters, "BatchAccountCreateParameters") request = build_create_request( resource_group_name=resource_group_name, account_name=account_name, subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, content=_content, template_url=self._create_initial.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = None response_headers = {} if response.status_code == 200: deserialized = self._deserialize("BatchAccount", pipeline_response) if response.status_code == 202: response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) if cls: return cls(pipeline_response, deserialized, response_headers) return deserialized _create_initial.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}" } @overload async def begin_create( self, resource_group_name: str, account_name: str, parameters: _models.BatchAccountCreateParameters, *, content_type: str = "application/json", **kwargs: Any ) -> AsyncLROPoller[_models.BatchAccount]: """Creates a new Batch account with the specified parameters. Existing accounts cannot be updated with this API and should instead be updated with the Update Batch Account API. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: A name for the Batch account which must be unique within the region. Batch account names must be between 3 and 24 characters in length and must use only numbers and lowercase letters. This name is used as part of the DNS name that is used to access the Batch service in the region in which the account is created. For example: http://accountname.region.batch.azure.com/. Required. :type account_name: str :param parameters: Additional parameters for account creation. Required. :type parameters: ~azure.mgmt.batch.models.BatchAccountCreateParameters :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of AsyncLROPoller that returns either BatchAccount or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.batch.models.BatchAccount] :raises ~azure.core.exceptions.HttpResponseError: """ @overload async def begin_create( self, resource_group_name: str, account_name: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any ) -> AsyncLROPoller[_models.BatchAccount]: """Creates a new Batch account with the specified parameters. Existing accounts cannot be updated with this API and should instead be updated with the Update Batch Account API. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: A name for the Batch account which must be unique within the region. Batch account names must be between 3 and 24 characters in length and must use only numbers and lowercase letters. This name is used as part of the DNS name that is used to access the Batch service in the region in which the account is created. For example: http://accountname.region.batch.azure.com/. Required. :type account_name: str :param parameters: Additional parameters for account creation. Required. :type parameters: IO :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of AsyncLROPoller that returns either BatchAccount or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.batch.models.BatchAccount] :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace_async async def begin_create( self, resource_group_name: str, account_name: str, parameters: Union[_models.BatchAccountCreateParameters, IO], **kwargs: Any ) -> AsyncLROPoller[_models.BatchAccount]: """Creates a new Batch account with the specified parameters. Existing accounts cannot be updated with this API and should instead be updated with the Update Batch Account API. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: A name for the Batch account which must be unique within the region. Batch account names must be between 3 and 24 characters in length and must use only numbers and lowercase letters. This name is used as part of the DNS name that is used to access the Batch service in the region in which the account is created. For example: http://accountname.region.batch.azure.com/. Required. :type account_name: str :param parameters: Additional parameters for account creation. Is either a BatchAccountCreateParameters type or a IO type. Required. :type parameters: ~azure.mgmt.batch.models.BatchAccountCreateParameters or IO :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. Default value is None. :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of AsyncLROPoller that returns either BatchAccount or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.batch.models.BatchAccount] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.BatchAccount] = kwargs.pop("cls", None) polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) cont_token: Optional[str] = kwargs.pop("continuation_token", None) if cont_token is None: raw_result = await self._create_initial( resource_group_name=resource_group_name, account_name=account_name, parameters=parameters, api_version=api_version, content_type=content_type, cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): deserialized = self._deserialize("BatchAccount", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized if polling is True: polling_method: AsyncPollingMethod = cast( AsyncPollingMethod, AsyncARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) ) elif polling is False: polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) else: polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore begin_create.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}" } @overload async def update( self, resource_group_name: str, account_name: str, parameters: _models.BatchAccountUpdateParameters, *, content_type: str = "application/json", **kwargs: Any ) -> _models.BatchAccount: """Updates the properties of an existing Batch account. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param parameters: Additional parameters for account update. Required. :type parameters: ~azure.mgmt.batch.models.BatchAccountUpdateParameters :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: BatchAccount or the result of cls(response) :rtype: ~azure.mgmt.batch.models.BatchAccount :raises ~azure.core.exceptions.HttpResponseError: """ @overload async def update( self, resource_group_name: str, account_name: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any ) -> _models.BatchAccount: """Updates the properties of an existing Batch account. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param parameters: Additional parameters for account update. Required. :type parameters: IO :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: BatchAccount or the result of cls(response) :rtype: ~azure.mgmt.batch.models.BatchAccount :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace_async async def update( self, resource_group_name: str, account_name: str, parameters: Union[_models.BatchAccountUpdateParameters, IO], **kwargs: Any ) -> _models.BatchAccount: """Updates the properties of an existing Batch account. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param parameters: Additional parameters for account update. Is either a BatchAccountUpdateParameters type or a IO type. Required. :type parameters: ~azure.mgmt.batch.models.BatchAccountUpdateParameters or IO :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. Default value is None. :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: BatchAccount or the result of cls(response) :rtype: ~azure.mgmt.batch.models.BatchAccount :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.BatchAccount] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None if isinstance(parameters, (IOBase, bytes)): _content = parameters else: _json = self._serialize.body(parameters, "BatchAccountUpdateParameters") request = build_update_request( resource_group_name=resource_group_name, account_name=account_name, subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, content=_content, template_url=self.update.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize("BatchAccount", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized update.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}" } async def _delete_initial( # pylint: disable=inconsistent-return-statements self, resource_group_name: str, account_name: str, **kwargs: Any ) -> None: error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[None] = kwargs.pop("cls", None) request = build_delete_request( resource_group_name=resource_group_name, account_name=account_name, subscription_id=self._config.subscription_id, api_version=api_version, template_url=self._delete_initial.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) response_headers = {} if response.status_code == 202: response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) if cls: return cls(pipeline_response, None, response_headers) _delete_initial.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}" } @distributed_trace_async async def begin_delete(self, resource_group_name: str, account_name: str, **kwargs: Any) -> AsyncLROPoller[None]: """Deletes the specified Batch account. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[None] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[None] = kwargs.pop("cls", None) polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) cont_token: Optional[str] = kwargs.pop("continuation_token", None) if cont_token is None: raw_result = await self._delete_initial( # type: ignore resource_group_name=resource_group_name, account_name=account_name, api_version=api_version, cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) if polling is True: polling_method: AsyncPollingMethod = cast( AsyncPollingMethod, AsyncARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) ) elif polling is False: polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) else: polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore begin_delete.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}" } @distributed_trace_async async def get(self, resource_group_name: str, account_name: str, **kwargs: Any) -> _models.BatchAccount: """Gets information about the specified Batch account. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: BatchAccount or the result of cls(response) :rtype: ~azure.mgmt.batch.models.BatchAccount :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.BatchAccount] = kwargs.pop("cls", None) request = build_get_request( resource_group_name=resource_group_name, account_name=account_name, subscription_id=self._config.subscription_id, api_version=api_version, template_url=self.get.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize("BatchAccount", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}" } @distributed_trace def list(self, **kwargs: Any) -> AsyncIterable["_models.BatchAccount"]: """Gets information about the Batch accounts associated with the subscription. :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either BatchAccount or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.batch.models.BatchAccount] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.BatchAccountListResult] = kwargs.pop("cls", None) error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_request( subscription_id=self._config.subscription_id, api_version=api_version, template_url=self.list.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) else: # make call to next link with the client's api-version _parsed_next_link = urllib.parse.urlparse(next_link) _next_request_params = case_insensitive_dict( { key: [urllib.parse.quote(v) for v in value] for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) _next_request_params["api-version"] = self._config.api_version request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) request.url = self._client.format_url(request.url) request.method = "GET" return request async def extract_data(pipeline_response): deserialized = self._deserialize("BatchAccountListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) # type: ignore return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged(get_next, extract_data) list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Batch/batchAccounts"} @distributed_trace def list_by_resource_group(self, resource_group_name: str, **kwargs: Any) -> AsyncIterable["_models.BatchAccount"]: """Gets information about the Batch accounts associated with the specified resource group. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either BatchAccount or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.batch.models.BatchAccount] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.BatchAccountListResult] = kwargs.pop("cls", None) error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_by_resource_group_request( resource_group_name=resource_group_name, subscription_id=self._config.subscription_id, api_version=api_version, template_url=self.list_by_resource_group.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) else: # make call to next link with the client's api-version _parsed_next_link = urllib.parse.urlparse(next_link) _next_request_params = case_insensitive_dict( { key: [urllib.parse.quote(v) for v in value] for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) _next_request_params["api-version"] = self._config.api_version request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) request.url = self._client.format_url(request.url) request.method = "GET" return request async def extract_data(pipeline_response): deserialized = self._deserialize("BatchAccountListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) # type: ignore return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged(get_next, extract_data) list_by_resource_group.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts" } @distributed_trace_async async def synchronize_auto_storage_keys( # pylint: disable=inconsistent-return-statements self, resource_group_name: str, account_name: str, **kwargs: Any ) -> None: """Synchronizes access keys for the auto-storage account configured for the specified Batch account, only if storage key authentication is being used. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: None or the result of cls(response) :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[None] = kwargs.pop("cls", None) request = build_synchronize_auto_storage_keys_request( resource_group_name=resource_group_name, account_name=account_name, subscription_id=self._config.subscription_id, api_version=api_version, template_url=self.synchronize_auto_storage_keys.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [204]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) synchronize_auto_storage_keys.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/syncAutoStorageKeys" } @overload async def regenerate_key( self, resource_group_name: str, account_name: str, parameters: _models.BatchAccountRegenerateKeyParameters, *, content_type: str = "application/json", **kwargs: Any ) -> _models.BatchAccountKeys: """Regenerates the specified account key for the Batch account. This operation applies only to Batch accounts with allowedAuthenticationModes containing 'SharedKey'. If the Batch account doesn't contain 'SharedKey' in its allowedAuthenticationMode, clients cannot use shared keys to authenticate, and must use another allowedAuthenticationModes instead. In this case, regenerating the keys will fail. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param parameters: The type of key to regenerate. Required. :type parameters: ~azure.mgmt.batch.models.BatchAccountRegenerateKeyParameters :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: BatchAccountKeys or the result of cls(response) :rtype: ~azure.mgmt.batch.models.BatchAccountKeys :raises ~azure.core.exceptions.HttpResponseError: """ @overload async def regenerate_key( self, resource_group_name: str, account_name: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any ) -> _models.BatchAccountKeys: """Regenerates the specified account key for the Batch account. This operation applies only to Batch accounts with allowedAuthenticationModes containing 'SharedKey'. If the Batch account doesn't contain 'SharedKey' in its allowedAuthenticationMode, clients cannot use shared keys to authenticate, and must use another allowedAuthenticationModes instead. In this case, regenerating the keys will fail. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param parameters: The type of key to regenerate. Required. :type parameters: IO :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: BatchAccountKeys or the result of cls(response) :rtype: ~azure.mgmt.batch.models.BatchAccountKeys :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace_async async def regenerate_key( self, resource_group_name: str, account_name: str, parameters: Union[_models.BatchAccountRegenerateKeyParameters, IO], **kwargs: Any ) -> _models.BatchAccountKeys: """Regenerates the specified account key for the Batch account. This operation applies only to Batch accounts with allowedAuthenticationModes containing 'SharedKey'. If the Batch account doesn't contain 'SharedKey' in its allowedAuthenticationMode, clients cannot use shared keys to authenticate, and must use another allowedAuthenticationModes instead. In this case, regenerating the keys will fail. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param parameters: The type of key to regenerate. Is either a BatchAccountRegenerateKeyParameters type or a IO type. Required. :type parameters: ~azure.mgmt.batch.models.BatchAccountRegenerateKeyParameters or IO :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. Default value is None. :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: BatchAccountKeys or the result of cls(response) :rtype: ~azure.mgmt.batch.models.BatchAccountKeys :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.BatchAccountKeys] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None if isinstance(parameters, (IOBase, bytes)): _content = parameters else: _json = self._serialize.body(parameters, "BatchAccountRegenerateKeyParameters") request = build_regenerate_key_request( resource_group_name=resource_group_name, account_name=account_name, subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, content=_content, template_url=self.regenerate_key.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize("BatchAccountKeys", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized regenerate_key.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/regenerateKeys" } @distributed_trace_async async def get_keys(self, resource_group_name: str, account_name: str, **kwargs: Any) -> _models.BatchAccountKeys: """Gets the account keys for the specified Batch account. This operation applies only to Batch accounts with allowedAuthenticationModes containing 'SharedKey'. If the Batch account doesn't contain 'SharedKey' in its allowedAuthenticationMode, clients cannot use shared keys to authenticate, and must use another allowedAuthenticationModes instead. In this case, getting the keys will fail. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: BatchAccountKeys or the result of cls(response) :rtype: ~azure.mgmt.batch.models.BatchAccountKeys :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.BatchAccountKeys] = kwargs.pop("cls", None) request = build_get_keys_request( resource_group_name=resource_group_name, account_name=account_name, subscription_id=self._config.subscription_id, api_version=api_version, template_url=self.get_keys.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize("BatchAccountKeys", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get_keys.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/listKeys" } @distributed_trace def list_detectors( self, resource_group_name: str, account_name: str, **kwargs: Any ) -> AsyncIterable["_models.DetectorResponse"]: """Gets information about the detectors available for a given Batch account. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either DetectorResponse or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.batch.models.DetectorResponse] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.DetectorListResult] = kwargs.pop("cls", None) error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_detectors_request( resource_group_name=resource_group_name, account_name=account_name, subscription_id=self._config.subscription_id, api_version=api_version, template_url=self.list_detectors.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) else: # make call to next link with the client's api-version _parsed_next_link = urllib.parse.urlparse(next_link) _next_request_params = case_insensitive_dict( { key: [urllib.parse.quote(v) for v in value] for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) _next_request_params["api-version"] = self._config.api_version request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) request.url = self._client.format_url(request.url) request.method = "GET" return request async def extract_data(pipeline_response): deserialized = self._deserialize("DetectorListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) # type: ignore return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged(get_next, extract_data) list_detectors.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/detectors" } @distributed_trace_async async def get_detector( self, resource_group_name: str, account_name: str, detector_id: str, **kwargs: Any ) -> _models.DetectorResponse: """Gets information about the given detector for a given Batch account. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param detector_id: The name of the detector. Required. :type detector_id: str :keyword callable cls: A custom type or function that will be passed the direct response :return: DetectorResponse or the result of cls(response) :rtype: ~azure.mgmt.batch.models.DetectorResponse :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.DetectorResponse] = kwargs.pop("cls", None) request = build_get_detector_request( resource_group_name=resource_group_name, account_name=account_name, detector_id=detector_id, subscription_id=self._config.subscription_id, api_version=api_version, template_url=self.get_detector.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize("DetectorResponse", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get_detector.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/detectors/{detectorId}" } @distributed_trace def list_outbound_network_dependencies_endpoints( self, resource_group_name: str, account_name: str, **kwargs: Any ) -> AsyncIterable["_models.OutboundEnvironmentEndpoint"]: """Lists the endpoints that a Batch Compute Node under this Batch Account may call as part of Batch service administration. If you are deploying a Pool inside of a virtual network that you specify, you must make sure your network allows outbound access to these endpoints. Failure to allow access to these endpoints may cause Batch to mark the affected nodes as unusable. For more information about creating a pool inside of a virtual network, see https://docs.microsoft.com/en-us/azure/batch/batch-virtual-network. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either OutboundEnvironmentEndpoint or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.batch.models.OutboundEnvironmentEndpoint] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.OutboundEnvironmentEndpointCollection] = kwargs.pop("cls", None) error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_outbound_network_dependencies_endpoints_request( resource_group_name=resource_group_name, account_name=account_name, subscription_id=self._config.subscription_id, api_version=api_version, template_url=self.list_outbound_network_dependencies_endpoints.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) else: # make call to next link with the client's api-version _parsed_next_link = urllib.parse.urlparse(next_link) _next_request_params = case_insensitive_dict( { key: [urllib.parse.quote(v) for v in value] for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) _next_request_params["api-version"] = self._config.api_version request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) request.url = self._client.format_url(request.url) request.method = "GET" return request async def extract_data(pipeline_response): deserialized = self._deserialize("OutboundEnvironmentEndpointCollection", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) # type: ignore return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged(get_next, extract_data) list_outbound_network_dependencies_endpoints.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/outboundNetworkDependenciesEndpoints" }
0.889595
0.071656
from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar import urllib.parse from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, map_error, ) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models from ..._vendor import _convert_request from ...operations._private_link_resource_operations import build_get_request, build_list_by_batch_account_request T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] class PrivateLinkResourceOperations: """ .. warning:: **DO NOT** instantiate this class directly. Instead, you should access the following operations through :class:`~azure.mgmt.batch.aio.BatchManagementClient`'s :attr:`private_link_resource` attribute. """ models = _models def __init__(self, *args, **kwargs) -> None: input_args = list(args) self._client = input_args.pop(0) if input_args else kwargs.pop("client") self._config = input_args.pop(0) if input_args else kwargs.pop("config") self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace def list_by_batch_account( self, resource_group_name: str, account_name: str, maxresults: Optional[int] = None, **kwargs: Any ) -> AsyncIterable["_models.PrivateLinkResource"]: """Lists all of the private link resources in the specified account. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param maxresults: The maximum number of items to return in the response. Default value is None. :type maxresults: int :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either PrivateLinkResource or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.batch.models.PrivateLinkResource] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.ListPrivateLinkResourcesResult] = kwargs.pop("cls", None) error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_by_batch_account_request( resource_group_name=resource_group_name, account_name=account_name, subscription_id=self._config.subscription_id, maxresults=maxresults, api_version=api_version, template_url=self.list_by_batch_account.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) else: # make call to next link with the client's api-version _parsed_next_link = urllib.parse.urlparse(next_link) _next_request_params = case_insensitive_dict( { key: [urllib.parse.quote(v) for v in value] for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) _next_request_params["api-version"] = self._config.api_version request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) request.url = self._client.format_url(request.url) request.method = "GET" return request async def extract_data(pipeline_response): deserialized = self._deserialize("ListPrivateLinkResourcesResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) # type: ignore return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged(get_next, extract_data) list_by_batch_account.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/privateLinkResources" } @distributed_trace_async async def get( self, resource_group_name: str, account_name: str, private_link_resource_name: str, **kwargs: Any ) -> _models.PrivateLinkResource: """Gets information about the specified private link resource. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param private_link_resource_name: The private link resource name. This must be unique within the account. Required. :type private_link_resource_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: PrivateLinkResource or the result of cls(response) :rtype: ~azure.mgmt.batch.models.PrivateLinkResource :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.PrivateLinkResource] = kwargs.pop("cls", None) request = build_get_request( resource_group_name=resource_group_name, account_name=account_name, private_link_resource_name=private_link_resource_name, subscription_id=self._config.subscription_id, api_version=api_version, template_url=self.get.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize("PrivateLinkResource", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/privateLinkResources/{privateLinkResourceName}" }
azure-mgmt-batch
/azure_mgmt_batch-17.1.0-py3-none-any.whl/azure/mgmt/batch/aio/operations/_private_link_resource_operations.py
_private_link_resource_operations.py
from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar import urllib.parse from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, map_error, ) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models from ..._vendor import _convert_request from ...operations._private_link_resource_operations import build_get_request, build_list_by_batch_account_request T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] class PrivateLinkResourceOperations: """ .. warning:: **DO NOT** instantiate this class directly. Instead, you should access the following operations through :class:`~azure.mgmt.batch.aio.BatchManagementClient`'s :attr:`private_link_resource` attribute. """ models = _models def __init__(self, *args, **kwargs) -> None: input_args = list(args) self._client = input_args.pop(0) if input_args else kwargs.pop("client") self._config = input_args.pop(0) if input_args else kwargs.pop("config") self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace def list_by_batch_account( self, resource_group_name: str, account_name: str, maxresults: Optional[int] = None, **kwargs: Any ) -> AsyncIterable["_models.PrivateLinkResource"]: """Lists all of the private link resources in the specified account. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param maxresults: The maximum number of items to return in the response. Default value is None. :type maxresults: int :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either PrivateLinkResource or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.batch.models.PrivateLinkResource] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.ListPrivateLinkResourcesResult] = kwargs.pop("cls", None) error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_by_batch_account_request( resource_group_name=resource_group_name, account_name=account_name, subscription_id=self._config.subscription_id, maxresults=maxresults, api_version=api_version, template_url=self.list_by_batch_account.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) else: # make call to next link with the client's api-version _parsed_next_link = urllib.parse.urlparse(next_link) _next_request_params = case_insensitive_dict( { key: [urllib.parse.quote(v) for v in value] for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) _next_request_params["api-version"] = self._config.api_version request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) request.url = self._client.format_url(request.url) request.method = "GET" return request async def extract_data(pipeline_response): deserialized = self._deserialize("ListPrivateLinkResourcesResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) # type: ignore return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged(get_next, extract_data) list_by_batch_account.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/privateLinkResources" } @distributed_trace_async async def get( self, resource_group_name: str, account_name: str, private_link_resource_name: str, **kwargs: Any ) -> _models.PrivateLinkResource: """Gets information about the specified private link resource. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param private_link_resource_name: The private link resource name. This must be unique within the account. Required. :type private_link_resource_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: PrivateLinkResource or the result of cls(response) :rtype: ~azure.mgmt.batch.models.PrivateLinkResource :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.PrivateLinkResource] = kwargs.pop("cls", None) request = build_get_request( resource_group_name=resource_group_name, account_name=account_name, private_link_resource_name=private_link_resource_name, subscription_id=self._config.subscription_id, api_version=api_version, template_url=self.get.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize("PrivateLinkResource", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/privateLinkResources/{privateLinkResourceName}" }
0.904355
0.087603
from io import IOBase from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, overload import urllib.parse from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, map_error, ) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models from ..._vendor import _convert_request from ...operations._application_operations import ( build_create_request, build_delete_request, build_get_request, build_list_request, build_update_request, ) T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] class ApplicationOperations: """ .. warning:: **DO NOT** instantiate this class directly. Instead, you should access the following operations through :class:`~azure.mgmt.batch.aio.BatchManagementClient`'s :attr:`application` attribute. """ models = _models def __init__(self, *args, **kwargs) -> None: input_args = list(args) self._client = input_args.pop(0) if input_args else kwargs.pop("client") self._config = input_args.pop(0) if input_args else kwargs.pop("config") self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @overload async def create( self, resource_group_name: str, account_name: str, application_name: str, parameters: Optional[_models.Application] = None, *, content_type: str = "application/json", **kwargs: Any ) -> _models.Application: """Adds an application to the specified Batch account. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param application_name: The name of the application. This must be unique within the account. Required. :type application_name: str :param parameters: The parameters for the request. Default value is None. :type parameters: ~azure.mgmt.batch.models.Application :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Application or the result of cls(response) :rtype: ~azure.mgmt.batch.models.Application :raises ~azure.core.exceptions.HttpResponseError: """ @overload async def create( self, resource_group_name: str, account_name: str, application_name: str, parameters: Optional[IO] = None, *, content_type: str = "application/json", **kwargs: Any ) -> _models.Application: """Adds an application to the specified Batch account. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param application_name: The name of the application. This must be unique within the account. Required. :type application_name: str :param parameters: The parameters for the request. Default value is None. :type parameters: IO :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Application or the result of cls(response) :rtype: ~azure.mgmt.batch.models.Application :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace_async async def create( self, resource_group_name: str, account_name: str, application_name: str, parameters: Optional[Union[_models.Application, IO]] = None, **kwargs: Any ) -> _models.Application: """Adds an application to the specified Batch account. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param application_name: The name of the application. This must be unique within the account. Required. :type application_name: str :param parameters: The parameters for the request. Is either a Application type or a IO type. Default value is None. :type parameters: ~azure.mgmt.batch.models.Application or IO :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. Default value is None. :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Application or the result of cls(response) :rtype: ~azure.mgmt.batch.models.Application :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.Application] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None if isinstance(parameters, (IOBase, bytes)): _content = parameters else: if parameters is not None: _json = self._serialize.body(parameters, "Application") else: _json = None request = build_create_request( resource_group_name=resource_group_name, account_name=account_name, application_name=application_name, subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, content=_content, template_url=self.create.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize("Application", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized create.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/applications/{applicationName}" } @distributed_trace_async async def delete( # pylint: disable=inconsistent-return-statements self, resource_group_name: str, account_name: str, application_name: str, **kwargs: Any ) -> None: """Deletes an application. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param application_name: The name of the application. This must be unique within the account. Required. :type application_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: None or the result of cls(response) :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[None] = kwargs.pop("cls", None) request = build_delete_request( resource_group_name=resource_group_name, account_name=account_name, application_name=application_name, subscription_id=self._config.subscription_id, api_version=api_version, template_url=self.delete.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) delete.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/applications/{applicationName}" } @distributed_trace_async async def get( self, resource_group_name: str, account_name: str, application_name: str, **kwargs: Any ) -> _models.Application: """Gets information about the specified application. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param application_name: The name of the application. This must be unique within the account. Required. :type application_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Application or the result of cls(response) :rtype: ~azure.mgmt.batch.models.Application :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.Application] = kwargs.pop("cls", None) request = build_get_request( resource_group_name=resource_group_name, account_name=account_name, application_name=application_name, subscription_id=self._config.subscription_id, api_version=api_version, template_url=self.get.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize("Application", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/applications/{applicationName}" } @overload async def update( self, resource_group_name: str, account_name: str, application_name: str, parameters: _models.Application, *, content_type: str = "application/json", **kwargs: Any ) -> _models.Application: """Updates settings for the specified application. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param application_name: The name of the application. This must be unique within the account. Required. :type application_name: str :param parameters: The parameters for the request. Required. :type parameters: ~azure.mgmt.batch.models.Application :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Application or the result of cls(response) :rtype: ~azure.mgmt.batch.models.Application :raises ~azure.core.exceptions.HttpResponseError: """ @overload async def update( self, resource_group_name: str, account_name: str, application_name: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any ) -> _models.Application: """Updates settings for the specified application. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param application_name: The name of the application. This must be unique within the account. Required. :type application_name: str :param parameters: The parameters for the request. Required. :type parameters: IO :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Application or the result of cls(response) :rtype: ~azure.mgmt.batch.models.Application :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace_async async def update( self, resource_group_name: str, account_name: str, application_name: str, parameters: Union[_models.Application, IO], **kwargs: Any ) -> _models.Application: """Updates settings for the specified application. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param application_name: The name of the application. This must be unique within the account. Required. :type application_name: str :param parameters: The parameters for the request. Is either a Application type or a IO type. Required. :type parameters: ~azure.mgmt.batch.models.Application or IO :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. Default value is None. :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Application or the result of cls(response) :rtype: ~azure.mgmt.batch.models.Application :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.Application] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None if isinstance(parameters, (IOBase, bytes)): _content = parameters else: _json = self._serialize.body(parameters, "Application") request = build_update_request( resource_group_name=resource_group_name, account_name=account_name, application_name=application_name, subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, content=_content, template_url=self.update.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize("Application", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized update.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/applications/{applicationName}" } @distributed_trace def list( self, resource_group_name: str, account_name: str, maxresults: Optional[int] = None, **kwargs: Any ) -> AsyncIterable["_models.Application"]: """Lists all of the applications in the specified account. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param maxresults: The maximum number of items to return in the response. Default value is None. :type maxresults: int :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either Application or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.batch.models.Application] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.ListApplicationsResult] = kwargs.pop("cls", None) error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_request( resource_group_name=resource_group_name, account_name=account_name, subscription_id=self._config.subscription_id, maxresults=maxresults, api_version=api_version, template_url=self.list.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) else: # make call to next link with the client's api-version _parsed_next_link = urllib.parse.urlparse(next_link) _next_request_params = case_insensitive_dict( { key: [urllib.parse.quote(v) for v in value] for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) _next_request_params["api-version"] = self._config.api_version request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) request.url = self._client.format_url(request.url) request.method = "GET" return request async def extract_data(pipeline_response): deserialized = self._deserialize("ListApplicationsResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) # type: ignore return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged(get_next, extract_data) list.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/applications" }
azure-mgmt-batch
/azure_mgmt_batch-17.1.0-py3-none-any.whl/azure/mgmt/batch/aio/operations/_application_operations.py
_application_operations.py
from io import IOBase from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, overload import urllib.parse from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, map_error, ) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models from ..._vendor import _convert_request from ...operations._application_operations import ( build_create_request, build_delete_request, build_get_request, build_list_request, build_update_request, ) T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] class ApplicationOperations: """ .. warning:: **DO NOT** instantiate this class directly. Instead, you should access the following operations through :class:`~azure.mgmt.batch.aio.BatchManagementClient`'s :attr:`application` attribute. """ models = _models def __init__(self, *args, **kwargs) -> None: input_args = list(args) self._client = input_args.pop(0) if input_args else kwargs.pop("client") self._config = input_args.pop(0) if input_args else kwargs.pop("config") self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @overload async def create( self, resource_group_name: str, account_name: str, application_name: str, parameters: Optional[_models.Application] = None, *, content_type: str = "application/json", **kwargs: Any ) -> _models.Application: """Adds an application to the specified Batch account. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param application_name: The name of the application. This must be unique within the account. Required. :type application_name: str :param parameters: The parameters for the request. Default value is None. :type parameters: ~azure.mgmt.batch.models.Application :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Application or the result of cls(response) :rtype: ~azure.mgmt.batch.models.Application :raises ~azure.core.exceptions.HttpResponseError: """ @overload async def create( self, resource_group_name: str, account_name: str, application_name: str, parameters: Optional[IO] = None, *, content_type: str = "application/json", **kwargs: Any ) -> _models.Application: """Adds an application to the specified Batch account. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param application_name: The name of the application. This must be unique within the account. Required. :type application_name: str :param parameters: The parameters for the request. Default value is None. :type parameters: IO :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Application or the result of cls(response) :rtype: ~azure.mgmt.batch.models.Application :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace_async async def create( self, resource_group_name: str, account_name: str, application_name: str, parameters: Optional[Union[_models.Application, IO]] = None, **kwargs: Any ) -> _models.Application: """Adds an application to the specified Batch account. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param application_name: The name of the application. This must be unique within the account. Required. :type application_name: str :param parameters: The parameters for the request. Is either a Application type or a IO type. Default value is None. :type parameters: ~azure.mgmt.batch.models.Application or IO :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. Default value is None. :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Application or the result of cls(response) :rtype: ~azure.mgmt.batch.models.Application :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.Application] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None if isinstance(parameters, (IOBase, bytes)): _content = parameters else: if parameters is not None: _json = self._serialize.body(parameters, "Application") else: _json = None request = build_create_request( resource_group_name=resource_group_name, account_name=account_name, application_name=application_name, subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, content=_content, template_url=self.create.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize("Application", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized create.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/applications/{applicationName}" } @distributed_trace_async async def delete( # pylint: disable=inconsistent-return-statements self, resource_group_name: str, account_name: str, application_name: str, **kwargs: Any ) -> None: """Deletes an application. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param application_name: The name of the application. This must be unique within the account. Required. :type application_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: None or the result of cls(response) :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[None] = kwargs.pop("cls", None) request = build_delete_request( resource_group_name=resource_group_name, account_name=account_name, application_name=application_name, subscription_id=self._config.subscription_id, api_version=api_version, template_url=self.delete.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) delete.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/applications/{applicationName}" } @distributed_trace_async async def get( self, resource_group_name: str, account_name: str, application_name: str, **kwargs: Any ) -> _models.Application: """Gets information about the specified application. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param application_name: The name of the application. This must be unique within the account. Required. :type application_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Application or the result of cls(response) :rtype: ~azure.mgmt.batch.models.Application :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.Application] = kwargs.pop("cls", None) request = build_get_request( resource_group_name=resource_group_name, account_name=account_name, application_name=application_name, subscription_id=self._config.subscription_id, api_version=api_version, template_url=self.get.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize("Application", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/applications/{applicationName}" } @overload async def update( self, resource_group_name: str, account_name: str, application_name: str, parameters: _models.Application, *, content_type: str = "application/json", **kwargs: Any ) -> _models.Application: """Updates settings for the specified application. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param application_name: The name of the application. This must be unique within the account. Required. :type application_name: str :param parameters: The parameters for the request. Required. :type parameters: ~azure.mgmt.batch.models.Application :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Application or the result of cls(response) :rtype: ~azure.mgmt.batch.models.Application :raises ~azure.core.exceptions.HttpResponseError: """ @overload async def update( self, resource_group_name: str, account_name: str, application_name: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any ) -> _models.Application: """Updates settings for the specified application. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param application_name: The name of the application. This must be unique within the account. Required. :type application_name: str :param parameters: The parameters for the request. Required. :type parameters: IO :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Application or the result of cls(response) :rtype: ~azure.mgmt.batch.models.Application :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace_async async def update( self, resource_group_name: str, account_name: str, application_name: str, parameters: Union[_models.Application, IO], **kwargs: Any ) -> _models.Application: """Updates settings for the specified application. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param application_name: The name of the application. This must be unique within the account. Required. :type application_name: str :param parameters: The parameters for the request. Is either a Application type or a IO type. Required. :type parameters: ~azure.mgmt.batch.models.Application or IO :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. Default value is None. :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Application or the result of cls(response) :rtype: ~azure.mgmt.batch.models.Application :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.Application] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None if isinstance(parameters, (IOBase, bytes)): _content = parameters else: _json = self._serialize.body(parameters, "Application") request = build_update_request( resource_group_name=resource_group_name, account_name=account_name, application_name=application_name, subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, content=_content, template_url=self.update.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize("Application", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized update.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/applications/{applicationName}" } @distributed_trace def list( self, resource_group_name: str, account_name: str, maxresults: Optional[int] = None, **kwargs: Any ) -> AsyncIterable["_models.Application"]: """Lists all of the applications in the specified account. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param maxresults: The maximum number of items to return in the response. Default value is None. :type maxresults: int :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either Application or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.batch.models.Application] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.ListApplicationsResult] = kwargs.pop("cls", None) error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_request( resource_group_name=resource_group_name, account_name=account_name, subscription_id=self._config.subscription_id, maxresults=maxresults, api_version=api_version, template_url=self.list.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) else: # make call to next link with the client's api-version _parsed_next_link = urllib.parse.urlparse(next_link) _next_request_params = case_insensitive_dict( { key: [urllib.parse.quote(v) for v in value] for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) _next_request_params["api-version"] = self._config.api_version request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) request.url = self._client.format_url(request.url) request.method = "GET" return request async def extract_data(pipeline_response): deserialized = self._deserialize("ListApplicationsResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) # type: ignore return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged(get_next, extract_data) list.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/applications" }
0.898019
0.093182
from io import IOBase from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, overload import urllib.parse from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, map_error, ) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models from ..._vendor import _convert_request from ...operations._application_package_operations import ( build_activate_request, build_create_request, build_delete_request, build_get_request, build_list_request, ) T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] class ApplicationPackageOperations: """ .. warning:: **DO NOT** instantiate this class directly. Instead, you should access the following operations through :class:`~azure.mgmt.batch.aio.BatchManagementClient`'s :attr:`application_package` attribute. """ models = _models def __init__(self, *args, **kwargs) -> None: input_args = list(args) self._client = input_args.pop(0) if input_args else kwargs.pop("client") self._config = input_args.pop(0) if input_args else kwargs.pop("config") self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @overload async def activate( self, resource_group_name: str, account_name: str, application_name: str, version_name: str, parameters: _models.ActivateApplicationPackageParameters, *, content_type: str = "application/json", **kwargs: Any ) -> _models.ApplicationPackage: """Activates the specified application package. This should be done after the ``ApplicationPackage`` was created and uploaded. This needs to be done before an ``ApplicationPackage`` can be used on Pools or Tasks. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param application_name: The name of the application. This must be unique within the account. Required. :type application_name: str :param version_name: The version of the application. Required. :type version_name: str :param parameters: The parameters for the request. Required. :type parameters: ~azure.mgmt.batch.models.ActivateApplicationPackageParameters :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: ApplicationPackage or the result of cls(response) :rtype: ~azure.mgmt.batch.models.ApplicationPackage :raises ~azure.core.exceptions.HttpResponseError: """ @overload async def activate( self, resource_group_name: str, account_name: str, application_name: str, version_name: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any ) -> _models.ApplicationPackage: """Activates the specified application package. This should be done after the ``ApplicationPackage`` was created and uploaded. This needs to be done before an ``ApplicationPackage`` can be used on Pools or Tasks. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param application_name: The name of the application. This must be unique within the account. Required. :type application_name: str :param version_name: The version of the application. Required. :type version_name: str :param parameters: The parameters for the request. Required. :type parameters: IO :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: ApplicationPackage or the result of cls(response) :rtype: ~azure.mgmt.batch.models.ApplicationPackage :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace_async async def activate( self, resource_group_name: str, account_name: str, application_name: str, version_name: str, parameters: Union[_models.ActivateApplicationPackageParameters, IO], **kwargs: Any ) -> _models.ApplicationPackage: """Activates the specified application package. This should be done after the ``ApplicationPackage`` was created and uploaded. This needs to be done before an ``ApplicationPackage`` can be used on Pools or Tasks. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param application_name: The name of the application. This must be unique within the account. Required. :type application_name: str :param version_name: The version of the application. Required. :type version_name: str :param parameters: The parameters for the request. Is either a ActivateApplicationPackageParameters type or a IO type. Required. :type parameters: ~azure.mgmt.batch.models.ActivateApplicationPackageParameters or IO :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. Default value is None. :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: ApplicationPackage or the result of cls(response) :rtype: ~azure.mgmt.batch.models.ApplicationPackage :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.ApplicationPackage] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None if isinstance(parameters, (IOBase, bytes)): _content = parameters else: _json = self._serialize.body(parameters, "ActivateApplicationPackageParameters") request = build_activate_request( resource_group_name=resource_group_name, account_name=account_name, application_name=application_name, version_name=version_name, subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, content=_content, template_url=self.activate.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize("ApplicationPackage", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized activate.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/applications/{applicationName}/versions/{versionName}/activate" } @overload async def create( self, resource_group_name: str, account_name: str, application_name: str, version_name: str, parameters: Optional[_models.ApplicationPackage] = None, *, content_type: str = "application/json", **kwargs: Any ) -> _models.ApplicationPackage: """Creates an application package record. The record contains a storageUrl where the package should be uploaded to. Once it is uploaded the ``ApplicationPackage`` needs to be activated using ``ApplicationPackageActive`` before it can be used. If the auto storage account was configured to use storage keys, the URL returned will contain a SAS. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param application_name: The name of the application. This must be unique within the account. Required. :type application_name: str :param version_name: The version of the application. Required. :type version_name: str :param parameters: The parameters for the request. Default value is None. :type parameters: ~azure.mgmt.batch.models.ApplicationPackage :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: ApplicationPackage or the result of cls(response) :rtype: ~azure.mgmt.batch.models.ApplicationPackage :raises ~azure.core.exceptions.HttpResponseError: """ @overload async def create( self, resource_group_name: str, account_name: str, application_name: str, version_name: str, parameters: Optional[IO] = None, *, content_type: str = "application/json", **kwargs: Any ) -> _models.ApplicationPackage: """Creates an application package record. The record contains a storageUrl where the package should be uploaded to. Once it is uploaded the ``ApplicationPackage`` needs to be activated using ``ApplicationPackageActive`` before it can be used. If the auto storage account was configured to use storage keys, the URL returned will contain a SAS. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param application_name: The name of the application. This must be unique within the account. Required. :type application_name: str :param version_name: The version of the application. Required. :type version_name: str :param parameters: The parameters for the request. Default value is None. :type parameters: IO :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: ApplicationPackage or the result of cls(response) :rtype: ~azure.mgmt.batch.models.ApplicationPackage :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace_async async def create( self, resource_group_name: str, account_name: str, application_name: str, version_name: str, parameters: Optional[Union[_models.ApplicationPackage, IO]] = None, **kwargs: Any ) -> _models.ApplicationPackage: """Creates an application package record. The record contains a storageUrl where the package should be uploaded to. Once it is uploaded the ``ApplicationPackage`` needs to be activated using ``ApplicationPackageActive`` before it can be used. If the auto storage account was configured to use storage keys, the URL returned will contain a SAS. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param application_name: The name of the application. This must be unique within the account. Required. :type application_name: str :param version_name: The version of the application. Required. :type version_name: str :param parameters: The parameters for the request. Is either a ApplicationPackage type or a IO type. Default value is None. :type parameters: ~azure.mgmt.batch.models.ApplicationPackage or IO :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. Default value is None. :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: ApplicationPackage or the result of cls(response) :rtype: ~azure.mgmt.batch.models.ApplicationPackage :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.ApplicationPackage] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None if isinstance(parameters, (IOBase, bytes)): _content = parameters else: if parameters is not None: _json = self._serialize.body(parameters, "ApplicationPackage") else: _json = None request = build_create_request( resource_group_name=resource_group_name, account_name=account_name, application_name=application_name, version_name=version_name, subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, content=_content, template_url=self.create.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize("ApplicationPackage", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized create.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/applications/{applicationName}/versions/{versionName}" } @distributed_trace_async async def delete( # pylint: disable=inconsistent-return-statements self, resource_group_name: str, account_name: str, application_name: str, version_name: str, **kwargs: Any ) -> None: """Deletes an application package record and its associated binary file. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param application_name: The name of the application. This must be unique within the account. Required. :type application_name: str :param version_name: The version of the application. Required. :type version_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: None or the result of cls(response) :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[None] = kwargs.pop("cls", None) request = build_delete_request( resource_group_name=resource_group_name, account_name=account_name, application_name=application_name, version_name=version_name, subscription_id=self._config.subscription_id, api_version=api_version, template_url=self.delete.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) delete.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/applications/{applicationName}/versions/{versionName}" } @distributed_trace_async async def get( self, resource_group_name: str, account_name: str, application_name: str, version_name: str, **kwargs: Any ) -> _models.ApplicationPackage: """Gets information about the specified application package. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param application_name: The name of the application. This must be unique within the account. Required. :type application_name: str :param version_name: The version of the application. Required. :type version_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: ApplicationPackage or the result of cls(response) :rtype: ~azure.mgmt.batch.models.ApplicationPackage :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.ApplicationPackage] = kwargs.pop("cls", None) request = build_get_request( resource_group_name=resource_group_name, account_name=account_name, application_name=application_name, version_name=version_name, subscription_id=self._config.subscription_id, api_version=api_version, template_url=self.get.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize("ApplicationPackage", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/applications/{applicationName}/versions/{versionName}" } @distributed_trace def list( self, resource_group_name: str, account_name: str, application_name: str, maxresults: Optional[int] = None, **kwargs: Any ) -> AsyncIterable["_models.ApplicationPackage"]: """Lists all of the application packages in the specified application. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param application_name: The name of the application. This must be unique within the account. Required. :type application_name: str :param maxresults: The maximum number of items to return in the response. Default value is None. :type maxresults: int :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ApplicationPackage or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.batch.models.ApplicationPackage] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.ListApplicationPackagesResult] = kwargs.pop("cls", None) error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_request( resource_group_name=resource_group_name, account_name=account_name, application_name=application_name, subscription_id=self._config.subscription_id, maxresults=maxresults, api_version=api_version, template_url=self.list.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) else: # make call to next link with the client's api-version _parsed_next_link = urllib.parse.urlparse(next_link) _next_request_params = case_insensitive_dict( { key: [urllib.parse.quote(v) for v in value] for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) _next_request_params["api-version"] = self._config.api_version request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) request.url = self._client.format_url(request.url) request.method = "GET" return request async def extract_data(pipeline_response): deserialized = self._deserialize("ListApplicationPackagesResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) # type: ignore return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged(get_next, extract_data) list.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/applications/{applicationName}/versions" }
azure-mgmt-batch
/azure_mgmt_batch-17.1.0-py3-none-any.whl/azure/mgmt/batch/aio/operations/_application_package_operations.py
_application_package_operations.py
from io import IOBase from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, overload import urllib.parse from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, map_error, ) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models from ..._vendor import _convert_request from ...operations._application_package_operations import ( build_activate_request, build_create_request, build_delete_request, build_get_request, build_list_request, ) T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] class ApplicationPackageOperations: """ .. warning:: **DO NOT** instantiate this class directly. Instead, you should access the following operations through :class:`~azure.mgmt.batch.aio.BatchManagementClient`'s :attr:`application_package` attribute. """ models = _models def __init__(self, *args, **kwargs) -> None: input_args = list(args) self._client = input_args.pop(0) if input_args else kwargs.pop("client") self._config = input_args.pop(0) if input_args else kwargs.pop("config") self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @overload async def activate( self, resource_group_name: str, account_name: str, application_name: str, version_name: str, parameters: _models.ActivateApplicationPackageParameters, *, content_type: str = "application/json", **kwargs: Any ) -> _models.ApplicationPackage: """Activates the specified application package. This should be done after the ``ApplicationPackage`` was created and uploaded. This needs to be done before an ``ApplicationPackage`` can be used on Pools or Tasks. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param application_name: The name of the application. This must be unique within the account. Required. :type application_name: str :param version_name: The version of the application. Required. :type version_name: str :param parameters: The parameters for the request. Required. :type parameters: ~azure.mgmt.batch.models.ActivateApplicationPackageParameters :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: ApplicationPackage or the result of cls(response) :rtype: ~azure.mgmt.batch.models.ApplicationPackage :raises ~azure.core.exceptions.HttpResponseError: """ @overload async def activate( self, resource_group_name: str, account_name: str, application_name: str, version_name: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any ) -> _models.ApplicationPackage: """Activates the specified application package. This should be done after the ``ApplicationPackage`` was created and uploaded. This needs to be done before an ``ApplicationPackage`` can be used on Pools or Tasks. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param application_name: The name of the application. This must be unique within the account. Required. :type application_name: str :param version_name: The version of the application. Required. :type version_name: str :param parameters: The parameters for the request. Required. :type parameters: IO :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: ApplicationPackage or the result of cls(response) :rtype: ~azure.mgmt.batch.models.ApplicationPackage :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace_async async def activate( self, resource_group_name: str, account_name: str, application_name: str, version_name: str, parameters: Union[_models.ActivateApplicationPackageParameters, IO], **kwargs: Any ) -> _models.ApplicationPackage: """Activates the specified application package. This should be done after the ``ApplicationPackage`` was created and uploaded. This needs to be done before an ``ApplicationPackage`` can be used on Pools or Tasks. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param application_name: The name of the application. This must be unique within the account. Required. :type application_name: str :param version_name: The version of the application. Required. :type version_name: str :param parameters: The parameters for the request. Is either a ActivateApplicationPackageParameters type or a IO type. Required. :type parameters: ~azure.mgmt.batch.models.ActivateApplicationPackageParameters or IO :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. Default value is None. :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: ApplicationPackage or the result of cls(response) :rtype: ~azure.mgmt.batch.models.ApplicationPackage :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.ApplicationPackage] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None if isinstance(parameters, (IOBase, bytes)): _content = parameters else: _json = self._serialize.body(parameters, "ActivateApplicationPackageParameters") request = build_activate_request( resource_group_name=resource_group_name, account_name=account_name, application_name=application_name, version_name=version_name, subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, content=_content, template_url=self.activate.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize("ApplicationPackage", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized activate.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/applications/{applicationName}/versions/{versionName}/activate" } @overload async def create( self, resource_group_name: str, account_name: str, application_name: str, version_name: str, parameters: Optional[_models.ApplicationPackage] = None, *, content_type: str = "application/json", **kwargs: Any ) -> _models.ApplicationPackage: """Creates an application package record. The record contains a storageUrl where the package should be uploaded to. Once it is uploaded the ``ApplicationPackage`` needs to be activated using ``ApplicationPackageActive`` before it can be used. If the auto storage account was configured to use storage keys, the URL returned will contain a SAS. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param application_name: The name of the application. This must be unique within the account. Required. :type application_name: str :param version_name: The version of the application. Required. :type version_name: str :param parameters: The parameters for the request. Default value is None. :type parameters: ~azure.mgmt.batch.models.ApplicationPackage :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: ApplicationPackage or the result of cls(response) :rtype: ~azure.mgmt.batch.models.ApplicationPackage :raises ~azure.core.exceptions.HttpResponseError: """ @overload async def create( self, resource_group_name: str, account_name: str, application_name: str, version_name: str, parameters: Optional[IO] = None, *, content_type: str = "application/json", **kwargs: Any ) -> _models.ApplicationPackage: """Creates an application package record. The record contains a storageUrl where the package should be uploaded to. Once it is uploaded the ``ApplicationPackage`` needs to be activated using ``ApplicationPackageActive`` before it can be used. If the auto storage account was configured to use storage keys, the URL returned will contain a SAS. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param application_name: The name of the application. This must be unique within the account. Required. :type application_name: str :param version_name: The version of the application. Required. :type version_name: str :param parameters: The parameters for the request. Default value is None. :type parameters: IO :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: ApplicationPackage or the result of cls(response) :rtype: ~azure.mgmt.batch.models.ApplicationPackage :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace_async async def create( self, resource_group_name: str, account_name: str, application_name: str, version_name: str, parameters: Optional[Union[_models.ApplicationPackage, IO]] = None, **kwargs: Any ) -> _models.ApplicationPackage: """Creates an application package record. The record contains a storageUrl where the package should be uploaded to. Once it is uploaded the ``ApplicationPackage`` needs to be activated using ``ApplicationPackageActive`` before it can be used. If the auto storage account was configured to use storage keys, the URL returned will contain a SAS. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param application_name: The name of the application. This must be unique within the account. Required. :type application_name: str :param version_name: The version of the application. Required. :type version_name: str :param parameters: The parameters for the request. Is either a ApplicationPackage type or a IO type. Default value is None. :type parameters: ~azure.mgmt.batch.models.ApplicationPackage or IO :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. Default value is None. :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: ApplicationPackage or the result of cls(response) :rtype: ~azure.mgmt.batch.models.ApplicationPackage :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.ApplicationPackage] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None if isinstance(parameters, (IOBase, bytes)): _content = parameters else: if parameters is not None: _json = self._serialize.body(parameters, "ApplicationPackage") else: _json = None request = build_create_request( resource_group_name=resource_group_name, account_name=account_name, application_name=application_name, version_name=version_name, subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, content=_content, template_url=self.create.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize("ApplicationPackage", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized create.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/applications/{applicationName}/versions/{versionName}" } @distributed_trace_async async def delete( # pylint: disable=inconsistent-return-statements self, resource_group_name: str, account_name: str, application_name: str, version_name: str, **kwargs: Any ) -> None: """Deletes an application package record and its associated binary file. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param application_name: The name of the application. This must be unique within the account. Required. :type application_name: str :param version_name: The version of the application. Required. :type version_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: None or the result of cls(response) :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[None] = kwargs.pop("cls", None) request = build_delete_request( resource_group_name=resource_group_name, account_name=account_name, application_name=application_name, version_name=version_name, subscription_id=self._config.subscription_id, api_version=api_version, template_url=self.delete.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) delete.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/applications/{applicationName}/versions/{versionName}" } @distributed_trace_async async def get( self, resource_group_name: str, account_name: str, application_name: str, version_name: str, **kwargs: Any ) -> _models.ApplicationPackage: """Gets information about the specified application package. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param application_name: The name of the application. This must be unique within the account. Required. :type application_name: str :param version_name: The version of the application. Required. :type version_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: ApplicationPackage or the result of cls(response) :rtype: ~azure.mgmt.batch.models.ApplicationPackage :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.ApplicationPackage] = kwargs.pop("cls", None) request = build_get_request( resource_group_name=resource_group_name, account_name=account_name, application_name=application_name, version_name=version_name, subscription_id=self._config.subscription_id, api_version=api_version, template_url=self.get.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize("ApplicationPackage", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/applications/{applicationName}/versions/{versionName}" } @distributed_trace def list( self, resource_group_name: str, account_name: str, application_name: str, maxresults: Optional[int] = None, **kwargs: Any ) -> AsyncIterable["_models.ApplicationPackage"]: """Lists all of the application packages in the specified application. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param application_name: The name of the application. This must be unique within the account. Required. :type application_name: str :param maxresults: The maximum number of items to return in the response. Default value is None. :type maxresults: int :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ApplicationPackage or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.batch.models.ApplicationPackage] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.ListApplicationPackagesResult] = kwargs.pop("cls", None) error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_request( resource_group_name=resource_group_name, account_name=account_name, application_name=application_name, subscription_id=self._config.subscription_id, maxresults=maxresults, api_version=api_version, template_url=self.list.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) else: # make call to next link with the client's api-version _parsed_next_link = urllib.parse.urlparse(next_link) _next_request_params = case_insensitive_dict( { key: [urllib.parse.quote(v) for v in value] for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) _next_request_params["api-version"] = self._config.api_version request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) request.url = self._client.format_url(request.url) request.method = "GET" return request async def extract_data(pipeline_response): deserialized = self._deserialize("ListApplicationPackagesResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) # type: ignore return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged(get_next, extract_data) list.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/applications/{applicationName}/versions" }
0.916072
0.080792
from io import IOBase from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload import urllib.parse from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, map_error, ) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling from ... import models as _models from ..._vendor import _convert_request from ...operations._private_endpoint_connection_operations import ( build_delete_request, build_get_request, build_list_by_batch_account_request, build_update_request, ) T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] class PrivateEndpointConnectionOperations: """ .. warning:: **DO NOT** instantiate this class directly. Instead, you should access the following operations through :class:`~azure.mgmt.batch.aio.BatchManagementClient`'s :attr:`private_endpoint_connection` attribute. """ models = _models def __init__(self, *args, **kwargs) -> None: input_args = list(args) self._client = input_args.pop(0) if input_args else kwargs.pop("client") self._config = input_args.pop(0) if input_args else kwargs.pop("config") self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace def list_by_batch_account( self, resource_group_name: str, account_name: str, maxresults: Optional[int] = None, **kwargs: Any ) -> AsyncIterable["_models.PrivateEndpointConnection"]: """Lists all of the private endpoint connections in the specified account. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param maxresults: The maximum number of items to return in the response. Default value is None. :type maxresults: int :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either PrivateEndpointConnection or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.batch.models.PrivateEndpointConnection] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.ListPrivateEndpointConnectionsResult] = kwargs.pop("cls", None) error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_by_batch_account_request( resource_group_name=resource_group_name, account_name=account_name, subscription_id=self._config.subscription_id, maxresults=maxresults, api_version=api_version, template_url=self.list_by_batch_account.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) else: # make call to next link with the client's api-version _parsed_next_link = urllib.parse.urlparse(next_link) _next_request_params = case_insensitive_dict( { key: [urllib.parse.quote(v) for v in value] for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) _next_request_params["api-version"] = self._config.api_version request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) request.url = self._client.format_url(request.url) request.method = "GET" return request async def extract_data(pipeline_response): deserialized = self._deserialize("ListPrivateEndpointConnectionsResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) # type: ignore return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged(get_next, extract_data) list_by_batch_account.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/privateEndpointConnections" } @distributed_trace_async async def get( self, resource_group_name: str, account_name: str, private_endpoint_connection_name: str, **kwargs: Any ) -> _models.PrivateEndpointConnection: """Gets information about the specified private endpoint connection. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param private_endpoint_connection_name: The private endpoint connection name. This must be unique within the account. Required. :type private_endpoint_connection_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: PrivateEndpointConnection or the result of cls(response) :rtype: ~azure.mgmt.batch.models.PrivateEndpointConnection :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.PrivateEndpointConnection] = kwargs.pop("cls", None) request = build_get_request( resource_group_name=resource_group_name, account_name=account_name, private_endpoint_connection_name=private_endpoint_connection_name, subscription_id=self._config.subscription_id, api_version=api_version, template_url=self.get.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize("PrivateEndpointConnection", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/privateEndpointConnections/{privateEndpointConnectionName}" } async def _update_initial( self, resource_group_name: str, account_name: str, private_endpoint_connection_name: str, parameters: Union[_models.PrivateEndpointConnection, IO], if_match: Optional[str] = None, **kwargs: Any ) -> Optional[_models.PrivateEndpointConnection]: error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[Optional[_models.PrivateEndpointConnection]] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None if isinstance(parameters, (IOBase, bytes)): _content = parameters else: _json = self._serialize.body(parameters, "PrivateEndpointConnection") request = build_update_request( resource_group_name=resource_group_name, account_name=account_name, private_endpoint_connection_name=private_endpoint_connection_name, subscription_id=self._config.subscription_id, if_match=if_match, api_version=api_version, content_type=content_type, json=_json, content=_content, template_url=self._update_initial.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = None response_headers = {} if response.status_code == 200: deserialized = self._deserialize("PrivateEndpointConnection", pipeline_response) if response.status_code == 202: response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) if cls: return cls(pipeline_response, deserialized, response_headers) return deserialized _update_initial.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/privateEndpointConnections/{privateEndpointConnectionName}" } @overload async def begin_update( self, resource_group_name: str, account_name: str, private_endpoint_connection_name: str, parameters: _models.PrivateEndpointConnection, if_match: Optional[str] = None, *, content_type: str = "application/json", **kwargs: Any ) -> AsyncLROPoller[_models.PrivateEndpointConnection]: """Updates the properties of an existing private endpoint connection. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param private_endpoint_connection_name: The private endpoint connection name. This must be unique within the account. Required. :type private_endpoint_connection_name: str :param parameters: PrivateEndpointConnection properties that should be updated. Properties that are supplied will be updated, any property not supplied will be unchanged. Required. :type parameters: ~azure.mgmt.batch.models.PrivateEndpointConnection :param if_match: The state (ETag) version of the private endpoint connection to update. This value can be omitted or set to "*" to apply the operation unconditionally. Default value is None. :type if_match: str :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of AsyncLROPoller that returns either PrivateEndpointConnection or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.batch.models.PrivateEndpointConnection] :raises ~azure.core.exceptions.HttpResponseError: """ @overload async def begin_update( self, resource_group_name: str, account_name: str, private_endpoint_connection_name: str, parameters: IO, if_match: Optional[str] = None, *, content_type: str = "application/json", **kwargs: Any ) -> AsyncLROPoller[_models.PrivateEndpointConnection]: """Updates the properties of an existing private endpoint connection. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param private_endpoint_connection_name: The private endpoint connection name. This must be unique within the account. Required. :type private_endpoint_connection_name: str :param parameters: PrivateEndpointConnection properties that should be updated. Properties that are supplied will be updated, any property not supplied will be unchanged. Required. :type parameters: IO :param if_match: The state (ETag) version of the private endpoint connection to update. This value can be omitted or set to "*" to apply the operation unconditionally. Default value is None. :type if_match: str :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of AsyncLROPoller that returns either PrivateEndpointConnection or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.batch.models.PrivateEndpointConnection] :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace_async async def begin_update( self, resource_group_name: str, account_name: str, private_endpoint_connection_name: str, parameters: Union[_models.PrivateEndpointConnection, IO], if_match: Optional[str] = None, **kwargs: Any ) -> AsyncLROPoller[_models.PrivateEndpointConnection]: """Updates the properties of an existing private endpoint connection. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param private_endpoint_connection_name: The private endpoint connection name. This must be unique within the account. Required. :type private_endpoint_connection_name: str :param parameters: PrivateEndpointConnection properties that should be updated. Properties that are supplied will be updated, any property not supplied will be unchanged. Is either a PrivateEndpointConnection type or a IO type. Required. :type parameters: ~azure.mgmt.batch.models.PrivateEndpointConnection or IO :param if_match: The state (ETag) version of the private endpoint connection to update. This value can be omitted or set to "*" to apply the operation unconditionally. Default value is None. :type if_match: str :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. Default value is None. :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of AsyncLROPoller that returns either PrivateEndpointConnection or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.batch.models.PrivateEndpointConnection] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.PrivateEndpointConnection] = kwargs.pop("cls", None) polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) cont_token: Optional[str] = kwargs.pop("continuation_token", None) if cont_token is None: raw_result = await self._update_initial( resource_group_name=resource_group_name, account_name=account_name, private_endpoint_connection_name=private_endpoint_connection_name, parameters=parameters, if_match=if_match, api_version=api_version, content_type=content_type, cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): deserialized = self._deserialize("PrivateEndpointConnection", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized if polling is True: polling_method: AsyncPollingMethod = cast( AsyncPollingMethod, AsyncARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs), ) elif polling is False: polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) else: polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore begin_update.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/privateEndpointConnections/{privateEndpointConnectionName}" } async def _delete_initial( # pylint: disable=inconsistent-return-statements self, resource_group_name: str, account_name: str, private_endpoint_connection_name: str, **kwargs: Any ) -> None: error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[None] = kwargs.pop("cls", None) request = build_delete_request( resource_group_name=resource_group_name, account_name=account_name, private_endpoint_connection_name=private_endpoint_connection_name, subscription_id=self._config.subscription_id, api_version=api_version, template_url=self._delete_initial.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [202, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) response_headers = {} if response.status_code == 202: response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) if cls: return cls(pipeline_response, None, response_headers) _delete_initial.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/privateEndpointConnections/{privateEndpointConnectionName}" } @distributed_trace_async async def begin_delete( self, resource_group_name: str, account_name: str, private_endpoint_connection_name: str, **kwargs: Any ) -> AsyncLROPoller[None]: """Deletes the specified private endpoint connection. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param private_endpoint_connection_name: The private endpoint connection name. This must be unique within the account. Required. :type private_endpoint_connection_name: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[None] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[None] = kwargs.pop("cls", None) polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) cont_token: Optional[str] = kwargs.pop("continuation_token", None) if cont_token is None: raw_result = await self._delete_initial( # type: ignore resource_group_name=resource_group_name, account_name=account_name, private_endpoint_connection_name=private_endpoint_connection_name, api_version=api_version, cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) if polling is True: polling_method: AsyncPollingMethod = cast( AsyncPollingMethod, AsyncARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs), ) elif polling is False: polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) else: polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore begin_delete.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/privateEndpointConnections/{privateEndpointConnectionName}" }
azure-mgmt-batch
/azure_mgmt_batch-17.1.0-py3-none-any.whl/azure/mgmt/batch/aio/operations/_private_endpoint_connection_operations.py
_private_endpoint_connection_operations.py
from io import IOBase from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload import urllib.parse from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, map_error, ) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling from ... import models as _models from ..._vendor import _convert_request from ...operations._private_endpoint_connection_operations import ( build_delete_request, build_get_request, build_list_by_batch_account_request, build_update_request, ) T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] class PrivateEndpointConnectionOperations: """ .. warning:: **DO NOT** instantiate this class directly. Instead, you should access the following operations through :class:`~azure.mgmt.batch.aio.BatchManagementClient`'s :attr:`private_endpoint_connection` attribute. """ models = _models def __init__(self, *args, **kwargs) -> None: input_args = list(args) self._client = input_args.pop(0) if input_args else kwargs.pop("client") self._config = input_args.pop(0) if input_args else kwargs.pop("config") self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace def list_by_batch_account( self, resource_group_name: str, account_name: str, maxresults: Optional[int] = None, **kwargs: Any ) -> AsyncIterable["_models.PrivateEndpointConnection"]: """Lists all of the private endpoint connections in the specified account. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param maxresults: The maximum number of items to return in the response. Default value is None. :type maxresults: int :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either PrivateEndpointConnection or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.batch.models.PrivateEndpointConnection] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.ListPrivateEndpointConnectionsResult] = kwargs.pop("cls", None) error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_by_batch_account_request( resource_group_name=resource_group_name, account_name=account_name, subscription_id=self._config.subscription_id, maxresults=maxresults, api_version=api_version, template_url=self.list_by_batch_account.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) else: # make call to next link with the client's api-version _parsed_next_link = urllib.parse.urlparse(next_link) _next_request_params = case_insensitive_dict( { key: [urllib.parse.quote(v) for v in value] for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) _next_request_params["api-version"] = self._config.api_version request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) request.url = self._client.format_url(request.url) request.method = "GET" return request async def extract_data(pipeline_response): deserialized = self._deserialize("ListPrivateEndpointConnectionsResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) # type: ignore return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged(get_next, extract_data) list_by_batch_account.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/privateEndpointConnections" } @distributed_trace_async async def get( self, resource_group_name: str, account_name: str, private_endpoint_connection_name: str, **kwargs: Any ) -> _models.PrivateEndpointConnection: """Gets information about the specified private endpoint connection. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param private_endpoint_connection_name: The private endpoint connection name. This must be unique within the account. Required. :type private_endpoint_connection_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: PrivateEndpointConnection or the result of cls(response) :rtype: ~azure.mgmt.batch.models.PrivateEndpointConnection :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.PrivateEndpointConnection] = kwargs.pop("cls", None) request = build_get_request( resource_group_name=resource_group_name, account_name=account_name, private_endpoint_connection_name=private_endpoint_connection_name, subscription_id=self._config.subscription_id, api_version=api_version, template_url=self.get.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize("PrivateEndpointConnection", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/privateEndpointConnections/{privateEndpointConnectionName}" } async def _update_initial( self, resource_group_name: str, account_name: str, private_endpoint_connection_name: str, parameters: Union[_models.PrivateEndpointConnection, IO], if_match: Optional[str] = None, **kwargs: Any ) -> Optional[_models.PrivateEndpointConnection]: error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[Optional[_models.PrivateEndpointConnection]] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None if isinstance(parameters, (IOBase, bytes)): _content = parameters else: _json = self._serialize.body(parameters, "PrivateEndpointConnection") request = build_update_request( resource_group_name=resource_group_name, account_name=account_name, private_endpoint_connection_name=private_endpoint_connection_name, subscription_id=self._config.subscription_id, if_match=if_match, api_version=api_version, content_type=content_type, json=_json, content=_content, template_url=self._update_initial.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = None response_headers = {} if response.status_code == 200: deserialized = self._deserialize("PrivateEndpointConnection", pipeline_response) if response.status_code == 202: response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) if cls: return cls(pipeline_response, deserialized, response_headers) return deserialized _update_initial.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/privateEndpointConnections/{privateEndpointConnectionName}" } @overload async def begin_update( self, resource_group_name: str, account_name: str, private_endpoint_connection_name: str, parameters: _models.PrivateEndpointConnection, if_match: Optional[str] = None, *, content_type: str = "application/json", **kwargs: Any ) -> AsyncLROPoller[_models.PrivateEndpointConnection]: """Updates the properties of an existing private endpoint connection. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param private_endpoint_connection_name: The private endpoint connection name. This must be unique within the account. Required. :type private_endpoint_connection_name: str :param parameters: PrivateEndpointConnection properties that should be updated. Properties that are supplied will be updated, any property not supplied will be unchanged. Required. :type parameters: ~azure.mgmt.batch.models.PrivateEndpointConnection :param if_match: The state (ETag) version of the private endpoint connection to update. This value can be omitted or set to "*" to apply the operation unconditionally. Default value is None. :type if_match: str :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of AsyncLROPoller that returns either PrivateEndpointConnection or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.batch.models.PrivateEndpointConnection] :raises ~azure.core.exceptions.HttpResponseError: """ @overload async def begin_update( self, resource_group_name: str, account_name: str, private_endpoint_connection_name: str, parameters: IO, if_match: Optional[str] = None, *, content_type: str = "application/json", **kwargs: Any ) -> AsyncLROPoller[_models.PrivateEndpointConnection]: """Updates the properties of an existing private endpoint connection. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param private_endpoint_connection_name: The private endpoint connection name. This must be unique within the account. Required. :type private_endpoint_connection_name: str :param parameters: PrivateEndpointConnection properties that should be updated. Properties that are supplied will be updated, any property not supplied will be unchanged. Required. :type parameters: IO :param if_match: The state (ETag) version of the private endpoint connection to update. This value can be omitted or set to "*" to apply the operation unconditionally. Default value is None. :type if_match: str :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of AsyncLROPoller that returns either PrivateEndpointConnection or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.batch.models.PrivateEndpointConnection] :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace_async async def begin_update( self, resource_group_name: str, account_name: str, private_endpoint_connection_name: str, parameters: Union[_models.PrivateEndpointConnection, IO], if_match: Optional[str] = None, **kwargs: Any ) -> AsyncLROPoller[_models.PrivateEndpointConnection]: """Updates the properties of an existing private endpoint connection. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param private_endpoint_connection_name: The private endpoint connection name. This must be unique within the account. Required. :type private_endpoint_connection_name: str :param parameters: PrivateEndpointConnection properties that should be updated. Properties that are supplied will be updated, any property not supplied will be unchanged. Is either a PrivateEndpointConnection type or a IO type. Required. :type parameters: ~azure.mgmt.batch.models.PrivateEndpointConnection or IO :param if_match: The state (ETag) version of the private endpoint connection to update. This value can be omitted or set to "*" to apply the operation unconditionally. Default value is None. :type if_match: str :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. Default value is None. :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of AsyncLROPoller that returns either PrivateEndpointConnection or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.batch.models.PrivateEndpointConnection] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.PrivateEndpointConnection] = kwargs.pop("cls", None) polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) cont_token: Optional[str] = kwargs.pop("continuation_token", None) if cont_token is None: raw_result = await self._update_initial( resource_group_name=resource_group_name, account_name=account_name, private_endpoint_connection_name=private_endpoint_connection_name, parameters=parameters, if_match=if_match, api_version=api_version, content_type=content_type, cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): deserialized = self._deserialize("PrivateEndpointConnection", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized if polling is True: polling_method: AsyncPollingMethod = cast( AsyncPollingMethod, AsyncARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs), ) elif polling is False: polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) else: polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore begin_update.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/privateEndpointConnections/{privateEndpointConnectionName}" } async def _delete_initial( # pylint: disable=inconsistent-return-statements self, resource_group_name: str, account_name: str, private_endpoint_connection_name: str, **kwargs: Any ) -> None: error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[None] = kwargs.pop("cls", None) request = build_delete_request( resource_group_name=resource_group_name, account_name=account_name, private_endpoint_connection_name=private_endpoint_connection_name, subscription_id=self._config.subscription_id, api_version=api_version, template_url=self._delete_initial.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [202, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) response_headers = {} if response.status_code == 202: response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) if cls: return cls(pipeline_response, None, response_headers) _delete_initial.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/privateEndpointConnections/{privateEndpointConnectionName}" } @distributed_trace_async async def begin_delete( self, resource_group_name: str, account_name: str, private_endpoint_connection_name: str, **kwargs: Any ) -> AsyncLROPoller[None]: """Deletes the specified private endpoint connection. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param private_endpoint_connection_name: The private endpoint connection name. This must be unique within the account. Required. :type private_endpoint_connection_name: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[None] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[None] = kwargs.pop("cls", None) polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) cont_token: Optional[str] = kwargs.pop("continuation_token", None) if cont_token is None: raw_result = await self._delete_initial( # type: ignore resource_group_name=resource_group_name, account_name=account_name, private_endpoint_connection_name=private_endpoint_connection_name, api_version=api_version, cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) if polling is True: polling_method: AsyncPollingMethod = cast( AsyncPollingMethod, AsyncARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs), ) elif polling is False: polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) else: polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore begin_delete.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/privateEndpointConnections/{privateEndpointConnectionName}" }
0.896455
0.075927
from io import IOBase from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, overload import urllib.parse from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, map_error, ) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models from ..._vendor import _convert_request from ...operations._location_operations import ( build_check_name_availability_request, build_get_quotas_request, build_list_supported_cloud_service_skus_request, build_list_supported_virtual_machine_skus_request, ) T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] class LocationOperations: """ .. warning:: **DO NOT** instantiate this class directly. Instead, you should access the following operations through :class:`~azure.mgmt.batch.aio.BatchManagementClient`'s :attr:`location` attribute. """ models = _models def __init__(self, *args, **kwargs) -> None: input_args = list(args) self._client = input_args.pop(0) if input_args else kwargs.pop("client") self._config = input_args.pop(0) if input_args else kwargs.pop("config") self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace_async async def get_quotas(self, location_name: str, **kwargs: Any) -> _models.BatchLocationQuota: """Gets the Batch service quotas for the specified subscription at the given location. :param location_name: The region for which to retrieve Batch service quotas. Required. :type location_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: BatchLocationQuota or the result of cls(response) :rtype: ~azure.mgmt.batch.models.BatchLocationQuota :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.BatchLocationQuota] = kwargs.pop("cls", None) request = build_get_quotas_request( location_name=location_name, subscription_id=self._config.subscription_id, api_version=api_version, template_url=self.get_quotas.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize("BatchLocationQuota", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get_quotas.metadata = { "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Batch/locations/{locationName}/quotas" } @distributed_trace def list_supported_virtual_machine_skus( self, location_name: str, maxresults: Optional[int] = None, filter: Optional[str] = None, **kwargs: Any ) -> AsyncIterable["_models.SupportedSku"]: """Gets the list of Batch supported Virtual Machine VM sizes available at the given location. :param location_name: The region for which to retrieve Batch service supported SKUs. Required. :type location_name: str :param maxresults: The maximum number of items to return in the response. Default value is None. :type maxresults: int :param filter: OData filter expression. Valid properties for filtering are "familyName". Default value is None. :type filter: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either SupportedSku or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.batch.models.SupportedSku] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.SupportedSkusResult] = kwargs.pop("cls", None) error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_supported_virtual_machine_skus_request( location_name=location_name, subscription_id=self._config.subscription_id, maxresults=maxresults, filter=filter, api_version=api_version, template_url=self.list_supported_virtual_machine_skus.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) else: # make call to next link with the client's api-version _parsed_next_link = urllib.parse.urlparse(next_link) _next_request_params = case_insensitive_dict( { key: [urllib.parse.quote(v) for v in value] for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) _next_request_params["api-version"] = self._config.api_version request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) request.url = self._client.format_url(request.url) request.method = "GET" return request async def extract_data(pipeline_response): deserialized = self._deserialize("SupportedSkusResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) # type: ignore return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged(get_next, extract_data) list_supported_virtual_machine_skus.metadata = { "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Batch/locations/{locationName}/virtualMachineSkus" } @distributed_trace def list_supported_cloud_service_skus( self, location_name: str, maxresults: Optional[int] = None, filter: Optional[str] = None, **kwargs: Any ) -> AsyncIterable["_models.SupportedSku"]: """Gets the list of Batch supported Cloud Service VM sizes available at the given location. :param location_name: The region for which to retrieve Batch service supported SKUs. Required. :type location_name: str :param maxresults: The maximum number of items to return in the response. Default value is None. :type maxresults: int :param filter: OData filter expression. Valid properties for filtering are "familyName". Default value is None. :type filter: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either SupportedSku or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.batch.models.SupportedSku] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.SupportedSkusResult] = kwargs.pop("cls", None) error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_supported_cloud_service_skus_request( location_name=location_name, subscription_id=self._config.subscription_id, maxresults=maxresults, filter=filter, api_version=api_version, template_url=self.list_supported_cloud_service_skus.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) else: # make call to next link with the client's api-version _parsed_next_link = urllib.parse.urlparse(next_link) _next_request_params = case_insensitive_dict( { key: [urllib.parse.quote(v) for v in value] for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) _next_request_params["api-version"] = self._config.api_version request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) request.url = self._client.format_url(request.url) request.method = "GET" return request async def extract_data(pipeline_response): deserialized = self._deserialize("SupportedSkusResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) # type: ignore return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged(get_next, extract_data) list_supported_cloud_service_skus.metadata = { "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Batch/locations/{locationName}/cloudServiceSkus" } @overload async def check_name_availability( self, location_name: str, parameters: _models.CheckNameAvailabilityParameters, *, content_type: str = "application/json", **kwargs: Any ) -> _models.CheckNameAvailabilityResult: """Checks whether the Batch account name is available in the specified region. :param location_name: The desired region for the name check. Required. :type location_name: str :param parameters: Properties needed to check the availability of a name. Required. :type parameters: ~azure.mgmt.batch.models.CheckNameAvailabilityParameters :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: CheckNameAvailabilityResult or the result of cls(response) :rtype: ~azure.mgmt.batch.models.CheckNameAvailabilityResult :raises ~azure.core.exceptions.HttpResponseError: """ @overload async def check_name_availability( self, location_name: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any ) -> _models.CheckNameAvailabilityResult: """Checks whether the Batch account name is available in the specified region. :param location_name: The desired region for the name check. Required. :type location_name: str :param parameters: Properties needed to check the availability of a name. Required. :type parameters: IO :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: CheckNameAvailabilityResult or the result of cls(response) :rtype: ~azure.mgmt.batch.models.CheckNameAvailabilityResult :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace_async async def check_name_availability( self, location_name: str, parameters: Union[_models.CheckNameAvailabilityParameters, IO], **kwargs: Any ) -> _models.CheckNameAvailabilityResult: """Checks whether the Batch account name is available in the specified region. :param location_name: The desired region for the name check. Required. :type location_name: str :param parameters: Properties needed to check the availability of a name. Is either a CheckNameAvailabilityParameters type or a IO type. Required. :type parameters: ~azure.mgmt.batch.models.CheckNameAvailabilityParameters or IO :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. Default value is None. :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: CheckNameAvailabilityResult or the result of cls(response) :rtype: ~azure.mgmt.batch.models.CheckNameAvailabilityResult :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.CheckNameAvailabilityResult] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None if isinstance(parameters, (IOBase, bytes)): _content = parameters else: _json = self._serialize.body(parameters, "CheckNameAvailabilityParameters") request = build_check_name_availability_request( location_name=location_name, subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, content=_content, template_url=self.check_name_availability.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize("CheckNameAvailabilityResult", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized check_name_availability.metadata = { "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Batch/locations/{locationName}/checkNameAvailability" }
azure-mgmt-batch
/azure_mgmt_batch-17.1.0-py3-none-any.whl/azure/mgmt/batch/aio/operations/_location_operations.py
_location_operations.py
from io import IOBase from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, overload import urllib.parse from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, map_error, ) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models from ..._vendor import _convert_request from ...operations._location_operations import ( build_check_name_availability_request, build_get_quotas_request, build_list_supported_cloud_service_skus_request, build_list_supported_virtual_machine_skus_request, ) T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] class LocationOperations: """ .. warning:: **DO NOT** instantiate this class directly. Instead, you should access the following operations through :class:`~azure.mgmt.batch.aio.BatchManagementClient`'s :attr:`location` attribute. """ models = _models def __init__(self, *args, **kwargs) -> None: input_args = list(args) self._client = input_args.pop(0) if input_args else kwargs.pop("client") self._config = input_args.pop(0) if input_args else kwargs.pop("config") self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace_async async def get_quotas(self, location_name: str, **kwargs: Any) -> _models.BatchLocationQuota: """Gets the Batch service quotas for the specified subscription at the given location. :param location_name: The region for which to retrieve Batch service quotas. Required. :type location_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: BatchLocationQuota or the result of cls(response) :rtype: ~azure.mgmt.batch.models.BatchLocationQuota :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.BatchLocationQuota] = kwargs.pop("cls", None) request = build_get_quotas_request( location_name=location_name, subscription_id=self._config.subscription_id, api_version=api_version, template_url=self.get_quotas.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize("BatchLocationQuota", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get_quotas.metadata = { "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Batch/locations/{locationName}/quotas" } @distributed_trace def list_supported_virtual_machine_skus( self, location_name: str, maxresults: Optional[int] = None, filter: Optional[str] = None, **kwargs: Any ) -> AsyncIterable["_models.SupportedSku"]: """Gets the list of Batch supported Virtual Machine VM sizes available at the given location. :param location_name: The region for which to retrieve Batch service supported SKUs. Required. :type location_name: str :param maxresults: The maximum number of items to return in the response. Default value is None. :type maxresults: int :param filter: OData filter expression. Valid properties for filtering are "familyName". Default value is None. :type filter: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either SupportedSku or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.batch.models.SupportedSku] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.SupportedSkusResult] = kwargs.pop("cls", None) error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_supported_virtual_machine_skus_request( location_name=location_name, subscription_id=self._config.subscription_id, maxresults=maxresults, filter=filter, api_version=api_version, template_url=self.list_supported_virtual_machine_skus.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) else: # make call to next link with the client's api-version _parsed_next_link = urllib.parse.urlparse(next_link) _next_request_params = case_insensitive_dict( { key: [urllib.parse.quote(v) for v in value] for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) _next_request_params["api-version"] = self._config.api_version request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) request.url = self._client.format_url(request.url) request.method = "GET" return request async def extract_data(pipeline_response): deserialized = self._deserialize("SupportedSkusResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) # type: ignore return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged(get_next, extract_data) list_supported_virtual_machine_skus.metadata = { "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Batch/locations/{locationName}/virtualMachineSkus" } @distributed_trace def list_supported_cloud_service_skus( self, location_name: str, maxresults: Optional[int] = None, filter: Optional[str] = None, **kwargs: Any ) -> AsyncIterable["_models.SupportedSku"]: """Gets the list of Batch supported Cloud Service VM sizes available at the given location. :param location_name: The region for which to retrieve Batch service supported SKUs. Required. :type location_name: str :param maxresults: The maximum number of items to return in the response. Default value is None. :type maxresults: int :param filter: OData filter expression. Valid properties for filtering are "familyName". Default value is None. :type filter: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either SupportedSku or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.batch.models.SupportedSku] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.SupportedSkusResult] = kwargs.pop("cls", None) error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_supported_cloud_service_skus_request( location_name=location_name, subscription_id=self._config.subscription_id, maxresults=maxresults, filter=filter, api_version=api_version, template_url=self.list_supported_cloud_service_skus.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) else: # make call to next link with the client's api-version _parsed_next_link = urllib.parse.urlparse(next_link) _next_request_params = case_insensitive_dict( { key: [urllib.parse.quote(v) for v in value] for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) _next_request_params["api-version"] = self._config.api_version request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) request.url = self._client.format_url(request.url) request.method = "GET" return request async def extract_data(pipeline_response): deserialized = self._deserialize("SupportedSkusResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) # type: ignore return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged(get_next, extract_data) list_supported_cloud_service_skus.metadata = { "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Batch/locations/{locationName}/cloudServiceSkus" } @overload async def check_name_availability( self, location_name: str, parameters: _models.CheckNameAvailabilityParameters, *, content_type: str = "application/json", **kwargs: Any ) -> _models.CheckNameAvailabilityResult: """Checks whether the Batch account name is available in the specified region. :param location_name: The desired region for the name check. Required. :type location_name: str :param parameters: Properties needed to check the availability of a name. Required. :type parameters: ~azure.mgmt.batch.models.CheckNameAvailabilityParameters :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: CheckNameAvailabilityResult or the result of cls(response) :rtype: ~azure.mgmt.batch.models.CheckNameAvailabilityResult :raises ~azure.core.exceptions.HttpResponseError: """ @overload async def check_name_availability( self, location_name: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any ) -> _models.CheckNameAvailabilityResult: """Checks whether the Batch account name is available in the specified region. :param location_name: The desired region for the name check. Required. :type location_name: str :param parameters: Properties needed to check the availability of a name. Required. :type parameters: IO :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: CheckNameAvailabilityResult or the result of cls(response) :rtype: ~azure.mgmt.batch.models.CheckNameAvailabilityResult :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace_async async def check_name_availability( self, location_name: str, parameters: Union[_models.CheckNameAvailabilityParameters, IO], **kwargs: Any ) -> _models.CheckNameAvailabilityResult: """Checks whether the Batch account name is available in the specified region. :param location_name: The desired region for the name check. Required. :type location_name: str :param parameters: Properties needed to check the availability of a name. Is either a CheckNameAvailabilityParameters type or a IO type. Required. :type parameters: ~azure.mgmt.batch.models.CheckNameAvailabilityParameters or IO :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. Default value is None. :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: CheckNameAvailabilityResult or the result of cls(response) :rtype: ~azure.mgmt.batch.models.CheckNameAvailabilityResult :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.CheckNameAvailabilityResult] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None if isinstance(parameters, (IOBase, bytes)): _content = parameters else: _json = self._serialize.body(parameters, "CheckNameAvailabilityParameters") request = build_check_name_availability_request( location_name=location_name, subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, content=_content, template_url=self.check_name_availability.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize("CheckNameAvailabilityResult", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized check_name_availability.metadata = { "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Batch/locations/{locationName}/checkNameAvailability" }
0.902231
0.090816
from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar import urllib.parse from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, map_error, ) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models from ..._vendor import _convert_request from ...operations._operations import build_list_request T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] class Operations: """ .. warning:: **DO NOT** instantiate this class directly. Instead, you should access the following operations through :class:`~azure.mgmt.batch.aio.BatchManagementClient`'s :attr:`operations` attribute. """ models = _models def __init__(self, *args, **kwargs) -> None: input_args = list(args) self._client = input_args.pop(0) if input_args else kwargs.pop("client") self._config = input_args.pop(0) if input_args else kwargs.pop("config") self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace def list(self, **kwargs: Any) -> AsyncIterable["_models.Operation"]: """Lists available operations for the Microsoft.Batch provider. :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either Operation or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.batch.models.Operation] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.OperationListResult] = kwargs.pop("cls", None) error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_request( api_version=api_version, template_url=self.list.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) else: # make call to next link with the client's api-version _parsed_next_link = urllib.parse.urlparse(next_link) _next_request_params = case_insensitive_dict( { key: [urllib.parse.quote(v) for v in value] for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) _next_request_params["api-version"] = self._config.api_version request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) request.url = self._client.format_url(request.url) request.method = "GET" return request async def extract_data(pipeline_response): deserialized = self._deserialize("OperationListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) # type: ignore return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged(get_next, extract_data) list.metadata = {"url": "/providers/Microsoft.Batch/operations"}
azure-mgmt-batch
/azure_mgmt_batch-17.1.0-py3-none-any.whl/azure/mgmt/batch/aio/operations/_operations.py
_operations.py
from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar import urllib.parse from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, map_error, ) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models from ..._vendor import _convert_request from ...operations._operations import build_list_request T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] class Operations: """ .. warning:: **DO NOT** instantiate this class directly. Instead, you should access the following operations through :class:`~azure.mgmt.batch.aio.BatchManagementClient`'s :attr:`operations` attribute. """ models = _models def __init__(self, *args, **kwargs) -> None: input_args = list(args) self._client = input_args.pop(0) if input_args else kwargs.pop("client") self._config = input_args.pop(0) if input_args else kwargs.pop("config") self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace def list(self, **kwargs: Any) -> AsyncIterable["_models.Operation"]: """Lists available operations for the Microsoft.Batch provider. :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either Operation or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.batch.models.Operation] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.OperationListResult] = kwargs.pop("cls", None) error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_request( api_version=api_version, template_url=self.list.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) else: # make call to next link with the client's api-version _parsed_next_link = urllib.parse.urlparse(next_link) _next_request_params = case_insensitive_dict( { key: [urllib.parse.quote(v) for v in value] for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) _next_request_params["api-version"] = self._config.api_version request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) request.url = self._client.format_url(request.url) request.method = "GET" return request async def extract_data(pipeline_response): deserialized = self._deserialize("OperationListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) # type: ignore return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged(get_next, extract_data) list.metadata = {"url": "/providers/Microsoft.Batch/operations"}
0.864554
0.091992
from io import IOBase from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload import urllib.parse from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, map_error, ) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling from ... import models as _models from ..._vendor import _convert_request from ...operations._certificate_operations import ( build_cancel_deletion_request, build_create_request, build_delete_request, build_get_request, build_list_by_batch_account_request, build_update_request, ) T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] class CertificateOperations: """ .. warning:: **DO NOT** instantiate this class directly. Instead, you should access the following operations through :class:`~azure.mgmt.batch.aio.BatchManagementClient`'s :attr:`certificate` attribute. """ models = _models def __init__(self, *args, **kwargs) -> None: input_args = list(args) self._client = input_args.pop(0) if input_args else kwargs.pop("client") self._config = input_args.pop(0) if input_args else kwargs.pop("config") self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace def list_by_batch_account( self, resource_group_name: str, account_name: str, maxresults: Optional[int] = None, select: Optional[str] = None, filter: Optional[str] = None, **kwargs: Any ) -> AsyncIterable["_models.Certificate"]: """Lists all of the certificates in the specified account. Warning: This operation is deprecated and will be removed after February, 2024. Please use the `Azure KeyVault Extension <https://learn.microsoft.com/azure/batch/batch-certificate-migration-guide>`_ instead. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param maxresults: The maximum number of items to return in the response. Default value is None. :type maxresults: int :param select: Comma separated list of properties that should be returned. e.g. "properties/provisioningState". Only top level properties under properties/ are valid for selection. Default value is None. :type select: str :param filter: OData filter expression. Valid properties for filtering are "properties/provisioningState", "properties/provisioningStateTransitionTime", "name". Default value is None. :type filter: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either Certificate or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.batch.models.Certificate] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.ListCertificatesResult] = kwargs.pop("cls", None) error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_by_batch_account_request( resource_group_name=resource_group_name, account_name=account_name, subscription_id=self._config.subscription_id, maxresults=maxresults, select=select, filter=filter, api_version=api_version, template_url=self.list_by_batch_account.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) else: # make call to next link with the client's api-version _parsed_next_link = urllib.parse.urlparse(next_link) _next_request_params = case_insensitive_dict( { key: [urllib.parse.quote(v) for v in value] for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) _next_request_params["api-version"] = self._config.api_version request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) request.url = self._client.format_url(request.url) request.method = "GET" return request async def extract_data(pipeline_response): deserialized = self._deserialize("ListCertificatesResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) # type: ignore return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged(get_next, extract_data) list_by_batch_account.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/certificates" } @overload async def create( self, resource_group_name: str, account_name: str, certificate_name: str, parameters: _models.CertificateCreateOrUpdateParameters, if_match: Optional[str] = None, if_none_match: Optional[str] = None, *, content_type: str = "application/json", **kwargs: Any ) -> _models.Certificate: """Creates a new certificate inside the specified account. Warning: This operation is deprecated and will be removed after February, 2024. Please use the `Azure KeyVault Extension <https://learn.microsoft.com/azure/batch/batch-certificate-migration-guide>`_ instead. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param certificate_name: The identifier for the certificate. This must be made up of algorithm and thumbprint separated by a dash, and must match the certificate data in the request. For example SHA1-a3d1c5. Required. :type certificate_name: str :param parameters: Additional parameters for certificate creation. Required. :type parameters: ~azure.mgmt.batch.models.CertificateCreateOrUpdateParameters :param if_match: The entity state (ETag) version of the certificate to update. A value of "*" can be used to apply the operation only if the certificate already exists. If omitted, this operation will always be applied. Default value is None. :type if_match: str :param if_none_match: Set to '*' to allow a new certificate to be created, but to prevent updating an existing certificate. Other values will be ignored. Default value is None. :type if_none_match: str :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Certificate or the result of cls(response) :rtype: ~azure.mgmt.batch.models.Certificate :raises ~azure.core.exceptions.HttpResponseError: """ @overload async def create( self, resource_group_name: str, account_name: str, certificate_name: str, parameters: IO, if_match: Optional[str] = None, if_none_match: Optional[str] = None, *, content_type: str = "application/json", **kwargs: Any ) -> _models.Certificate: """Creates a new certificate inside the specified account. Warning: This operation is deprecated and will be removed after February, 2024. Please use the `Azure KeyVault Extension <https://learn.microsoft.com/azure/batch/batch-certificate-migration-guide>`_ instead. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param certificate_name: The identifier for the certificate. This must be made up of algorithm and thumbprint separated by a dash, and must match the certificate data in the request. For example SHA1-a3d1c5. Required. :type certificate_name: str :param parameters: Additional parameters for certificate creation. Required. :type parameters: IO :param if_match: The entity state (ETag) version of the certificate to update. A value of "*" can be used to apply the operation only if the certificate already exists. If omitted, this operation will always be applied. Default value is None. :type if_match: str :param if_none_match: Set to '*' to allow a new certificate to be created, but to prevent updating an existing certificate. Other values will be ignored. Default value is None. :type if_none_match: str :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Certificate or the result of cls(response) :rtype: ~azure.mgmt.batch.models.Certificate :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace_async async def create( self, resource_group_name: str, account_name: str, certificate_name: str, parameters: Union[_models.CertificateCreateOrUpdateParameters, IO], if_match: Optional[str] = None, if_none_match: Optional[str] = None, **kwargs: Any ) -> _models.Certificate: """Creates a new certificate inside the specified account. Warning: This operation is deprecated and will be removed after February, 2024. Please use the `Azure KeyVault Extension <https://learn.microsoft.com/azure/batch/batch-certificate-migration-guide>`_ instead. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param certificate_name: The identifier for the certificate. This must be made up of algorithm and thumbprint separated by a dash, and must match the certificate data in the request. For example SHA1-a3d1c5. Required. :type certificate_name: str :param parameters: Additional parameters for certificate creation. Is either a CertificateCreateOrUpdateParameters type or a IO type. Required. :type parameters: ~azure.mgmt.batch.models.CertificateCreateOrUpdateParameters or IO :param if_match: The entity state (ETag) version of the certificate to update. A value of "*" can be used to apply the operation only if the certificate already exists. If omitted, this operation will always be applied. Default value is None. :type if_match: str :param if_none_match: Set to '*' to allow a new certificate to be created, but to prevent updating an existing certificate. Other values will be ignored. Default value is None. :type if_none_match: str :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. Default value is None. :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Certificate or the result of cls(response) :rtype: ~azure.mgmt.batch.models.Certificate :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.Certificate] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None if isinstance(parameters, (IOBase, bytes)): _content = parameters else: _json = self._serialize.body(parameters, "CertificateCreateOrUpdateParameters") request = build_create_request( resource_group_name=resource_group_name, account_name=account_name, certificate_name=certificate_name, subscription_id=self._config.subscription_id, if_match=if_match, if_none_match=if_none_match, api_version=api_version, content_type=content_type, json=_json, content=_content, template_url=self.create.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) response_headers = {} response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) deserialized = self._deserialize("Certificate", pipeline_response) if cls: return cls(pipeline_response, deserialized, response_headers) return deserialized create.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/certificates/{certificateName}" } @overload async def update( self, resource_group_name: str, account_name: str, certificate_name: str, parameters: _models.CertificateCreateOrUpdateParameters, if_match: Optional[str] = None, *, content_type: str = "application/json", **kwargs: Any ) -> _models.Certificate: """Updates the properties of an existing certificate. Warning: This operation is deprecated and will be removed after February, 2024. Please use the `Azure KeyVault Extension <https://learn.microsoft.com/azure/batch/batch-certificate-migration-guide>`_ instead. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param certificate_name: The identifier for the certificate. This must be made up of algorithm and thumbprint separated by a dash, and must match the certificate data in the request. For example SHA1-a3d1c5. Required. :type certificate_name: str :param parameters: Certificate entity to update. Required. :type parameters: ~azure.mgmt.batch.models.CertificateCreateOrUpdateParameters :param if_match: The entity state (ETag) version of the certificate to update. This value can be omitted or set to "*" to apply the operation unconditionally. Default value is None. :type if_match: str :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Certificate or the result of cls(response) :rtype: ~azure.mgmt.batch.models.Certificate :raises ~azure.core.exceptions.HttpResponseError: """ @overload async def update( self, resource_group_name: str, account_name: str, certificate_name: str, parameters: IO, if_match: Optional[str] = None, *, content_type: str = "application/json", **kwargs: Any ) -> _models.Certificate: """Updates the properties of an existing certificate. Warning: This operation is deprecated and will be removed after February, 2024. Please use the `Azure KeyVault Extension <https://learn.microsoft.com/azure/batch/batch-certificate-migration-guide>`_ instead. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param certificate_name: The identifier for the certificate. This must be made up of algorithm and thumbprint separated by a dash, and must match the certificate data in the request. For example SHA1-a3d1c5. Required. :type certificate_name: str :param parameters: Certificate entity to update. Required. :type parameters: IO :param if_match: The entity state (ETag) version of the certificate to update. This value can be omitted or set to "*" to apply the operation unconditionally. Default value is None. :type if_match: str :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Certificate or the result of cls(response) :rtype: ~azure.mgmt.batch.models.Certificate :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace_async async def update( self, resource_group_name: str, account_name: str, certificate_name: str, parameters: Union[_models.CertificateCreateOrUpdateParameters, IO], if_match: Optional[str] = None, **kwargs: Any ) -> _models.Certificate: """Updates the properties of an existing certificate. Warning: This operation is deprecated and will be removed after February, 2024. Please use the `Azure KeyVault Extension <https://learn.microsoft.com/azure/batch/batch-certificate-migration-guide>`_ instead. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param certificate_name: The identifier for the certificate. This must be made up of algorithm and thumbprint separated by a dash, and must match the certificate data in the request. For example SHA1-a3d1c5. Required. :type certificate_name: str :param parameters: Certificate entity to update. Is either a CertificateCreateOrUpdateParameters type or a IO type. Required. :type parameters: ~azure.mgmt.batch.models.CertificateCreateOrUpdateParameters or IO :param if_match: The entity state (ETag) version of the certificate to update. This value can be omitted or set to "*" to apply the operation unconditionally. Default value is None. :type if_match: str :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. Default value is None. :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Certificate or the result of cls(response) :rtype: ~azure.mgmt.batch.models.Certificate :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.Certificate] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None if isinstance(parameters, (IOBase, bytes)): _content = parameters else: _json = self._serialize.body(parameters, "CertificateCreateOrUpdateParameters") request = build_update_request( resource_group_name=resource_group_name, account_name=account_name, certificate_name=certificate_name, subscription_id=self._config.subscription_id, if_match=if_match, api_version=api_version, content_type=content_type, json=_json, content=_content, template_url=self.update.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) response_headers = {} response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) deserialized = self._deserialize("Certificate", pipeline_response) if cls: return cls(pipeline_response, deserialized, response_headers) return deserialized update.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/certificates/{certificateName}" } async def _delete_initial( # pylint: disable=inconsistent-return-statements self, resource_group_name: str, account_name: str, certificate_name: str, **kwargs: Any ) -> None: error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[None] = kwargs.pop("cls", None) request = build_delete_request( resource_group_name=resource_group_name, account_name=account_name, certificate_name=certificate_name, subscription_id=self._config.subscription_id, api_version=api_version, template_url=self._delete_initial.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) response_headers = {} if response.status_code == 202: response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) if cls: return cls(pipeline_response, None, response_headers) _delete_initial.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/certificates/{certificateName}" } @distributed_trace_async async def begin_delete( self, resource_group_name: str, account_name: str, certificate_name: str, **kwargs: Any ) -> AsyncLROPoller[None]: """Deletes the specified certificate. Warning: This operation is deprecated and will be removed after February, 2024. Please use the `Azure KeyVault Extension <https://learn.microsoft.com/azure/batch/batch-certificate-migration-guide>`_ instead. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param certificate_name: The identifier for the certificate. This must be made up of algorithm and thumbprint separated by a dash, and must match the certificate data in the request. For example SHA1-a3d1c5. Required. :type certificate_name: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[None] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[None] = kwargs.pop("cls", None) polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) cont_token: Optional[str] = kwargs.pop("continuation_token", None) if cont_token is None: raw_result = await self._delete_initial( # type: ignore resource_group_name=resource_group_name, account_name=account_name, certificate_name=certificate_name, api_version=api_version, cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) if polling is True: polling_method: AsyncPollingMethod = cast( AsyncPollingMethod, AsyncARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) ) elif polling is False: polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) else: polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore begin_delete.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/certificates/{certificateName}" } @distributed_trace_async async def get( self, resource_group_name: str, account_name: str, certificate_name: str, **kwargs: Any ) -> _models.Certificate: """Gets information about the specified certificate. Warning: This operation is deprecated and will be removed after February, 2024. Please use the `Azure KeyVault Extension <https://learn.microsoft.com/azure/batch/batch-certificate-migration-guide>`_ instead. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param certificate_name: The identifier for the certificate. This must be made up of algorithm and thumbprint separated by a dash, and must match the certificate data in the request. For example SHA1-a3d1c5. Required. :type certificate_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Certificate or the result of cls(response) :rtype: ~azure.mgmt.batch.models.Certificate :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.Certificate] = kwargs.pop("cls", None) request = build_get_request( resource_group_name=resource_group_name, account_name=account_name, certificate_name=certificate_name, subscription_id=self._config.subscription_id, api_version=api_version, template_url=self.get.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) response_headers = {} response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) deserialized = self._deserialize("Certificate", pipeline_response) if cls: return cls(pipeline_response, deserialized, response_headers) return deserialized get.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/certificates/{certificateName}" } @distributed_trace_async async def cancel_deletion( self, resource_group_name: str, account_name: str, certificate_name: str, **kwargs: Any ) -> _models.Certificate: """Cancels a failed deletion of a certificate from the specified account. If you try to delete a certificate that is being used by a pool or compute node, the status of the certificate changes to deleteFailed. If you decide that you want to continue using the certificate, you can use this operation to set the status of the certificate back to active. If you intend to delete the certificate, you do not need to run this operation after the deletion failed. You must make sure that the certificate is not being used by any resources, and then you can try again to delete the certificate. Warning: This operation is deprecated and will be removed after February, 2024. Please use the `Azure KeyVault Extension <https://learn.microsoft.com/azure/batch/batch-certificate-migration-guide>`_ instead. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param certificate_name: The identifier for the certificate. This must be made up of algorithm and thumbprint separated by a dash, and must match the certificate data in the request. For example SHA1-a3d1c5. Required. :type certificate_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Certificate or the result of cls(response) :rtype: ~azure.mgmt.batch.models.Certificate :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.Certificate] = kwargs.pop("cls", None) request = build_cancel_deletion_request( resource_group_name=resource_group_name, account_name=account_name, certificate_name=certificate_name, subscription_id=self._config.subscription_id, api_version=api_version, template_url=self.cancel_deletion.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) response_headers = {} response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) deserialized = self._deserialize("Certificate", pipeline_response) if cls: return cls(pipeline_response, deserialized, response_headers) return deserialized cancel_deletion.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/certificates/{certificateName}/cancelDelete" }
azure-mgmt-batch
/azure_mgmt_batch-17.1.0-py3-none-any.whl/azure/mgmt/batch/aio/operations/_certificate_operations.py
_certificate_operations.py
from io import IOBase from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload import urllib.parse from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, map_error, ) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling from ... import models as _models from ..._vendor import _convert_request from ...operations._certificate_operations import ( build_cancel_deletion_request, build_create_request, build_delete_request, build_get_request, build_list_by_batch_account_request, build_update_request, ) T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] class CertificateOperations: """ .. warning:: **DO NOT** instantiate this class directly. Instead, you should access the following operations through :class:`~azure.mgmt.batch.aio.BatchManagementClient`'s :attr:`certificate` attribute. """ models = _models def __init__(self, *args, **kwargs) -> None: input_args = list(args) self._client = input_args.pop(0) if input_args else kwargs.pop("client") self._config = input_args.pop(0) if input_args else kwargs.pop("config") self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace def list_by_batch_account( self, resource_group_name: str, account_name: str, maxresults: Optional[int] = None, select: Optional[str] = None, filter: Optional[str] = None, **kwargs: Any ) -> AsyncIterable["_models.Certificate"]: """Lists all of the certificates in the specified account. Warning: This operation is deprecated and will be removed after February, 2024. Please use the `Azure KeyVault Extension <https://learn.microsoft.com/azure/batch/batch-certificate-migration-guide>`_ instead. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param maxresults: The maximum number of items to return in the response. Default value is None. :type maxresults: int :param select: Comma separated list of properties that should be returned. e.g. "properties/provisioningState". Only top level properties under properties/ are valid for selection. Default value is None. :type select: str :param filter: OData filter expression. Valid properties for filtering are "properties/provisioningState", "properties/provisioningStateTransitionTime", "name". Default value is None. :type filter: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either Certificate or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.batch.models.Certificate] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.ListCertificatesResult] = kwargs.pop("cls", None) error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_by_batch_account_request( resource_group_name=resource_group_name, account_name=account_name, subscription_id=self._config.subscription_id, maxresults=maxresults, select=select, filter=filter, api_version=api_version, template_url=self.list_by_batch_account.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) else: # make call to next link with the client's api-version _parsed_next_link = urllib.parse.urlparse(next_link) _next_request_params = case_insensitive_dict( { key: [urllib.parse.quote(v) for v in value] for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) _next_request_params["api-version"] = self._config.api_version request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) request.url = self._client.format_url(request.url) request.method = "GET" return request async def extract_data(pipeline_response): deserialized = self._deserialize("ListCertificatesResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) # type: ignore return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged(get_next, extract_data) list_by_batch_account.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/certificates" } @overload async def create( self, resource_group_name: str, account_name: str, certificate_name: str, parameters: _models.CertificateCreateOrUpdateParameters, if_match: Optional[str] = None, if_none_match: Optional[str] = None, *, content_type: str = "application/json", **kwargs: Any ) -> _models.Certificate: """Creates a new certificate inside the specified account. Warning: This operation is deprecated and will be removed after February, 2024. Please use the `Azure KeyVault Extension <https://learn.microsoft.com/azure/batch/batch-certificate-migration-guide>`_ instead. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param certificate_name: The identifier for the certificate. This must be made up of algorithm and thumbprint separated by a dash, and must match the certificate data in the request. For example SHA1-a3d1c5. Required. :type certificate_name: str :param parameters: Additional parameters for certificate creation. Required. :type parameters: ~azure.mgmt.batch.models.CertificateCreateOrUpdateParameters :param if_match: The entity state (ETag) version of the certificate to update. A value of "*" can be used to apply the operation only if the certificate already exists. If omitted, this operation will always be applied. Default value is None. :type if_match: str :param if_none_match: Set to '*' to allow a new certificate to be created, but to prevent updating an existing certificate. Other values will be ignored. Default value is None. :type if_none_match: str :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Certificate or the result of cls(response) :rtype: ~azure.mgmt.batch.models.Certificate :raises ~azure.core.exceptions.HttpResponseError: """ @overload async def create( self, resource_group_name: str, account_name: str, certificate_name: str, parameters: IO, if_match: Optional[str] = None, if_none_match: Optional[str] = None, *, content_type: str = "application/json", **kwargs: Any ) -> _models.Certificate: """Creates a new certificate inside the specified account. Warning: This operation is deprecated and will be removed after February, 2024. Please use the `Azure KeyVault Extension <https://learn.microsoft.com/azure/batch/batch-certificate-migration-guide>`_ instead. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param certificate_name: The identifier for the certificate. This must be made up of algorithm and thumbprint separated by a dash, and must match the certificate data in the request. For example SHA1-a3d1c5. Required. :type certificate_name: str :param parameters: Additional parameters for certificate creation. Required. :type parameters: IO :param if_match: The entity state (ETag) version of the certificate to update. A value of "*" can be used to apply the operation only if the certificate already exists. If omitted, this operation will always be applied. Default value is None. :type if_match: str :param if_none_match: Set to '*' to allow a new certificate to be created, but to prevent updating an existing certificate. Other values will be ignored. Default value is None. :type if_none_match: str :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Certificate or the result of cls(response) :rtype: ~azure.mgmt.batch.models.Certificate :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace_async async def create( self, resource_group_name: str, account_name: str, certificate_name: str, parameters: Union[_models.CertificateCreateOrUpdateParameters, IO], if_match: Optional[str] = None, if_none_match: Optional[str] = None, **kwargs: Any ) -> _models.Certificate: """Creates a new certificate inside the specified account. Warning: This operation is deprecated and will be removed after February, 2024. Please use the `Azure KeyVault Extension <https://learn.microsoft.com/azure/batch/batch-certificate-migration-guide>`_ instead. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param certificate_name: The identifier for the certificate. This must be made up of algorithm and thumbprint separated by a dash, and must match the certificate data in the request. For example SHA1-a3d1c5. Required. :type certificate_name: str :param parameters: Additional parameters for certificate creation. Is either a CertificateCreateOrUpdateParameters type or a IO type. Required. :type parameters: ~azure.mgmt.batch.models.CertificateCreateOrUpdateParameters or IO :param if_match: The entity state (ETag) version of the certificate to update. A value of "*" can be used to apply the operation only if the certificate already exists. If omitted, this operation will always be applied. Default value is None. :type if_match: str :param if_none_match: Set to '*' to allow a new certificate to be created, but to prevent updating an existing certificate. Other values will be ignored. Default value is None. :type if_none_match: str :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. Default value is None. :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Certificate or the result of cls(response) :rtype: ~azure.mgmt.batch.models.Certificate :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.Certificate] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None if isinstance(parameters, (IOBase, bytes)): _content = parameters else: _json = self._serialize.body(parameters, "CertificateCreateOrUpdateParameters") request = build_create_request( resource_group_name=resource_group_name, account_name=account_name, certificate_name=certificate_name, subscription_id=self._config.subscription_id, if_match=if_match, if_none_match=if_none_match, api_version=api_version, content_type=content_type, json=_json, content=_content, template_url=self.create.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) response_headers = {} response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) deserialized = self._deserialize("Certificate", pipeline_response) if cls: return cls(pipeline_response, deserialized, response_headers) return deserialized create.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/certificates/{certificateName}" } @overload async def update( self, resource_group_name: str, account_name: str, certificate_name: str, parameters: _models.CertificateCreateOrUpdateParameters, if_match: Optional[str] = None, *, content_type: str = "application/json", **kwargs: Any ) -> _models.Certificate: """Updates the properties of an existing certificate. Warning: This operation is deprecated and will be removed after February, 2024. Please use the `Azure KeyVault Extension <https://learn.microsoft.com/azure/batch/batch-certificate-migration-guide>`_ instead. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param certificate_name: The identifier for the certificate. This must be made up of algorithm and thumbprint separated by a dash, and must match the certificate data in the request. For example SHA1-a3d1c5. Required. :type certificate_name: str :param parameters: Certificate entity to update. Required. :type parameters: ~azure.mgmt.batch.models.CertificateCreateOrUpdateParameters :param if_match: The entity state (ETag) version of the certificate to update. This value can be omitted or set to "*" to apply the operation unconditionally. Default value is None. :type if_match: str :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Certificate or the result of cls(response) :rtype: ~azure.mgmt.batch.models.Certificate :raises ~azure.core.exceptions.HttpResponseError: """ @overload async def update( self, resource_group_name: str, account_name: str, certificate_name: str, parameters: IO, if_match: Optional[str] = None, *, content_type: str = "application/json", **kwargs: Any ) -> _models.Certificate: """Updates the properties of an existing certificate. Warning: This operation is deprecated and will be removed after February, 2024. Please use the `Azure KeyVault Extension <https://learn.microsoft.com/azure/batch/batch-certificate-migration-guide>`_ instead. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param certificate_name: The identifier for the certificate. This must be made up of algorithm and thumbprint separated by a dash, and must match the certificate data in the request. For example SHA1-a3d1c5. Required. :type certificate_name: str :param parameters: Certificate entity to update. Required. :type parameters: IO :param if_match: The entity state (ETag) version of the certificate to update. This value can be omitted or set to "*" to apply the operation unconditionally. Default value is None. :type if_match: str :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Certificate or the result of cls(response) :rtype: ~azure.mgmt.batch.models.Certificate :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace_async async def update( self, resource_group_name: str, account_name: str, certificate_name: str, parameters: Union[_models.CertificateCreateOrUpdateParameters, IO], if_match: Optional[str] = None, **kwargs: Any ) -> _models.Certificate: """Updates the properties of an existing certificate. Warning: This operation is deprecated and will be removed after February, 2024. Please use the `Azure KeyVault Extension <https://learn.microsoft.com/azure/batch/batch-certificate-migration-guide>`_ instead. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param certificate_name: The identifier for the certificate. This must be made up of algorithm and thumbprint separated by a dash, and must match the certificate data in the request. For example SHA1-a3d1c5. Required. :type certificate_name: str :param parameters: Certificate entity to update. Is either a CertificateCreateOrUpdateParameters type or a IO type. Required. :type parameters: ~azure.mgmt.batch.models.CertificateCreateOrUpdateParameters or IO :param if_match: The entity state (ETag) version of the certificate to update. This value can be omitted or set to "*" to apply the operation unconditionally. Default value is None. :type if_match: str :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. Default value is None. :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Certificate or the result of cls(response) :rtype: ~azure.mgmt.batch.models.Certificate :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.Certificate] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None if isinstance(parameters, (IOBase, bytes)): _content = parameters else: _json = self._serialize.body(parameters, "CertificateCreateOrUpdateParameters") request = build_update_request( resource_group_name=resource_group_name, account_name=account_name, certificate_name=certificate_name, subscription_id=self._config.subscription_id, if_match=if_match, api_version=api_version, content_type=content_type, json=_json, content=_content, template_url=self.update.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) response_headers = {} response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) deserialized = self._deserialize("Certificate", pipeline_response) if cls: return cls(pipeline_response, deserialized, response_headers) return deserialized update.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/certificates/{certificateName}" } async def _delete_initial( # pylint: disable=inconsistent-return-statements self, resource_group_name: str, account_name: str, certificate_name: str, **kwargs: Any ) -> None: error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[None] = kwargs.pop("cls", None) request = build_delete_request( resource_group_name=resource_group_name, account_name=account_name, certificate_name=certificate_name, subscription_id=self._config.subscription_id, api_version=api_version, template_url=self._delete_initial.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) response_headers = {} if response.status_code == 202: response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) if cls: return cls(pipeline_response, None, response_headers) _delete_initial.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/certificates/{certificateName}" } @distributed_trace_async async def begin_delete( self, resource_group_name: str, account_name: str, certificate_name: str, **kwargs: Any ) -> AsyncLROPoller[None]: """Deletes the specified certificate. Warning: This operation is deprecated and will be removed after February, 2024. Please use the `Azure KeyVault Extension <https://learn.microsoft.com/azure/batch/batch-certificate-migration-guide>`_ instead. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param certificate_name: The identifier for the certificate. This must be made up of algorithm and thumbprint separated by a dash, and must match the certificate data in the request. For example SHA1-a3d1c5. Required. :type certificate_name: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[None] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[None] = kwargs.pop("cls", None) polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) cont_token: Optional[str] = kwargs.pop("continuation_token", None) if cont_token is None: raw_result = await self._delete_initial( # type: ignore resource_group_name=resource_group_name, account_name=account_name, certificate_name=certificate_name, api_version=api_version, cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) if polling is True: polling_method: AsyncPollingMethod = cast( AsyncPollingMethod, AsyncARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) ) elif polling is False: polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) else: polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore begin_delete.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/certificates/{certificateName}" } @distributed_trace_async async def get( self, resource_group_name: str, account_name: str, certificate_name: str, **kwargs: Any ) -> _models.Certificate: """Gets information about the specified certificate. Warning: This operation is deprecated and will be removed after February, 2024. Please use the `Azure KeyVault Extension <https://learn.microsoft.com/azure/batch/batch-certificate-migration-guide>`_ instead. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param certificate_name: The identifier for the certificate. This must be made up of algorithm and thumbprint separated by a dash, and must match the certificate data in the request. For example SHA1-a3d1c5. Required. :type certificate_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Certificate or the result of cls(response) :rtype: ~azure.mgmt.batch.models.Certificate :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.Certificate] = kwargs.pop("cls", None) request = build_get_request( resource_group_name=resource_group_name, account_name=account_name, certificate_name=certificate_name, subscription_id=self._config.subscription_id, api_version=api_version, template_url=self.get.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) response_headers = {} response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) deserialized = self._deserialize("Certificate", pipeline_response) if cls: return cls(pipeline_response, deserialized, response_headers) return deserialized get.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/certificates/{certificateName}" } @distributed_trace_async async def cancel_deletion( self, resource_group_name: str, account_name: str, certificate_name: str, **kwargs: Any ) -> _models.Certificate: """Cancels a failed deletion of a certificate from the specified account. If you try to delete a certificate that is being used by a pool or compute node, the status of the certificate changes to deleteFailed. If you decide that you want to continue using the certificate, you can use this operation to set the status of the certificate back to active. If you intend to delete the certificate, you do not need to run this operation after the deletion failed. You must make sure that the certificate is not being used by any resources, and then you can try again to delete the certificate. Warning: This operation is deprecated and will be removed after February, 2024. Please use the `Azure KeyVault Extension <https://learn.microsoft.com/azure/batch/batch-certificate-migration-guide>`_ instead. :param resource_group_name: The name of the resource group that contains the Batch account. Required. :type resource_group_name: str :param account_name: The name of the Batch account. Required. :type account_name: str :param certificate_name: The identifier for the certificate. This must be made up of algorithm and thumbprint separated by a dash, and must match the certificate data in the request. For example SHA1-a3d1c5. Required. :type certificate_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Certificate or the result of cls(response) :rtype: ~azure.mgmt.batch.models.Certificate :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.Certificate] = kwargs.pop("cls", None) request = build_cancel_deletion_request( resource_group_name=resource_group_name, account_name=account_name, certificate_name=certificate_name, subscription_id=self._config.subscription_id, api_version=api_version, template_url=self.cancel_deletion.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) response_headers = {} response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) deserialized = self._deserialize("Certificate", pipeline_response) if cls: return cls(pipeline_response, deserialized, response_headers) return deserialized cancel_deletion.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/certificates/{certificateName}/cancelDelete" }
0.908625
0.099952
import datetime import sys from typing import Any, Dict, List, Optional, TYPE_CHECKING, Union from .. import _serialization if sys.version_info >= (3, 9): from collections.abc import MutableMapping else: from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports if sys.version_info >= (3, 8): from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports else: from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from .. import models as _models JSON = MutableMapping[str, Any] # pylint: disable=unsubscriptable-object class ActivateApplicationPackageParameters(_serialization.Model): """Parameters for an activating an application package. All required parameters must be populated in order to send to Azure. :ivar format: The format of the application package binary file. Required. :vartype format: str """ _validation = { "format": {"required": True}, } _attribute_map = { "format": {"key": "format", "type": "str"}, } def __init__(self, *, format: str, **kwargs: Any) -> None: """ :keyword format: The format of the application package binary file. Required. :paramtype format: str """ super().__init__(**kwargs) self.format = format class ProxyResource(_serialization.Model): """A definition of an Azure resource. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: The ID of the resource. :vartype id: str :ivar name: The name of the resource. :vartype name: str :ivar type: The type of the resource. :vartype type: str :ivar etag: The ETag of the resource, used for concurrency statements. :vartype etag: str """ _validation = { "id": {"readonly": True}, "name": {"readonly": True}, "type": {"readonly": True}, "etag": {"readonly": True}, } _attribute_map = { "id": {"key": "id", "type": "str"}, "name": {"key": "name", "type": "str"}, "type": {"key": "type", "type": "str"}, "etag": {"key": "etag", "type": "str"}, } def __init__(self, **kwargs: Any) -> None: """ """ super().__init__(**kwargs) self.id = None self.name = None self.type = None self.etag = None class Application(ProxyResource): """Contains information about an application in a Batch account. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: The ID of the resource. :vartype id: str :ivar name: The name of the resource. :vartype name: str :ivar type: The type of the resource. :vartype type: str :ivar etag: The ETag of the resource, used for concurrency statements. :vartype etag: str :ivar display_name: The display name for the application. :vartype display_name: str :ivar allow_updates: A value indicating whether packages within the application may be overwritten using the same version string. :vartype allow_updates: bool :ivar default_version: The package to use if a client requests the application but does not specify a version. This property can only be set to the name of an existing package. :vartype default_version: str """ _validation = { "id": {"readonly": True}, "name": {"readonly": True}, "type": {"readonly": True}, "etag": {"readonly": True}, } _attribute_map = { "id": {"key": "id", "type": "str"}, "name": {"key": "name", "type": "str"}, "type": {"key": "type", "type": "str"}, "etag": {"key": "etag", "type": "str"}, "display_name": {"key": "properties.displayName", "type": "str"}, "allow_updates": {"key": "properties.allowUpdates", "type": "bool"}, "default_version": {"key": "properties.defaultVersion", "type": "str"}, } def __init__( self, *, display_name: Optional[str] = None, allow_updates: Optional[bool] = None, default_version: Optional[str] = None, **kwargs: Any ) -> None: """ :keyword display_name: The display name for the application. :paramtype display_name: str :keyword allow_updates: A value indicating whether packages within the application may be overwritten using the same version string. :paramtype allow_updates: bool :keyword default_version: The package to use if a client requests the application but does not specify a version. This property can only be set to the name of an existing package. :paramtype default_version: str """ super().__init__(**kwargs) self.display_name = display_name self.allow_updates = allow_updates self.default_version = default_version class ApplicationPackage(ProxyResource): """An application package which represents a particular version of an application. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: The ID of the resource. :vartype id: str :ivar name: The name of the resource. :vartype name: str :ivar type: The type of the resource. :vartype type: str :ivar etag: The ETag of the resource, used for concurrency statements. :vartype etag: str :ivar state: The current state of the application package. Known values are: "Pending" and "Active". :vartype state: str or ~azure.mgmt.batch.models.PackageState :ivar format: The format of the application package, if the package is active. :vartype format: str :ivar storage_url: The URL for the application package in Azure Storage. :vartype storage_url: str :ivar storage_url_expiry: The UTC time at which the Azure Storage URL will expire. :vartype storage_url_expiry: ~datetime.datetime :ivar last_activation_time: The time at which the package was last activated, if the package is active. :vartype last_activation_time: ~datetime.datetime """ _validation = { "id": {"readonly": True}, "name": {"readonly": True}, "type": {"readonly": True}, "etag": {"readonly": True}, "state": {"readonly": True}, "format": {"readonly": True}, "storage_url": {"readonly": True}, "storage_url_expiry": {"readonly": True}, "last_activation_time": {"readonly": True}, } _attribute_map = { "id": {"key": "id", "type": "str"}, "name": {"key": "name", "type": "str"}, "type": {"key": "type", "type": "str"}, "etag": {"key": "etag", "type": "str"}, "state": {"key": "properties.state", "type": "str"}, "format": {"key": "properties.format", "type": "str"}, "storage_url": {"key": "properties.storageUrl", "type": "str"}, "storage_url_expiry": {"key": "properties.storageUrlExpiry", "type": "iso-8601"}, "last_activation_time": {"key": "properties.lastActivationTime", "type": "iso-8601"}, } def __init__(self, **kwargs: Any) -> None: """ """ super().__init__(**kwargs) self.state = None self.format = None self.storage_url = None self.storage_url_expiry = None self.last_activation_time = None class ApplicationPackageReference(_serialization.Model): """Link to an application package inside the batch account. All required parameters must be populated in order to send to Azure. :ivar id: The ID of the application package to install. This must be inside the same batch account as the pool. This can either be a reference to a specific version or the default version if one exists. Required. :vartype id: str :ivar version: If this is omitted, and no default version is specified for this application, the request fails with the error code InvalidApplicationPackageReferences. If you are calling the REST API directly, the HTTP status code is 409. :vartype version: str """ _validation = { "id": {"required": True}, } _attribute_map = { "id": {"key": "id", "type": "str"}, "version": {"key": "version", "type": "str"}, } def __init__( self, *, id: str, version: Optional[str] = None, **kwargs: Any # pylint: disable=redefined-builtin ) -> None: """ :keyword id: The ID of the application package to install. This must be inside the same batch account as the pool. This can either be a reference to a specific version or the default version if one exists. Required. :paramtype id: str :keyword version: If this is omitted, and no default version is specified for this application, the request fails with the error code InvalidApplicationPackageReferences. If you are calling the REST API directly, the HTTP status code is 409. :paramtype version: str """ super().__init__(**kwargs) self.id = id self.version = version class AutoScaleRun(_serialization.Model): """The results and errors from an execution of a pool autoscale formula. All required parameters must be populated in order to send to Azure. :ivar evaluation_time: The time at which the autoscale formula was last evaluated. Required. :vartype evaluation_time: ~datetime.datetime :ivar results: Each variable value is returned in the form $variable=value, and variables are separated by semicolons. :vartype results: str :ivar error: An error that occurred when autoscaling a pool. :vartype error: ~azure.mgmt.batch.models.AutoScaleRunError """ _validation = { "evaluation_time": {"required": True}, } _attribute_map = { "evaluation_time": {"key": "evaluationTime", "type": "iso-8601"}, "results": {"key": "results", "type": "str"}, "error": {"key": "error", "type": "AutoScaleRunError"}, } def __init__( self, *, evaluation_time: datetime.datetime, results: Optional[str] = None, error: Optional["_models.AutoScaleRunError"] = None, **kwargs: Any ) -> None: """ :keyword evaluation_time: The time at which the autoscale formula was last evaluated. Required. :paramtype evaluation_time: ~datetime.datetime :keyword results: Each variable value is returned in the form $variable=value, and variables are separated by semicolons. :paramtype results: str :keyword error: An error that occurred when autoscaling a pool. :paramtype error: ~azure.mgmt.batch.models.AutoScaleRunError """ super().__init__(**kwargs) self.evaluation_time = evaluation_time self.results = results self.error = error class AutoScaleRunError(_serialization.Model): """An error that occurred when autoscaling a pool. All required parameters must be populated in order to send to Azure. :ivar code: An identifier for the error. Codes are invariant and are intended to be consumed programmatically. Required. :vartype code: str :ivar message: A message describing the error, intended to be suitable for display in a user interface. Required. :vartype message: str :ivar details: Additional details about the error. :vartype details: list[~azure.mgmt.batch.models.AutoScaleRunError] """ _validation = { "code": {"required": True}, "message": {"required": True}, } _attribute_map = { "code": {"key": "code", "type": "str"}, "message": {"key": "message", "type": "str"}, "details": {"key": "details", "type": "[AutoScaleRunError]"}, } def __init__( self, *, code: str, message: str, details: Optional[List["_models.AutoScaleRunError"]] = None, **kwargs: Any ) -> None: """ :keyword code: An identifier for the error. Codes are invariant and are intended to be consumed programmatically. Required. :paramtype code: str :keyword message: A message describing the error, intended to be suitable for display in a user interface. Required. :paramtype message: str :keyword details: Additional details about the error. :paramtype details: list[~azure.mgmt.batch.models.AutoScaleRunError] """ super().__init__(**kwargs) self.code = code self.message = message self.details = details class AutoScaleSettings(_serialization.Model): """AutoScale settings for the pool. All required parameters must be populated in order to send to Azure. :ivar formula: A formula for the desired number of compute nodes in the pool. Required. :vartype formula: str :ivar evaluation_interval: If omitted, the default value is 15 minutes (PT15M). :vartype evaluation_interval: ~datetime.timedelta """ _validation = { "formula": {"required": True}, } _attribute_map = { "formula": {"key": "formula", "type": "str"}, "evaluation_interval": {"key": "evaluationInterval", "type": "duration"}, } def __init__( self, *, formula: str, evaluation_interval: Optional[datetime.timedelta] = None, **kwargs: Any ) -> None: """ :keyword formula: A formula for the desired number of compute nodes in the pool. Required. :paramtype formula: str :keyword evaluation_interval: If omitted, the default value is 15 minutes (PT15M). :paramtype evaluation_interval: ~datetime.timedelta """ super().__init__(**kwargs) self.formula = formula self.evaluation_interval = evaluation_interval class AutoStorageBaseProperties(_serialization.Model): """The properties related to the auto-storage account. All required parameters must be populated in order to send to Azure. :ivar storage_account_id: The resource ID of the storage account to be used for auto-storage account. Required. :vartype storage_account_id: str :ivar authentication_mode: The authentication mode which the Batch service will use to manage the auto-storage account. Known values are: "StorageKeys" and "BatchAccountManagedIdentity". :vartype authentication_mode: str or ~azure.mgmt.batch.models.AutoStorageAuthenticationMode :ivar node_identity_reference: The identity referenced here must be assigned to pools which have compute nodes that need access to auto-storage. :vartype node_identity_reference: ~azure.mgmt.batch.models.ComputeNodeIdentityReference """ _validation = { "storage_account_id": {"required": True}, } _attribute_map = { "storage_account_id": {"key": "storageAccountId", "type": "str"}, "authentication_mode": {"key": "authenticationMode", "type": "str"}, "node_identity_reference": {"key": "nodeIdentityReference", "type": "ComputeNodeIdentityReference"}, } def __init__( self, *, storage_account_id: str, authentication_mode: Union[str, "_models.AutoStorageAuthenticationMode"] = "StorageKeys", node_identity_reference: Optional["_models.ComputeNodeIdentityReference"] = None, **kwargs: Any ) -> None: """ :keyword storage_account_id: The resource ID of the storage account to be used for auto-storage account. Required. :paramtype storage_account_id: str :keyword authentication_mode: The authentication mode which the Batch service will use to manage the auto-storage account. Known values are: "StorageKeys" and "BatchAccountManagedIdentity". :paramtype authentication_mode: str or ~azure.mgmt.batch.models.AutoStorageAuthenticationMode :keyword node_identity_reference: The identity referenced here must be assigned to pools which have compute nodes that need access to auto-storage. :paramtype node_identity_reference: ~azure.mgmt.batch.models.ComputeNodeIdentityReference """ super().__init__(**kwargs) self.storage_account_id = storage_account_id self.authentication_mode = authentication_mode self.node_identity_reference = node_identity_reference class AutoStorageProperties(AutoStorageBaseProperties): """Contains information about the auto-storage account associated with a Batch account. All required parameters must be populated in order to send to Azure. :ivar storage_account_id: The resource ID of the storage account to be used for auto-storage account. Required. :vartype storage_account_id: str :ivar authentication_mode: The authentication mode which the Batch service will use to manage the auto-storage account. Known values are: "StorageKeys" and "BatchAccountManagedIdentity". :vartype authentication_mode: str or ~azure.mgmt.batch.models.AutoStorageAuthenticationMode :ivar node_identity_reference: The identity referenced here must be assigned to pools which have compute nodes that need access to auto-storage. :vartype node_identity_reference: ~azure.mgmt.batch.models.ComputeNodeIdentityReference :ivar last_key_sync: The UTC time at which storage keys were last synchronized with the Batch account. Required. :vartype last_key_sync: ~datetime.datetime """ _validation = { "storage_account_id": {"required": True}, "last_key_sync": {"required": True}, } _attribute_map = { "storage_account_id": {"key": "storageAccountId", "type": "str"}, "authentication_mode": {"key": "authenticationMode", "type": "str"}, "node_identity_reference": {"key": "nodeIdentityReference", "type": "ComputeNodeIdentityReference"}, "last_key_sync": {"key": "lastKeySync", "type": "iso-8601"}, } def __init__( self, *, storage_account_id: str, last_key_sync: datetime.datetime, authentication_mode: Union[str, "_models.AutoStorageAuthenticationMode"] = "StorageKeys", node_identity_reference: Optional["_models.ComputeNodeIdentityReference"] = None, **kwargs: Any ) -> None: """ :keyword storage_account_id: The resource ID of the storage account to be used for auto-storage account. Required. :paramtype storage_account_id: str :keyword authentication_mode: The authentication mode which the Batch service will use to manage the auto-storage account. Known values are: "StorageKeys" and "BatchAccountManagedIdentity". :paramtype authentication_mode: str or ~azure.mgmt.batch.models.AutoStorageAuthenticationMode :keyword node_identity_reference: The identity referenced here must be assigned to pools which have compute nodes that need access to auto-storage. :paramtype node_identity_reference: ~azure.mgmt.batch.models.ComputeNodeIdentityReference :keyword last_key_sync: The UTC time at which storage keys were last synchronized with the Batch account. Required. :paramtype last_key_sync: ~datetime.datetime """ super().__init__( storage_account_id=storage_account_id, authentication_mode=authentication_mode, node_identity_reference=node_identity_reference, **kwargs ) self.last_key_sync = last_key_sync class AutoUserSpecification(_serialization.Model): """Specifies the parameters for the auto user that runs a task on the Batch service. :ivar scope: The default value is Pool. If the pool is running Windows a value of Task should be specified if stricter isolation between tasks is required. For example, if the task mutates the registry in a way which could impact other tasks, or if certificates have been specified on the pool which should not be accessible by normal tasks but should be accessible by start tasks. Known values are: "Task" and "Pool". :vartype scope: str or ~azure.mgmt.batch.models.AutoUserScope :ivar elevation_level: The default value is nonAdmin. Known values are: "NonAdmin" and "Admin". :vartype elevation_level: str or ~azure.mgmt.batch.models.ElevationLevel """ _attribute_map = { "scope": {"key": "scope", "type": "str"}, "elevation_level": {"key": "elevationLevel", "type": "str"}, } def __init__( self, *, scope: Optional[Union[str, "_models.AutoUserScope"]] = None, elevation_level: Optional[Union[str, "_models.ElevationLevel"]] = None, **kwargs: Any ) -> None: """ :keyword scope: The default value is Pool. If the pool is running Windows a value of Task should be specified if stricter isolation between tasks is required. For example, if the task mutates the registry in a way which could impact other tasks, or if certificates have been specified on the pool which should not be accessible by normal tasks but should be accessible by start tasks. Known values are: "Task" and "Pool". :paramtype scope: str or ~azure.mgmt.batch.models.AutoUserScope :keyword elevation_level: The default value is nonAdmin. Known values are: "NonAdmin" and "Admin". :paramtype elevation_level: str or ~azure.mgmt.batch.models.ElevationLevel """ super().__init__(**kwargs) self.scope = scope self.elevation_level = elevation_level class AzureBlobFileSystemConfiguration(_serialization.Model): """Information used to connect to an Azure Storage Container using Blobfuse. All required parameters must be populated in order to send to Azure. :ivar account_name: The Azure Storage Account name. Required. :vartype account_name: str :ivar container_name: The Azure Blob Storage Container name. Required. :vartype container_name: str :ivar account_key: This property is mutually exclusive with both sasKey and identity; exactly one must be specified. :vartype account_key: str :ivar sas_key: This property is mutually exclusive with both accountKey and identity; exactly one must be specified. :vartype sas_key: str :ivar blobfuse_options: These are 'net use' options in Windows and 'mount' options in Linux. :vartype blobfuse_options: str :ivar relative_mount_path: All file systems are mounted relative to the Batch mounts directory, accessible via the AZ_BATCH_NODE_MOUNTS_DIR environment variable. Required. :vartype relative_mount_path: str :ivar identity_reference: This property is mutually exclusive with both accountKey and sasKey; exactly one must be specified. :vartype identity_reference: ~azure.mgmt.batch.models.ComputeNodeIdentityReference """ _validation = { "account_name": {"required": True}, "container_name": {"required": True}, "relative_mount_path": {"required": True}, } _attribute_map = { "account_name": {"key": "accountName", "type": "str"}, "container_name": {"key": "containerName", "type": "str"}, "account_key": {"key": "accountKey", "type": "str"}, "sas_key": {"key": "sasKey", "type": "str"}, "blobfuse_options": {"key": "blobfuseOptions", "type": "str"}, "relative_mount_path": {"key": "relativeMountPath", "type": "str"}, "identity_reference": {"key": "identityReference", "type": "ComputeNodeIdentityReference"}, } def __init__( self, *, account_name: str, container_name: str, relative_mount_path: str, account_key: Optional[str] = None, sas_key: Optional[str] = None, blobfuse_options: Optional[str] = None, identity_reference: Optional["_models.ComputeNodeIdentityReference"] = None, **kwargs: Any ) -> None: """ :keyword account_name: The Azure Storage Account name. Required. :paramtype account_name: str :keyword container_name: The Azure Blob Storage Container name. Required. :paramtype container_name: str :keyword account_key: This property is mutually exclusive with both sasKey and identity; exactly one must be specified. :paramtype account_key: str :keyword sas_key: This property is mutually exclusive with both accountKey and identity; exactly one must be specified. :paramtype sas_key: str :keyword blobfuse_options: These are 'net use' options in Windows and 'mount' options in Linux. :paramtype blobfuse_options: str :keyword relative_mount_path: All file systems are mounted relative to the Batch mounts directory, accessible via the AZ_BATCH_NODE_MOUNTS_DIR environment variable. Required. :paramtype relative_mount_path: str :keyword identity_reference: This property is mutually exclusive with both accountKey and sasKey; exactly one must be specified. :paramtype identity_reference: ~azure.mgmt.batch.models.ComputeNodeIdentityReference """ super().__init__(**kwargs) self.account_name = account_name self.container_name = container_name self.account_key = account_key self.sas_key = sas_key self.blobfuse_options = blobfuse_options self.relative_mount_path = relative_mount_path self.identity_reference = identity_reference class AzureFileShareConfiguration(_serialization.Model): """Information used to connect to an Azure Fileshare. All required parameters must be populated in order to send to Azure. :ivar account_name: The Azure Storage account name. Required. :vartype account_name: str :ivar azure_file_url: This is of the form 'https://{account}.file.core.windows.net/'. Required. :vartype azure_file_url: str :ivar account_key: The Azure Storage account key. Required. :vartype account_key: str :ivar relative_mount_path: All file systems are mounted relative to the Batch mounts directory, accessible via the AZ_BATCH_NODE_MOUNTS_DIR environment variable. Required. :vartype relative_mount_path: str :ivar mount_options: These are 'net use' options in Windows and 'mount' options in Linux. :vartype mount_options: str """ _validation = { "account_name": {"required": True}, "azure_file_url": {"required": True}, "account_key": {"required": True}, "relative_mount_path": {"required": True}, } _attribute_map = { "account_name": {"key": "accountName", "type": "str"}, "azure_file_url": {"key": "azureFileUrl", "type": "str"}, "account_key": {"key": "accountKey", "type": "str"}, "relative_mount_path": {"key": "relativeMountPath", "type": "str"}, "mount_options": {"key": "mountOptions", "type": "str"}, } def __init__( self, *, account_name: str, azure_file_url: str, account_key: str, relative_mount_path: str, mount_options: Optional[str] = None, **kwargs: Any ) -> None: """ :keyword account_name: The Azure Storage account name. Required. :paramtype account_name: str :keyword azure_file_url: This is of the form 'https://{account}.file.core.windows.net/'. Required. :paramtype azure_file_url: str :keyword account_key: The Azure Storage account key. Required. :paramtype account_key: str :keyword relative_mount_path: All file systems are mounted relative to the Batch mounts directory, accessible via the AZ_BATCH_NODE_MOUNTS_DIR environment variable. Required. :paramtype relative_mount_path: str :keyword mount_options: These are 'net use' options in Windows and 'mount' options in Linux. :paramtype mount_options: str """ super().__init__(**kwargs) self.account_name = account_name self.azure_file_url = azure_file_url self.account_key = account_key self.relative_mount_path = relative_mount_path self.mount_options = mount_options class Resource(_serialization.Model): """A definition of an Azure resource. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: The ID of the resource. :vartype id: str :ivar name: The name of the resource. :vartype name: str :ivar type: The type of the resource. :vartype type: str :ivar location: The location of the resource. :vartype location: str :ivar tags: The tags of the resource. :vartype tags: dict[str, str] """ _validation = { "id": {"readonly": True}, "name": {"readonly": True}, "type": {"readonly": True}, "location": {"readonly": True}, "tags": {"readonly": True}, } _attribute_map = { "id": {"key": "id", "type": "str"}, "name": {"key": "name", "type": "str"}, "type": {"key": "type", "type": "str"}, "location": {"key": "location", "type": "str"}, "tags": {"key": "tags", "type": "{str}"}, } def __init__(self, **kwargs: Any) -> None: """ """ super().__init__(**kwargs) self.id = None self.name = None self.type = None self.location = None self.tags = None class BatchAccount(Resource): # pylint: disable=too-many-instance-attributes """Contains information about an Azure Batch account. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: The ID of the resource. :vartype id: str :ivar name: The name of the resource. :vartype name: str :ivar type: The type of the resource. :vartype type: str :ivar location: The location of the resource. :vartype location: str :ivar tags: The tags of the resource. :vartype tags: dict[str, str] :ivar identity: The identity of the Batch account. :vartype identity: ~azure.mgmt.batch.models.BatchAccountIdentity :ivar account_endpoint: The account endpoint used to interact with the Batch service. :vartype account_endpoint: str :ivar node_management_endpoint: The endpoint used by compute node to connect to the Batch node management service. :vartype node_management_endpoint: str :ivar provisioning_state: The provisioned state of the resource. Known values are: "Invalid", "Creating", "Deleting", "Succeeded", "Failed", and "Cancelled". :vartype provisioning_state: str or ~azure.mgmt.batch.models.ProvisioningState :ivar pool_allocation_mode: The allocation mode for creating pools in the Batch account. Known values are: "BatchService" and "UserSubscription". :vartype pool_allocation_mode: str or ~azure.mgmt.batch.models.PoolAllocationMode :ivar key_vault_reference: Identifies the Azure key vault associated with a Batch account. :vartype key_vault_reference: ~azure.mgmt.batch.models.KeyVaultReference :ivar public_network_access: If not specified, the default value is 'enabled'. Known values are: "Enabled" and "Disabled". :vartype public_network_access: str or ~azure.mgmt.batch.models.PublicNetworkAccessType :ivar network_profile: The network profile only takes effect when publicNetworkAccess is enabled. :vartype network_profile: ~azure.mgmt.batch.models.NetworkProfile :ivar private_endpoint_connections: List of private endpoint connections associated with the Batch account. :vartype private_endpoint_connections: list[~azure.mgmt.batch.models.PrivateEndpointConnection] :ivar auto_storage: Contains information about the auto-storage account associated with a Batch account. :vartype auto_storage: ~azure.mgmt.batch.models.AutoStorageProperties :ivar encryption: Configures how customer data is encrypted inside the Batch account. By default, accounts are encrypted using a Microsoft managed key. For additional control, a customer-managed key can be used instead. :vartype encryption: ~azure.mgmt.batch.models.EncryptionProperties :ivar dedicated_core_quota: For accounts with PoolAllocationMode set to UserSubscription, quota is managed on the subscription so this value is not returned. :vartype dedicated_core_quota: int :ivar low_priority_core_quota: For accounts with PoolAllocationMode set to UserSubscription, quota is managed on the subscription so this value is not returned. :vartype low_priority_core_quota: int :ivar dedicated_core_quota_per_vm_family: A list of the dedicated core quota per Virtual Machine family for the Batch account. For accounts with PoolAllocationMode set to UserSubscription, quota is managed on the subscription so this value is not returned. :vartype dedicated_core_quota_per_vm_family: list[~azure.mgmt.batch.models.VirtualMachineFamilyCoreQuota] :ivar dedicated_core_quota_per_vm_family_enforced: If this flag is true, dedicated core quota is enforced via both the dedicatedCoreQuotaPerVMFamily and dedicatedCoreQuota properties on the account. If this flag is false, dedicated core quota is enforced only via the dedicatedCoreQuota property on the account and does not consider Virtual Machine family. :vartype dedicated_core_quota_per_vm_family_enforced: bool :ivar pool_quota: The pool quota for the Batch account. :vartype pool_quota: int :ivar active_job_and_job_schedule_quota: The active job and job schedule quota for the Batch account. :vartype active_job_and_job_schedule_quota: int :ivar allowed_authentication_modes: List of allowed authentication modes for the Batch account that can be used to authenticate with the data plane. This does not affect authentication with the control plane. :vartype allowed_authentication_modes: list[str or ~azure.mgmt.batch.models.AuthenticationMode] """ _validation = { "id": {"readonly": True}, "name": {"readonly": True}, "type": {"readonly": True}, "location": {"readonly": True}, "tags": {"readonly": True}, "account_endpoint": {"readonly": True}, "node_management_endpoint": {"readonly": True}, "provisioning_state": {"readonly": True}, "pool_allocation_mode": {"readonly": True}, "key_vault_reference": {"readonly": True}, "private_endpoint_connections": {"readonly": True}, "auto_storage": {"readonly": True}, "encryption": {"readonly": True}, "dedicated_core_quota": {"readonly": True}, "low_priority_core_quota": {"readonly": True}, "dedicated_core_quota_per_vm_family": {"readonly": True}, "dedicated_core_quota_per_vm_family_enforced": {"readonly": True}, "pool_quota": {"readonly": True}, "active_job_and_job_schedule_quota": {"readonly": True}, "allowed_authentication_modes": {"readonly": True}, } _attribute_map = { "id": {"key": "id", "type": "str"}, "name": {"key": "name", "type": "str"}, "type": {"key": "type", "type": "str"}, "location": {"key": "location", "type": "str"}, "tags": {"key": "tags", "type": "{str}"}, "identity": {"key": "identity", "type": "BatchAccountIdentity"}, "account_endpoint": {"key": "properties.accountEndpoint", "type": "str"}, "node_management_endpoint": {"key": "properties.nodeManagementEndpoint", "type": "str"}, "provisioning_state": {"key": "properties.provisioningState", "type": "str"}, "pool_allocation_mode": {"key": "properties.poolAllocationMode", "type": "str"}, "key_vault_reference": {"key": "properties.keyVaultReference", "type": "KeyVaultReference"}, "public_network_access": {"key": "properties.publicNetworkAccess", "type": "str"}, "network_profile": {"key": "properties.networkProfile", "type": "NetworkProfile"}, "private_endpoint_connections": { "key": "properties.privateEndpointConnections", "type": "[PrivateEndpointConnection]", }, "auto_storage": {"key": "properties.autoStorage", "type": "AutoStorageProperties"}, "encryption": {"key": "properties.encryption", "type": "EncryptionProperties"}, "dedicated_core_quota": {"key": "properties.dedicatedCoreQuota", "type": "int"}, "low_priority_core_quota": {"key": "properties.lowPriorityCoreQuota", "type": "int"}, "dedicated_core_quota_per_vm_family": { "key": "properties.dedicatedCoreQuotaPerVMFamily", "type": "[VirtualMachineFamilyCoreQuota]", }, "dedicated_core_quota_per_vm_family_enforced": { "key": "properties.dedicatedCoreQuotaPerVMFamilyEnforced", "type": "bool", }, "pool_quota": {"key": "properties.poolQuota", "type": "int"}, "active_job_and_job_schedule_quota": {"key": "properties.activeJobAndJobScheduleQuota", "type": "int"}, "allowed_authentication_modes": {"key": "properties.allowedAuthenticationModes", "type": "[str]"}, } def __init__( self, *, identity: Optional["_models.BatchAccountIdentity"] = None, public_network_access: Union[str, "_models.PublicNetworkAccessType"] = "Enabled", network_profile: Optional["_models.NetworkProfile"] = None, **kwargs: Any ) -> None: """ :keyword identity: The identity of the Batch account. :paramtype identity: ~azure.mgmt.batch.models.BatchAccountIdentity :keyword public_network_access: If not specified, the default value is 'enabled'. Known values are: "Enabled" and "Disabled". :paramtype public_network_access: str or ~azure.mgmt.batch.models.PublicNetworkAccessType :keyword network_profile: The network profile only takes effect when publicNetworkAccess is enabled. :paramtype network_profile: ~azure.mgmt.batch.models.NetworkProfile """ super().__init__(**kwargs) self.identity = identity self.account_endpoint = None self.node_management_endpoint = None self.provisioning_state = None self.pool_allocation_mode = None self.key_vault_reference = None self.public_network_access = public_network_access self.network_profile = network_profile self.private_endpoint_connections = None self.auto_storage = None self.encryption = None self.dedicated_core_quota = None self.low_priority_core_quota = None self.dedicated_core_quota_per_vm_family = None self.dedicated_core_quota_per_vm_family_enforced = None self.pool_quota = None self.active_job_and_job_schedule_quota = None self.allowed_authentication_modes = None class BatchAccountCreateParameters(_serialization.Model): """Parameters supplied to the Create operation. All required parameters must be populated in order to send to Azure. :ivar location: The region in which to create the account. Required. :vartype location: str :ivar tags: The user-specified tags associated with the account. :vartype tags: dict[str, str] :ivar identity: The identity of the Batch account. :vartype identity: ~azure.mgmt.batch.models.BatchAccountIdentity :ivar auto_storage: The properties related to the auto-storage account. :vartype auto_storage: ~azure.mgmt.batch.models.AutoStorageBaseProperties :ivar pool_allocation_mode: The pool allocation mode also affects how clients may authenticate to the Batch Service API. If the mode is BatchService, clients may authenticate using access keys or Azure Active Directory. If the mode is UserSubscription, clients must use Azure Active Directory. The default is BatchService. Known values are: "BatchService" and "UserSubscription". :vartype pool_allocation_mode: str or ~azure.mgmt.batch.models.PoolAllocationMode :ivar key_vault_reference: A reference to the Azure key vault associated with the Batch account. :vartype key_vault_reference: ~azure.mgmt.batch.models.KeyVaultReference :ivar public_network_access: If not specified, the default value is 'enabled'. Known values are: "Enabled" and "Disabled". :vartype public_network_access: str or ~azure.mgmt.batch.models.PublicNetworkAccessType :ivar network_profile: The network profile only takes effect when publicNetworkAccess is enabled. :vartype network_profile: ~azure.mgmt.batch.models.NetworkProfile :ivar encryption: Configures how customer data is encrypted inside the Batch account. By default, accounts are encrypted using a Microsoft managed key. For additional control, a customer-managed key can be used instead. :vartype encryption: ~azure.mgmt.batch.models.EncryptionProperties :ivar allowed_authentication_modes: List of allowed authentication modes for the Batch account that can be used to authenticate with the data plane. This does not affect authentication with the control plane. :vartype allowed_authentication_modes: list[str or ~azure.mgmt.batch.models.AuthenticationMode] """ _validation = { "location": {"required": True}, } _attribute_map = { "location": {"key": "location", "type": "str"}, "tags": {"key": "tags", "type": "{str}"}, "identity": {"key": "identity", "type": "BatchAccountIdentity"}, "auto_storage": {"key": "properties.autoStorage", "type": "AutoStorageBaseProperties"}, "pool_allocation_mode": {"key": "properties.poolAllocationMode", "type": "str"}, "key_vault_reference": {"key": "properties.keyVaultReference", "type": "KeyVaultReference"}, "public_network_access": {"key": "properties.publicNetworkAccess", "type": "str"}, "network_profile": {"key": "properties.networkProfile", "type": "NetworkProfile"}, "encryption": {"key": "properties.encryption", "type": "EncryptionProperties"}, "allowed_authentication_modes": {"key": "properties.allowedAuthenticationModes", "type": "[str]"}, } def __init__( self, *, location: str, tags: Optional[Dict[str, str]] = None, identity: Optional["_models.BatchAccountIdentity"] = None, auto_storage: Optional["_models.AutoStorageBaseProperties"] = None, pool_allocation_mode: Optional[Union[str, "_models.PoolAllocationMode"]] = None, key_vault_reference: Optional["_models.KeyVaultReference"] = None, public_network_access: Union[str, "_models.PublicNetworkAccessType"] = "Enabled", network_profile: Optional["_models.NetworkProfile"] = None, encryption: Optional["_models.EncryptionProperties"] = None, allowed_authentication_modes: Optional[List[Union[str, "_models.AuthenticationMode"]]] = None, **kwargs: Any ) -> None: """ :keyword location: The region in which to create the account. Required. :paramtype location: str :keyword tags: The user-specified tags associated with the account. :paramtype tags: dict[str, str] :keyword identity: The identity of the Batch account. :paramtype identity: ~azure.mgmt.batch.models.BatchAccountIdentity :keyword auto_storage: The properties related to the auto-storage account. :paramtype auto_storage: ~azure.mgmt.batch.models.AutoStorageBaseProperties :keyword pool_allocation_mode: The pool allocation mode also affects how clients may authenticate to the Batch Service API. If the mode is BatchService, clients may authenticate using access keys or Azure Active Directory. If the mode is UserSubscription, clients must use Azure Active Directory. The default is BatchService. Known values are: "BatchService" and "UserSubscription". :paramtype pool_allocation_mode: str or ~azure.mgmt.batch.models.PoolAllocationMode :keyword key_vault_reference: A reference to the Azure key vault associated with the Batch account. :paramtype key_vault_reference: ~azure.mgmt.batch.models.KeyVaultReference :keyword public_network_access: If not specified, the default value is 'enabled'. Known values are: "Enabled" and "Disabled". :paramtype public_network_access: str or ~azure.mgmt.batch.models.PublicNetworkAccessType :keyword network_profile: The network profile only takes effect when publicNetworkAccess is enabled. :paramtype network_profile: ~azure.mgmt.batch.models.NetworkProfile :keyword encryption: Configures how customer data is encrypted inside the Batch account. By default, accounts are encrypted using a Microsoft managed key. For additional control, a customer-managed key can be used instead. :paramtype encryption: ~azure.mgmt.batch.models.EncryptionProperties :keyword allowed_authentication_modes: List of allowed authentication modes for the Batch account that can be used to authenticate with the data plane. This does not affect authentication with the control plane. :paramtype allowed_authentication_modes: list[str or ~azure.mgmt.batch.models.AuthenticationMode] """ super().__init__(**kwargs) self.location = location self.tags = tags self.identity = identity self.auto_storage = auto_storage self.pool_allocation_mode = pool_allocation_mode self.key_vault_reference = key_vault_reference self.public_network_access = public_network_access self.network_profile = network_profile self.encryption = encryption self.allowed_authentication_modes = allowed_authentication_modes class BatchAccountIdentity(_serialization.Model): """The identity of the Batch account, if configured. This is used when the user specifies 'Microsoft.KeyVault' as their Batch account encryption configuration or when ``ManagedIdentity`` is selected as the auto-storage authentication mode. Variables are only populated by the server, and will be ignored when sending a request. All required parameters must be populated in order to send to Azure. :ivar principal_id: The principal id of the Batch account. This property will only be provided for a system assigned identity. :vartype principal_id: str :ivar tenant_id: The tenant id associated with the Batch account. This property will only be provided for a system assigned identity. :vartype tenant_id: str :ivar type: The type of identity used for the Batch account. Required. Known values are: "SystemAssigned", "UserAssigned", and "None". :vartype type: str or ~azure.mgmt.batch.models.ResourceIdentityType :ivar user_assigned_identities: The list of user identities associated with the Batch account. :vartype user_assigned_identities: dict[str, ~azure.mgmt.batch.models.UserAssignedIdentities] """ _validation = { "principal_id": {"readonly": True}, "tenant_id": {"readonly": True}, "type": {"required": True}, } _attribute_map = { "principal_id": {"key": "principalId", "type": "str"}, "tenant_id": {"key": "tenantId", "type": "str"}, "type": {"key": "type", "type": "str"}, "user_assigned_identities": {"key": "userAssignedIdentities", "type": "{UserAssignedIdentities}"}, } def __init__( self, *, type: Union[str, "_models.ResourceIdentityType"], user_assigned_identities: Optional[Dict[str, "_models.UserAssignedIdentities"]] = None, **kwargs: Any ) -> None: """ :keyword type: The type of identity used for the Batch account. Required. Known values are: "SystemAssigned", "UserAssigned", and "None". :paramtype type: str or ~azure.mgmt.batch.models.ResourceIdentityType :keyword user_assigned_identities: The list of user identities associated with the Batch account. :paramtype user_assigned_identities: dict[str, ~azure.mgmt.batch.models.UserAssignedIdentities] """ super().__init__(**kwargs) self.principal_id = None self.tenant_id = None self.type = type self.user_assigned_identities = user_assigned_identities class BatchAccountKeys(_serialization.Model): """A set of Azure Batch account keys. Variables are only populated by the server, and will be ignored when sending a request. :ivar account_name: The Batch account name. :vartype account_name: str :ivar primary: The primary key associated with the account. :vartype primary: str :ivar secondary: The secondary key associated with the account. :vartype secondary: str """ _validation = { "account_name": {"readonly": True}, "primary": {"readonly": True}, "secondary": {"readonly": True}, } _attribute_map = { "account_name": {"key": "accountName", "type": "str"}, "primary": {"key": "primary", "type": "str"}, "secondary": {"key": "secondary", "type": "str"}, } def __init__(self, **kwargs: Any) -> None: """ """ super().__init__(**kwargs) self.account_name = None self.primary = None self.secondary = None class BatchAccountListResult(_serialization.Model): """Values returned by the List operation. :ivar value: The collection of Batch accounts returned by the listing operation. :vartype value: list[~azure.mgmt.batch.models.BatchAccount] :ivar next_link: The continuation token. :vartype next_link: str """ _attribute_map = { "value": {"key": "value", "type": "[BatchAccount]"}, "next_link": {"key": "nextLink", "type": "str"}, } def __init__( self, *, value: Optional[List["_models.BatchAccount"]] = None, next_link: Optional[str] = None, **kwargs: Any ) -> None: """ :keyword value: The collection of Batch accounts returned by the listing operation. :paramtype value: list[~azure.mgmt.batch.models.BatchAccount] :keyword next_link: The continuation token. :paramtype next_link: str """ super().__init__(**kwargs) self.value = value self.next_link = next_link class BatchAccountRegenerateKeyParameters(_serialization.Model): """Parameters supplied to the RegenerateKey operation. All required parameters must be populated in order to send to Azure. :ivar key_name: The type of account key to regenerate. Required. Known values are: "Primary" and "Secondary". :vartype key_name: str or ~azure.mgmt.batch.models.AccountKeyType """ _validation = { "key_name": {"required": True}, } _attribute_map = { "key_name": {"key": "keyName", "type": "str"}, } def __init__(self, *, key_name: Union[str, "_models.AccountKeyType"], **kwargs: Any) -> None: """ :keyword key_name: The type of account key to regenerate. Required. Known values are: "Primary" and "Secondary". :paramtype key_name: str or ~azure.mgmt.batch.models.AccountKeyType """ super().__init__(**kwargs) self.key_name = key_name class BatchAccountUpdateParameters(_serialization.Model): """Parameters for updating an Azure Batch account. :ivar tags: The user-specified tags associated with the account. :vartype tags: dict[str, str] :ivar identity: The identity of the Batch account. :vartype identity: ~azure.mgmt.batch.models.BatchAccountIdentity :ivar auto_storage: The properties related to the auto-storage account. :vartype auto_storage: ~azure.mgmt.batch.models.AutoStorageBaseProperties :ivar encryption: Configures how customer data is encrypted inside the Batch account. By default, accounts are encrypted using a Microsoft managed key. For additional control, a customer-managed key can be used instead. :vartype encryption: ~azure.mgmt.batch.models.EncryptionProperties :ivar allowed_authentication_modes: List of allowed authentication modes for the Batch account that can be used to authenticate with the data plane. This does not affect authentication with the control plane. :vartype allowed_authentication_modes: list[str or ~azure.mgmt.batch.models.AuthenticationMode] :ivar public_network_access: If not specified, the default value is 'enabled'. Known values are: "Enabled" and "Disabled". :vartype public_network_access: str or ~azure.mgmt.batch.models.PublicNetworkAccessType :ivar network_profile: The network profile only takes effect when publicNetworkAccess is enabled. :vartype network_profile: ~azure.mgmt.batch.models.NetworkProfile """ _attribute_map = { "tags": {"key": "tags", "type": "{str}"}, "identity": {"key": "identity", "type": "BatchAccountIdentity"}, "auto_storage": {"key": "properties.autoStorage", "type": "AutoStorageBaseProperties"}, "encryption": {"key": "properties.encryption", "type": "EncryptionProperties"}, "allowed_authentication_modes": {"key": "properties.allowedAuthenticationModes", "type": "[str]"}, "public_network_access": {"key": "properties.publicNetworkAccess", "type": "str"}, "network_profile": {"key": "properties.networkProfile", "type": "NetworkProfile"}, } def __init__( self, *, tags: Optional[Dict[str, str]] = None, identity: Optional["_models.BatchAccountIdentity"] = None, auto_storage: Optional["_models.AutoStorageBaseProperties"] = None, encryption: Optional["_models.EncryptionProperties"] = None, allowed_authentication_modes: Optional[List[Union[str, "_models.AuthenticationMode"]]] = None, public_network_access: Union[str, "_models.PublicNetworkAccessType"] = "Enabled", network_profile: Optional["_models.NetworkProfile"] = None, **kwargs: Any ) -> None: """ :keyword tags: The user-specified tags associated with the account. :paramtype tags: dict[str, str] :keyword identity: The identity of the Batch account. :paramtype identity: ~azure.mgmt.batch.models.BatchAccountIdentity :keyword auto_storage: The properties related to the auto-storage account. :paramtype auto_storage: ~azure.mgmt.batch.models.AutoStorageBaseProperties :keyword encryption: Configures how customer data is encrypted inside the Batch account. By default, accounts are encrypted using a Microsoft managed key. For additional control, a customer-managed key can be used instead. :paramtype encryption: ~azure.mgmt.batch.models.EncryptionProperties :keyword allowed_authentication_modes: List of allowed authentication modes for the Batch account that can be used to authenticate with the data plane. This does not affect authentication with the control plane. :paramtype allowed_authentication_modes: list[str or ~azure.mgmt.batch.models.AuthenticationMode] :keyword public_network_access: If not specified, the default value is 'enabled'. Known values are: "Enabled" and "Disabled". :paramtype public_network_access: str or ~azure.mgmt.batch.models.PublicNetworkAccessType :keyword network_profile: The network profile only takes effect when publicNetworkAccess is enabled. :paramtype network_profile: ~azure.mgmt.batch.models.NetworkProfile """ super().__init__(**kwargs) self.tags = tags self.identity = identity self.auto_storage = auto_storage self.encryption = encryption self.allowed_authentication_modes = allowed_authentication_modes self.public_network_access = public_network_access self.network_profile = network_profile class BatchLocationQuota(_serialization.Model): """Quotas associated with a Batch region for a particular subscription. Variables are only populated by the server, and will be ignored when sending a request. :ivar account_quota: The number of Batch accounts that may be created under the subscription in the specified region. :vartype account_quota: int """ _validation = { "account_quota": {"readonly": True}, } _attribute_map = { "account_quota": {"key": "accountQuota", "type": "int"}, } def __init__(self, **kwargs: Any) -> None: """ """ super().__init__(**kwargs) self.account_quota = None class BatchPoolIdentity(_serialization.Model): """The identity of the Batch pool, if configured. If the pool identity is updated during update an existing pool, only the new vms which are created after the pool shrinks to 0 will have the updated identities. All required parameters must be populated in order to send to Azure. :ivar type: The type of identity used for the Batch Pool. Required. Known values are: "UserAssigned" and "None". :vartype type: str or ~azure.mgmt.batch.models.PoolIdentityType :ivar user_assigned_identities: The list of user identities associated with the Batch pool. :vartype user_assigned_identities: dict[str, ~azure.mgmt.batch.models.UserAssignedIdentities] """ _validation = { "type": {"required": True}, } _attribute_map = { "type": {"key": "type", "type": "str"}, "user_assigned_identities": {"key": "userAssignedIdentities", "type": "{UserAssignedIdentities}"}, } def __init__( self, *, type: Union[str, "_models.PoolIdentityType"], user_assigned_identities: Optional[Dict[str, "_models.UserAssignedIdentities"]] = None, **kwargs: Any ) -> None: """ :keyword type: The type of identity used for the Batch Pool. Required. Known values are: "UserAssigned" and "None". :paramtype type: str or ~azure.mgmt.batch.models.PoolIdentityType :keyword user_assigned_identities: The list of user identities associated with the Batch pool. :paramtype user_assigned_identities: dict[str, ~azure.mgmt.batch.models.UserAssignedIdentities] """ super().__init__(**kwargs) self.type = type self.user_assigned_identities = user_assigned_identities class Certificate(ProxyResource): # pylint: disable=too-many-instance-attributes """Contains information about a certificate. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: The ID of the resource. :vartype id: str :ivar name: The name of the resource. :vartype name: str :ivar type: The type of the resource. :vartype type: str :ivar etag: The ETag of the resource, used for concurrency statements. :vartype etag: str :ivar thumbprint_algorithm: This must match the first portion of the certificate name. Currently required to be 'SHA1'. :vartype thumbprint_algorithm: str :ivar thumbprint: This must match the thumbprint from the name. :vartype thumbprint: str :ivar format: The format of the certificate - either Pfx or Cer. If omitted, the default is Pfx. Known values are: "Pfx" and "Cer". :vartype format: str or ~azure.mgmt.batch.models.CertificateFormat :ivar provisioning_state: Known values are: "Succeeded", "Deleting", and "Failed". :vartype provisioning_state: str or ~azure.mgmt.batch.models.CertificateProvisioningState :ivar provisioning_state_transition_time: The time at which the certificate entered its current state. :vartype provisioning_state_transition_time: ~datetime.datetime :ivar previous_provisioning_state: The previous provisioned state of the resource. Known values are: "Succeeded", "Deleting", and "Failed". :vartype previous_provisioning_state: str or ~azure.mgmt.batch.models.CertificateProvisioningState :ivar previous_provisioning_state_transition_time: The time at which the certificate entered its previous state. :vartype previous_provisioning_state_transition_time: ~datetime.datetime :ivar public_data: The public key of the certificate. :vartype public_data: str :ivar delete_certificate_error: This is only returned when the certificate provisioningState is 'Failed'. :vartype delete_certificate_error: ~azure.mgmt.batch.models.DeleteCertificateError """ _validation = { "id": {"readonly": True}, "name": {"readonly": True}, "type": {"readonly": True}, "etag": {"readonly": True}, "provisioning_state": {"readonly": True}, "provisioning_state_transition_time": {"readonly": True}, "previous_provisioning_state": {"readonly": True}, "previous_provisioning_state_transition_time": {"readonly": True}, "public_data": {"readonly": True}, "delete_certificate_error": {"readonly": True}, } _attribute_map = { "id": {"key": "id", "type": "str"}, "name": {"key": "name", "type": "str"}, "type": {"key": "type", "type": "str"}, "etag": {"key": "etag", "type": "str"}, "thumbprint_algorithm": {"key": "properties.thumbprintAlgorithm", "type": "str"}, "thumbprint": {"key": "properties.thumbprint", "type": "str"}, "format": {"key": "properties.format", "type": "str"}, "provisioning_state": {"key": "properties.provisioningState", "type": "str"}, "provisioning_state_transition_time": {"key": "properties.provisioningStateTransitionTime", "type": "iso-8601"}, "previous_provisioning_state": {"key": "properties.previousProvisioningState", "type": "str"}, "previous_provisioning_state_transition_time": { "key": "properties.previousProvisioningStateTransitionTime", "type": "iso-8601", }, "public_data": {"key": "properties.publicData", "type": "str"}, "delete_certificate_error": {"key": "properties.deleteCertificateError", "type": "DeleteCertificateError"}, } def __init__( self, *, thumbprint_algorithm: Optional[str] = None, thumbprint: Optional[str] = None, format: Optional[Union[str, "_models.CertificateFormat"]] = None, **kwargs: Any ) -> None: """ :keyword thumbprint_algorithm: This must match the first portion of the certificate name. Currently required to be 'SHA1'. :paramtype thumbprint_algorithm: str :keyword thumbprint: This must match the thumbprint from the name. :paramtype thumbprint: str :keyword format: The format of the certificate - either Pfx or Cer. If omitted, the default is Pfx. Known values are: "Pfx" and "Cer". :paramtype format: str or ~azure.mgmt.batch.models.CertificateFormat """ super().__init__(**kwargs) self.thumbprint_algorithm = thumbprint_algorithm self.thumbprint = thumbprint self.format = format self.provisioning_state = None self.provisioning_state_transition_time = None self.previous_provisioning_state = None self.previous_provisioning_state_transition_time = None self.public_data = None self.delete_certificate_error = None class CertificateBaseProperties(_serialization.Model): """Base certificate properties. :ivar thumbprint_algorithm: This must match the first portion of the certificate name. Currently required to be 'SHA1'. :vartype thumbprint_algorithm: str :ivar thumbprint: This must match the thumbprint from the name. :vartype thumbprint: str :ivar format: The format of the certificate - either Pfx or Cer. If omitted, the default is Pfx. Known values are: "Pfx" and "Cer". :vartype format: str or ~azure.mgmt.batch.models.CertificateFormat """ _attribute_map = { "thumbprint_algorithm": {"key": "thumbprintAlgorithm", "type": "str"}, "thumbprint": {"key": "thumbprint", "type": "str"}, "format": {"key": "format", "type": "str"}, } def __init__( self, *, thumbprint_algorithm: Optional[str] = None, thumbprint: Optional[str] = None, format: Optional[Union[str, "_models.CertificateFormat"]] = None, **kwargs: Any ) -> None: """ :keyword thumbprint_algorithm: This must match the first portion of the certificate name. Currently required to be 'SHA1'. :paramtype thumbprint_algorithm: str :keyword thumbprint: This must match the thumbprint from the name. :paramtype thumbprint: str :keyword format: The format of the certificate - either Pfx or Cer. If omitted, the default is Pfx. Known values are: "Pfx" and "Cer". :paramtype format: str or ~azure.mgmt.batch.models.CertificateFormat """ super().__init__(**kwargs) self.thumbprint_algorithm = thumbprint_algorithm self.thumbprint = thumbprint self.format = format class CertificateCreateOrUpdateParameters(ProxyResource): """Contains information about a certificate. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: The ID of the resource. :vartype id: str :ivar name: The name of the resource. :vartype name: str :ivar type: The type of the resource. :vartype type: str :ivar etag: The ETag of the resource, used for concurrency statements. :vartype etag: str :ivar thumbprint_algorithm: This must match the first portion of the certificate name. Currently required to be 'SHA1'. :vartype thumbprint_algorithm: str :ivar thumbprint: This must match the thumbprint from the name. :vartype thumbprint: str :ivar format: The format of the certificate - either Pfx or Cer. If omitted, the default is Pfx. Known values are: "Pfx" and "Cer". :vartype format: str or ~azure.mgmt.batch.models.CertificateFormat :ivar data: The maximum size is 10KB. :vartype data: str :ivar password: This must not be specified if the certificate format is Cer. :vartype password: str """ _validation = { "id": {"readonly": True}, "name": {"readonly": True}, "type": {"readonly": True}, "etag": {"readonly": True}, } _attribute_map = { "id": {"key": "id", "type": "str"}, "name": {"key": "name", "type": "str"}, "type": {"key": "type", "type": "str"}, "etag": {"key": "etag", "type": "str"}, "thumbprint_algorithm": {"key": "properties.thumbprintAlgorithm", "type": "str"}, "thumbprint": {"key": "properties.thumbprint", "type": "str"}, "format": {"key": "properties.format", "type": "str"}, "data": {"key": "properties.data", "type": "str"}, "password": {"key": "properties.password", "type": "str"}, } def __init__( self, *, thumbprint_algorithm: Optional[str] = None, thumbprint: Optional[str] = None, format: Optional[Union[str, "_models.CertificateFormat"]] = None, data: Optional[str] = None, password: Optional[str] = None, **kwargs: Any ) -> None: """ :keyword thumbprint_algorithm: This must match the first portion of the certificate name. Currently required to be 'SHA1'. :paramtype thumbprint_algorithm: str :keyword thumbprint: This must match the thumbprint from the name. :paramtype thumbprint: str :keyword format: The format of the certificate - either Pfx or Cer. If omitted, the default is Pfx. Known values are: "Pfx" and "Cer". :paramtype format: str or ~azure.mgmt.batch.models.CertificateFormat :keyword data: The maximum size is 10KB. :paramtype data: str :keyword password: This must not be specified if the certificate format is Cer. :paramtype password: str """ super().__init__(**kwargs) self.thumbprint_algorithm = thumbprint_algorithm self.thumbprint = thumbprint self.format = format self.data = data self.password = password class CertificateCreateOrUpdateProperties(CertificateBaseProperties): """Certificate properties for create operations. All required parameters must be populated in order to send to Azure. :ivar thumbprint_algorithm: This must match the first portion of the certificate name. Currently required to be 'SHA1'. :vartype thumbprint_algorithm: str :ivar thumbprint: This must match the thumbprint from the name. :vartype thumbprint: str :ivar format: The format of the certificate - either Pfx or Cer. If omitted, the default is Pfx. Known values are: "Pfx" and "Cer". :vartype format: str or ~azure.mgmt.batch.models.CertificateFormat :ivar data: The maximum size is 10KB. Required. :vartype data: str :ivar password: This must not be specified if the certificate format is Cer. :vartype password: str """ _validation = { "data": {"required": True}, } _attribute_map = { "thumbprint_algorithm": {"key": "thumbprintAlgorithm", "type": "str"}, "thumbprint": {"key": "thumbprint", "type": "str"}, "format": {"key": "format", "type": "str"}, "data": {"key": "data", "type": "str"}, "password": {"key": "password", "type": "str"}, } def __init__( self, *, data: str, thumbprint_algorithm: Optional[str] = None, thumbprint: Optional[str] = None, format: Optional[Union[str, "_models.CertificateFormat"]] = None, password: Optional[str] = None, **kwargs: Any ) -> None: """ :keyword thumbprint_algorithm: This must match the first portion of the certificate name. Currently required to be 'SHA1'. :paramtype thumbprint_algorithm: str :keyword thumbprint: This must match the thumbprint from the name. :paramtype thumbprint: str :keyword format: The format of the certificate - either Pfx or Cer. If omitted, the default is Pfx. Known values are: "Pfx" and "Cer". :paramtype format: str or ~azure.mgmt.batch.models.CertificateFormat :keyword data: The maximum size is 10KB. Required. :paramtype data: str :keyword password: This must not be specified if the certificate format is Cer. :paramtype password: str """ super().__init__(thumbprint_algorithm=thumbprint_algorithm, thumbprint=thumbprint, format=format, **kwargs) self.data = data self.password = password class CertificateProperties(CertificateBaseProperties): """Certificate properties. Variables are only populated by the server, and will be ignored when sending a request. :ivar thumbprint_algorithm: This must match the first portion of the certificate name. Currently required to be 'SHA1'. :vartype thumbprint_algorithm: str :ivar thumbprint: This must match the thumbprint from the name. :vartype thumbprint: str :ivar format: The format of the certificate - either Pfx or Cer. If omitted, the default is Pfx. Known values are: "Pfx" and "Cer". :vartype format: str or ~azure.mgmt.batch.models.CertificateFormat :ivar provisioning_state: Known values are: "Succeeded", "Deleting", and "Failed". :vartype provisioning_state: str or ~azure.mgmt.batch.models.CertificateProvisioningState :ivar provisioning_state_transition_time: The time at which the certificate entered its current state. :vartype provisioning_state_transition_time: ~datetime.datetime :ivar previous_provisioning_state: The previous provisioned state of the resource. Known values are: "Succeeded", "Deleting", and "Failed". :vartype previous_provisioning_state: str or ~azure.mgmt.batch.models.CertificateProvisioningState :ivar previous_provisioning_state_transition_time: The time at which the certificate entered its previous state. :vartype previous_provisioning_state_transition_time: ~datetime.datetime :ivar public_data: The public key of the certificate. :vartype public_data: str :ivar delete_certificate_error: This is only returned when the certificate provisioningState is 'Failed'. :vartype delete_certificate_error: ~azure.mgmt.batch.models.DeleteCertificateError """ _validation = { "provisioning_state": {"readonly": True}, "provisioning_state_transition_time": {"readonly": True}, "previous_provisioning_state": {"readonly": True}, "previous_provisioning_state_transition_time": {"readonly": True}, "public_data": {"readonly": True}, "delete_certificate_error": {"readonly": True}, } _attribute_map = { "thumbprint_algorithm": {"key": "thumbprintAlgorithm", "type": "str"}, "thumbprint": {"key": "thumbprint", "type": "str"}, "format": {"key": "format", "type": "str"}, "provisioning_state": {"key": "provisioningState", "type": "str"}, "provisioning_state_transition_time": {"key": "provisioningStateTransitionTime", "type": "iso-8601"}, "previous_provisioning_state": {"key": "previousProvisioningState", "type": "str"}, "previous_provisioning_state_transition_time": { "key": "previousProvisioningStateTransitionTime", "type": "iso-8601", }, "public_data": {"key": "publicData", "type": "str"}, "delete_certificate_error": {"key": "deleteCertificateError", "type": "DeleteCertificateError"}, } def __init__( self, *, thumbprint_algorithm: Optional[str] = None, thumbprint: Optional[str] = None, format: Optional[Union[str, "_models.CertificateFormat"]] = None, **kwargs: Any ) -> None: """ :keyword thumbprint_algorithm: This must match the first portion of the certificate name. Currently required to be 'SHA1'. :paramtype thumbprint_algorithm: str :keyword thumbprint: This must match the thumbprint from the name. :paramtype thumbprint: str :keyword format: The format of the certificate - either Pfx or Cer. If omitted, the default is Pfx. Known values are: "Pfx" and "Cer". :paramtype format: str or ~azure.mgmt.batch.models.CertificateFormat """ super().__init__(thumbprint_algorithm=thumbprint_algorithm, thumbprint=thumbprint, format=format, **kwargs) self.provisioning_state = None self.provisioning_state_transition_time = None self.previous_provisioning_state = None self.previous_provisioning_state_transition_time = None self.public_data = None self.delete_certificate_error = None class CertificateReference(_serialization.Model): """Warning: This object is deprecated and will be removed after February, 2024. Please use the `Azure KeyVault Extension <https://learn.microsoft.com/azure/batch/batch-certificate-migration-guide>`_ instead. All required parameters must be populated in order to send to Azure. :ivar id: The fully qualified ID of the certificate to install on the pool. This must be inside the same batch account as the pool. Required. :vartype id: str :ivar store_location: The default value is currentUser. This property is applicable only for pools configured with Windows nodes (that is, created with cloudServiceConfiguration, or with virtualMachineConfiguration using a Windows image reference). For Linux compute nodes, the certificates are stored in a directory inside the task working directory and an environment variable AZ_BATCH_CERTIFICATES_DIR is supplied to the task to query for this location. For certificates with visibility of 'remoteUser', a 'certs' directory is created in the user's home directory (e.g., /home/{user-name}/certs) and certificates are placed in that directory. Known values are: "CurrentUser" and "LocalMachine". :vartype store_location: str or ~azure.mgmt.batch.models.CertificateStoreLocation :ivar store_name: This property is applicable only for pools configured with Windows nodes (that is, created with cloudServiceConfiguration, or with virtualMachineConfiguration using a Windows image reference). Common store names include: My, Root, CA, Trust, Disallowed, TrustedPeople, TrustedPublisher, AuthRoot, AddressBook, but any custom store name can also be used. The default value is My. :vartype store_name: str :ivar visibility: Which user accounts on the compute node should have access to the private data of the certificate. :vartype visibility: list[str or ~azure.mgmt.batch.models.CertificateVisibility] """ _validation = { "id": {"required": True}, } _attribute_map = { "id": {"key": "id", "type": "str"}, "store_location": {"key": "storeLocation", "type": "str"}, "store_name": {"key": "storeName", "type": "str"}, "visibility": {"key": "visibility", "type": "[str]"}, } def __init__( self, *, id: str, # pylint: disable=redefined-builtin store_location: Optional[Union[str, "_models.CertificateStoreLocation"]] = None, store_name: Optional[str] = None, visibility: Optional[List[Union[str, "_models.CertificateVisibility"]]] = None, **kwargs: Any ) -> None: """ :keyword id: The fully qualified ID of the certificate to install on the pool. This must be inside the same batch account as the pool. Required. :paramtype id: str :keyword store_location: The default value is currentUser. This property is applicable only for pools configured with Windows nodes (that is, created with cloudServiceConfiguration, or with virtualMachineConfiguration using a Windows image reference). For Linux compute nodes, the certificates are stored in a directory inside the task working directory and an environment variable AZ_BATCH_CERTIFICATES_DIR is supplied to the task to query for this location. For certificates with visibility of 'remoteUser', a 'certs' directory is created in the user's home directory (e.g., /home/{user-name}/certs) and certificates are placed in that directory. Known values are: "CurrentUser" and "LocalMachine". :paramtype store_location: str or ~azure.mgmt.batch.models.CertificateStoreLocation :keyword store_name: This property is applicable only for pools configured with Windows nodes (that is, created with cloudServiceConfiguration, or with virtualMachineConfiguration using a Windows image reference). Common store names include: My, Root, CA, Trust, Disallowed, TrustedPeople, TrustedPublisher, AuthRoot, AddressBook, but any custom store name can also be used. The default value is My. :paramtype store_name: str :keyword visibility: Which user accounts on the compute node should have access to the private data of the certificate. :paramtype visibility: list[str or ~azure.mgmt.batch.models.CertificateVisibility] """ super().__init__(**kwargs) self.id = id self.store_location = store_location self.store_name = store_name self.visibility = visibility class CheckNameAvailabilityParameters(_serialization.Model): """Parameters for a check name availability request. Variables are only populated by the server, and will be ignored when sending a request. All required parameters must be populated in order to send to Azure. :ivar name: The name to check for availability. Required. :vartype name: str :ivar type: The resource type. Required. Default value is "Microsoft.Batch/batchAccounts". :vartype type: str """ _validation = { "name": {"required": True}, "type": {"required": True, "constant": True}, } _attribute_map = { "name": {"key": "name", "type": "str"}, "type": {"key": "type", "type": "str"}, } type = "Microsoft.Batch/batchAccounts" def __init__(self, *, name: str, **kwargs: Any) -> None: """ :keyword name: The name to check for availability. Required. :paramtype name: str """ super().__init__(**kwargs) self.name = name class CheckNameAvailabilityResult(_serialization.Model): """The CheckNameAvailability operation response. Variables are only populated by the server, and will be ignored when sending a request. :ivar name_available: Gets a boolean value that indicates whether the name is available for you to use. If true, the name is available. If false, the name has already been taken or invalid and cannot be used. :vartype name_available: bool :ivar reason: Gets the reason that a Batch account name could not be used. The Reason element is only returned if NameAvailable is false. Known values are: "Invalid" and "AlreadyExists". :vartype reason: str or ~azure.mgmt.batch.models.NameAvailabilityReason :ivar message: Gets an error message explaining the Reason value in more detail. :vartype message: str """ _validation = { "name_available": {"readonly": True}, "reason": {"readonly": True}, "message": {"readonly": True}, } _attribute_map = { "name_available": {"key": "nameAvailable", "type": "bool"}, "reason": {"key": "reason", "type": "str"}, "message": {"key": "message", "type": "str"}, } def __init__(self, **kwargs: Any) -> None: """ """ super().__init__(**kwargs) self.name_available = None self.reason = None self.message = None class CIFSMountConfiguration(_serialization.Model): """Information used to connect to a CIFS file system. All required parameters must be populated in order to send to Azure. :ivar user_name: The user to use for authentication against the CIFS file system. Required. :vartype user_name: str :ivar source: The URI of the file system to mount. Required. :vartype source: str :ivar relative_mount_path: All file systems are mounted relative to the Batch mounts directory, accessible via the AZ_BATCH_NODE_MOUNTS_DIR environment variable. Required. :vartype relative_mount_path: str :ivar mount_options: These are 'net use' options in Windows and 'mount' options in Linux. :vartype mount_options: str :ivar password: The password to use for authentication against the CIFS file system. Required. :vartype password: str """ _validation = { "user_name": {"required": True}, "source": {"required": True}, "relative_mount_path": {"required": True}, "password": {"required": True}, } _attribute_map = { "user_name": {"key": "userName", "type": "str"}, "source": {"key": "source", "type": "str"}, "relative_mount_path": {"key": "relativeMountPath", "type": "str"}, "mount_options": {"key": "mountOptions", "type": "str"}, "password": {"key": "password", "type": "str"}, } def __init__( self, *, user_name: str, source: str, relative_mount_path: str, password: str, mount_options: Optional[str] = None, **kwargs: Any ) -> None: """ :keyword user_name: The user to use for authentication against the CIFS file system. Required. :paramtype user_name: str :keyword source: The URI of the file system to mount. Required. :paramtype source: str :keyword relative_mount_path: All file systems are mounted relative to the Batch mounts directory, accessible via the AZ_BATCH_NODE_MOUNTS_DIR environment variable. Required. :paramtype relative_mount_path: str :keyword mount_options: These are 'net use' options in Windows and 'mount' options in Linux. :paramtype mount_options: str :keyword password: The password to use for authentication against the CIFS file system. Required. :paramtype password: str """ super().__init__(**kwargs) self.user_name = user_name self.source = source self.relative_mount_path = relative_mount_path self.mount_options = mount_options self.password = password class CloudErrorBody(_serialization.Model): """An error response from the Batch service. :ivar code: An identifier for the error. Codes are invariant and are intended to be consumed programmatically. :vartype code: str :ivar message: A message describing the error, intended to be suitable for display in a user interface. :vartype message: str :ivar target: The target of the particular error. For example, the name of the property in error. :vartype target: str :ivar details: A list of additional details about the error. :vartype details: list[~azure.mgmt.batch.models.CloudErrorBody] """ _attribute_map = { "code": {"key": "code", "type": "str"}, "message": {"key": "message", "type": "str"}, "target": {"key": "target", "type": "str"}, "details": {"key": "details", "type": "[CloudErrorBody]"}, } def __init__( self, *, code: Optional[str] = None, message: Optional[str] = None, target: Optional[str] = None, details: Optional[List["_models.CloudErrorBody"]] = None, **kwargs: Any ) -> None: """ :keyword code: An identifier for the error. Codes are invariant and are intended to be consumed programmatically. :paramtype code: str :keyword message: A message describing the error, intended to be suitable for display in a user interface. :paramtype message: str :keyword target: The target of the particular error. For example, the name of the property in error. :paramtype target: str :keyword details: A list of additional details about the error. :paramtype details: list[~azure.mgmt.batch.models.CloudErrorBody] """ super().__init__(**kwargs) self.code = code self.message = message self.target = target self.details = details class CloudServiceConfiguration(_serialization.Model): """The configuration for nodes in a pool based on the Azure Cloud Services platform. All required parameters must be populated in order to send to Azure. :ivar os_family: Possible values are: 2 - OS Family 2, equivalent to Windows Server 2008 R2 SP1. 3 - OS Family 3, equivalent to Windows Server 2012. 4 - OS Family 4, equivalent to Windows Server 2012 R2. 5 - OS Family 5, equivalent to Windows Server 2016. 6 - OS Family 6, equivalent to Windows Server 2019. For more information, see Azure Guest OS Releases (https://azure.microsoft.com/documentation/articles/cloud-services-guestos-update-matrix/#releases). Required. :vartype os_family: str :ivar os_version: The default value is * which specifies the latest operating system version for the specified OS family. :vartype os_version: str """ _validation = { "os_family": {"required": True}, } _attribute_map = { "os_family": {"key": "osFamily", "type": "str"}, "os_version": {"key": "osVersion", "type": "str"}, } def __init__(self, *, os_family: str, os_version: Optional[str] = None, **kwargs: Any) -> None: """ :keyword os_family: Possible values are: 2 - OS Family 2, equivalent to Windows Server 2008 R2 SP1. 3 - OS Family 3, equivalent to Windows Server 2012. 4 - OS Family 4, equivalent to Windows Server 2012 R2. 5 - OS Family 5, equivalent to Windows Server 2016. 6 - OS Family 6, equivalent to Windows Server 2019. For more information, see Azure Guest OS Releases (https://azure.microsoft.com/documentation/articles/cloud-services-guestos-update-matrix/#releases). Required. :paramtype os_family: str :keyword os_version: The default value is * which specifies the latest operating system version for the specified OS family. :paramtype os_version: str """ super().__init__(**kwargs) self.os_family = os_family self.os_version = os_version class ComputeNodeIdentityReference(_serialization.Model): """The reference to a user assigned identity associated with the Batch pool which a compute node will use. :ivar resource_id: The ARM resource id of the user assigned identity. :vartype resource_id: str """ _attribute_map = { "resource_id": {"key": "resourceId", "type": "str"}, } def __init__(self, *, resource_id: Optional[str] = None, **kwargs: Any) -> None: """ :keyword resource_id: The ARM resource id of the user assigned identity. :paramtype resource_id: str """ super().__init__(**kwargs) self.resource_id = resource_id class ContainerConfiguration(_serialization.Model): """The configuration for container-enabled pools. All required parameters must be populated in order to send to Azure. :ivar type: The container technology to be used. Required. Known values are: "DockerCompatible" and "CriCompatible". :vartype type: str or ~azure.mgmt.batch.models.ContainerType :ivar container_image_names: This is the full image reference, as would be specified to "docker pull". An image will be sourced from the default Docker registry unless the image is fully qualified with an alternative registry. :vartype container_image_names: list[str] :ivar container_registries: If any images must be downloaded from a private registry which requires credentials, then those credentials must be provided here. :vartype container_registries: list[~azure.mgmt.batch.models.ContainerRegistry] """ _validation = { "type": {"required": True}, } _attribute_map = { "type": {"key": "type", "type": "str"}, "container_image_names": {"key": "containerImageNames", "type": "[str]"}, "container_registries": {"key": "containerRegistries", "type": "[ContainerRegistry]"}, } def __init__( self, *, type: Union[str, "_models.ContainerType"], container_image_names: Optional[List[str]] = None, container_registries: Optional[List["_models.ContainerRegistry"]] = None, **kwargs: Any ) -> None: """ :keyword type: The container technology to be used. Required. Known values are: "DockerCompatible" and "CriCompatible". :paramtype type: str or ~azure.mgmt.batch.models.ContainerType :keyword container_image_names: This is the full image reference, as would be specified to "docker pull". An image will be sourced from the default Docker registry unless the image is fully qualified with an alternative registry. :paramtype container_image_names: list[str] :keyword container_registries: If any images must be downloaded from a private registry which requires credentials, then those credentials must be provided here. :paramtype container_registries: list[~azure.mgmt.batch.models.ContainerRegistry] """ super().__init__(**kwargs) self.type = type self.container_image_names = container_image_names self.container_registries = container_registries class ContainerRegistry(_serialization.Model): """A private container registry. :ivar user_name: The user name to log into the registry server. :vartype user_name: str :ivar password: The password to log into the registry server. :vartype password: str :ivar registry_server: If omitted, the default is "docker.io". :vartype registry_server: str :ivar identity_reference: The reference to a user assigned identity associated with the Batch pool which a compute node will use. :vartype identity_reference: ~azure.mgmt.batch.models.ComputeNodeIdentityReference """ _attribute_map = { "user_name": {"key": "username", "type": "str"}, "password": {"key": "password", "type": "str"}, "registry_server": {"key": "registryServer", "type": "str"}, "identity_reference": {"key": "identityReference", "type": "ComputeNodeIdentityReference"}, } def __init__( self, *, user_name: Optional[str] = None, password: Optional[str] = None, registry_server: Optional[str] = None, identity_reference: Optional["_models.ComputeNodeIdentityReference"] = None, **kwargs: Any ) -> None: """ :keyword user_name: The user name to log into the registry server. :paramtype user_name: str :keyword password: The password to log into the registry server. :paramtype password: str :keyword registry_server: If omitted, the default is "docker.io". :paramtype registry_server: str :keyword identity_reference: The reference to a user assigned identity associated with the Batch pool which a compute node will use. :paramtype identity_reference: ~azure.mgmt.batch.models.ComputeNodeIdentityReference """ super().__init__(**kwargs) self.user_name = user_name self.password = password self.registry_server = registry_server self.identity_reference = identity_reference class DataDisk(_serialization.Model): """Settings which will be used by the data disks associated to Compute Nodes in the Pool. When using attached data disks, you need to mount and format the disks from within a VM to use them. All required parameters must be populated in order to send to Azure. :ivar lun: The lun is used to uniquely identify each data disk. If attaching multiple disks, each should have a distinct lun. The value must be between 0 and 63, inclusive. Required. :vartype lun: int :ivar caching: Values are: none - The caching mode for the disk is not enabled. readOnly - The caching mode for the disk is read only. readWrite - The caching mode for the disk is read and write. The default value for caching is none. For information about the caching options see: https://blogs.msdn.microsoft.com/windowsazurestorage/2012/06/27/exploring-windows-azure-drives-disks-and-images/. Known values are: "None", "ReadOnly", and "ReadWrite". :vartype caching: str or ~azure.mgmt.batch.models.CachingType :ivar disk_size_gb: The initial disk size in GB when creating new data disk. Required. :vartype disk_size_gb: int :ivar storage_account_type: If omitted, the default is "Standard_LRS". Values are: Standard_LRS - The data disk should use standard locally redundant storage. Premium_LRS - The data disk should use premium locally redundant storage. Known values are: "Standard_LRS" and "Premium_LRS". :vartype storage_account_type: str or ~azure.mgmt.batch.models.StorageAccountType """ _validation = { "lun": {"required": True}, "disk_size_gb": {"required": True}, } _attribute_map = { "lun": {"key": "lun", "type": "int"}, "caching": {"key": "caching", "type": "str"}, "disk_size_gb": {"key": "diskSizeGB", "type": "int"}, "storage_account_type": {"key": "storageAccountType", "type": "str"}, } def __init__( self, *, lun: int, disk_size_gb: int, caching: Optional[Union[str, "_models.CachingType"]] = None, storage_account_type: Optional[Union[str, "_models.StorageAccountType"]] = None, **kwargs: Any ) -> None: """ :keyword lun: The lun is used to uniquely identify each data disk. If attaching multiple disks, each should have a distinct lun. The value must be between 0 and 63, inclusive. Required. :paramtype lun: int :keyword caching: Values are: none - The caching mode for the disk is not enabled. readOnly - The caching mode for the disk is read only. readWrite - The caching mode for the disk is read and write. The default value for caching is none. For information about the caching options see: https://blogs.msdn.microsoft.com/windowsazurestorage/2012/06/27/exploring-windows-azure-drives-disks-and-images/. Known values are: "None", "ReadOnly", and "ReadWrite". :paramtype caching: str or ~azure.mgmt.batch.models.CachingType :keyword disk_size_gb: The initial disk size in GB when creating new data disk. Required. :paramtype disk_size_gb: int :keyword storage_account_type: If omitted, the default is "Standard_LRS". Values are: Standard_LRS - The data disk should use standard locally redundant storage. Premium_LRS - The data disk should use premium locally redundant storage. Known values are: "Standard_LRS" and "Premium_LRS". :paramtype storage_account_type: str or ~azure.mgmt.batch.models.StorageAccountType """ super().__init__(**kwargs) self.lun = lun self.caching = caching self.disk_size_gb = disk_size_gb self.storage_account_type = storage_account_type class DeleteCertificateError(_serialization.Model): """An error response from the Batch service. All required parameters must be populated in order to send to Azure. :ivar code: An identifier for the error. Codes are invariant and are intended to be consumed programmatically. Required. :vartype code: str :ivar message: A message describing the error, intended to be suitable for display in a user interface. Required. :vartype message: str :ivar target: The target of the particular error. For example, the name of the property in error. :vartype target: str :ivar details: A list of additional details about the error. :vartype details: list[~azure.mgmt.batch.models.DeleteCertificateError] """ _validation = { "code": {"required": True}, "message": {"required": True}, } _attribute_map = { "code": {"key": "code", "type": "str"}, "message": {"key": "message", "type": "str"}, "target": {"key": "target", "type": "str"}, "details": {"key": "details", "type": "[DeleteCertificateError]"}, } def __init__( self, *, code: str, message: str, target: Optional[str] = None, details: Optional[List["_models.DeleteCertificateError"]] = None, **kwargs: Any ) -> None: """ :keyword code: An identifier for the error. Codes are invariant and are intended to be consumed programmatically. Required. :paramtype code: str :keyword message: A message describing the error, intended to be suitable for display in a user interface. Required. :paramtype message: str :keyword target: The target of the particular error. For example, the name of the property in error. :paramtype target: str :keyword details: A list of additional details about the error. :paramtype details: list[~azure.mgmt.batch.models.DeleteCertificateError] """ super().__init__(**kwargs) self.code = code self.message = message self.target = target self.details = details class DeploymentConfiguration(_serialization.Model): """Deployment configuration properties. :ivar cloud_service_configuration: This property and virtualMachineConfiguration are mutually exclusive and one of the properties must be specified. This property cannot be specified if the Batch account was created with its poolAllocationMode property set to 'UserSubscription'. :vartype cloud_service_configuration: ~azure.mgmt.batch.models.CloudServiceConfiguration :ivar virtual_machine_configuration: This property and cloudServiceConfiguration are mutually exclusive and one of the properties must be specified. :vartype virtual_machine_configuration: ~azure.mgmt.batch.models.VirtualMachineConfiguration """ _attribute_map = { "cloud_service_configuration": {"key": "cloudServiceConfiguration", "type": "CloudServiceConfiguration"}, "virtual_machine_configuration": {"key": "virtualMachineConfiguration", "type": "VirtualMachineConfiguration"}, } def __init__( self, *, cloud_service_configuration: Optional["_models.CloudServiceConfiguration"] = None, virtual_machine_configuration: Optional["_models.VirtualMachineConfiguration"] = None, **kwargs: Any ) -> None: """ :keyword cloud_service_configuration: This property and virtualMachineConfiguration are mutually exclusive and one of the properties must be specified. This property cannot be specified if the Batch account was created with its poolAllocationMode property set to 'UserSubscription'. :paramtype cloud_service_configuration: ~azure.mgmt.batch.models.CloudServiceConfiguration :keyword virtual_machine_configuration: This property and cloudServiceConfiguration are mutually exclusive and one of the properties must be specified. :paramtype virtual_machine_configuration: ~azure.mgmt.batch.models.VirtualMachineConfiguration """ super().__init__(**kwargs) self.cloud_service_configuration = cloud_service_configuration self.virtual_machine_configuration = virtual_machine_configuration class DetectorListResult(_serialization.Model): """Values returned by the List operation. :ivar value: The collection of Batch account detectors returned by the listing operation. :vartype value: list[~azure.mgmt.batch.models.DetectorResponse] :ivar next_link: The URL to get the next set of results. :vartype next_link: str """ _attribute_map = { "value": {"key": "value", "type": "[DetectorResponse]"}, "next_link": {"key": "nextLink", "type": "str"}, } def __init__( self, *, value: Optional[List["_models.DetectorResponse"]] = None, next_link: Optional[str] = None, **kwargs: Any ) -> None: """ :keyword value: The collection of Batch account detectors returned by the listing operation. :paramtype value: list[~azure.mgmt.batch.models.DetectorResponse] :keyword next_link: The URL to get the next set of results. :paramtype next_link: str """ super().__init__(**kwargs) self.value = value self.next_link = next_link class DetectorResponse(ProxyResource): """Contains the information for a detector. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: The ID of the resource. :vartype id: str :ivar name: The name of the resource. :vartype name: str :ivar type: The type of the resource. :vartype type: str :ivar etag: The ETag of the resource, used for concurrency statements. :vartype etag: str :ivar value: A base64 encoded string that represents the content of a detector. :vartype value: str """ _validation = { "id": {"readonly": True}, "name": {"readonly": True}, "type": {"readonly": True}, "etag": {"readonly": True}, } _attribute_map = { "id": {"key": "id", "type": "str"}, "name": {"key": "name", "type": "str"}, "type": {"key": "type", "type": "str"}, "etag": {"key": "etag", "type": "str"}, "value": {"key": "properties.value", "type": "str"}, } def __init__(self, *, value: Optional[str] = None, **kwargs: Any) -> None: """ :keyword value: A base64 encoded string that represents the content of a detector. :paramtype value: str """ super().__init__(**kwargs) self.value = value class DiffDiskSettings(_serialization.Model): """Specifies the ephemeral Disk Settings for the operating system disk used by the virtual machine. :ivar placement: This property can be used by user in the request to choose which location the operating system should be in. e.g., cache disk space for Ephemeral OS disk provisioning. For more information on Ephemeral OS disk size requirements, please refer to Ephemeral OS disk size requirements for Windows VMs at https://docs.microsoft.com/en-us/azure/virtual-machines/windows/ephemeral-os-disks#size-requirements and Linux VMs at https://docs.microsoft.com/en-us/azure/virtual-machines/linux/ephemeral-os-disks#size-requirements. Default value is "CacheDisk". :vartype placement: str """ _attribute_map = { "placement": {"key": "placement", "type": "str"}, } def __init__(self, *, placement: Optional[Literal["CacheDisk"]] = None, **kwargs: Any) -> None: """ :keyword placement: This property can be used by user in the request to choose which location the operating system should be in. e.g., cache disk space for Ephemeral OS disk provisioning. For more information on Ephemeral OS disk size requirements, please refer to Ephemeral OS disk size requirements for Windows VMs at https://docs.microsoft.com/en-us/azure/virtual-machines/windows/ephemeral-os-disks#size-requirements and Linux VMs at https://docs.microsoft.com/en-us/azure/virtual-machines/linux/ephemeral-os-disks#size-requirements. Default value is "CacheDisk". :paramtype placement: str """ super().__init__(**kwargs) self.placement = placement class DiskEncryptionConfiguration(_serialization.Model): """The disk encryption configuration applied on compute nodes in the pool. Disk encryption configuration is not supported on Linux pool created with Virtual Machine Image or Shared Image Gallery Image. :ivar targets: On Linux pool, only "TemporaryDisk" is supported; on Windows pool, "OsDisk" and "TemporaryDisk" must be specified. :vartype targets: list[str or ~azure.mgmt.batch.models.DiskEncryptionTarget] """ _attribute_map = { "targets": {"key": "targets", "type": "[str]"}, } def __init__( self, *, targets: Optional[List[Union[str, "_models.DiskEncryptionTarget"]]] = None, **kwargs: Any ) -> None: """ :keyword targets: On Linux pool, only "TemporaryDisk" is supported; on Windows pool, "OsDisk" and "TemporaryDisk" must be specified. :paramtype targets: list[str or ~azure.mgmt.batch.models.DiskEncryptionTarget] """ super().__init__(**kwargs) self.targets = targets class EncryptionProperties(_serialization.Model): """Configures how customer data is encrypted inside the Batch account. By default, accounts are encrypted using a Microsoft managed key. For additional control, a customer-managed key can be used instead. :ivar key_source: Type of the key source. Known values are: "Microsoft.Batch" and "Microsoft.KeyVault". :vartype key_source: str or ~azure.mgmt.batch.models.KeySource :ivar key_vault_properties: Additional details when using Microsoft.KeyVault. :vartype key_vault_properties: ~azure.mgmt.batch.models.KeyVaultProperties """ _attribute_map = { "key_source": {"key": "keySource", "type": "str"}, "key_vault_properties": {"key": "keyVaultProperties", "type": "KeyVaultProperties"}, } def __init__( self, *, key_source: Optional[Union[str, "_models.KeySource"]] = None, key_vault_properties: Optional["_models.KeyVaultProperties"] = None, **kwargs: Any ) -> None: """ :keyword key_source: Type of the key source. Known values are: "Microsoft.Batch" and "Microsoft.KeyVault". :paramtype key_source: str or ~azure.mgmt.batch.models.KeySource :keyword key_vault_properties: Additional details when using Microsoft.KeyVault. :paramtype key_vault_properties: ~azure.mgmt.batch.models.KeyVaultProperties """ super().__init__(**kwargs) self.key_source = key_source self.key_vault_properties = key_vault_properties class EndpointAccessProfile(_serialization.Model): """Network access profile for Batch endpoint. All required parameters must be populated in order to send to Azure. :ivar default_action: Default action for endpoint access. It is only applicable when publicNetworkAccess is enabled. Required. Known values are: "Allow" and "Deny". :vartype default_action: str or ~azure.mgmt.batch.models.EndpointAccessDefaultAction :ivar ip_rules: Array of IP ranges to filter client IP address. :vartype ip_rules: list[~azure.mgmt.batch.models.IPRule] """ _validation = { "default_action": {"required": True}, } _attribute_map = { "default_action": {"key": "defaultAction", "type": "str"}, "ip_rules": {"key": "ipRules", "type": "[IPRule]"}, } def __init__( self, *, default_action: Union[str, "_models.EndpointAccessDefaultAction"], ip_rules: Optional[List["_models.IPRule"]] = None, **kwargs: Any ) -> None: """ :keyword default_action: Default action for endpoint access. It is only applicable when publicNetworkAccess is enabled. Required. Known values are: "Allow" and "Deny". :paramtype default_action: str or ~azure.mgmt.batch.models.EndpointAccessDefaultAction :keyword ip_rules: Array of IP ranges to filter client IP address. :paramtype ip_rules: list[~azure.mgmt.batch.models.IPRule] """ super().__init__(**kwargs) self.default_action = default_action self.ip_rules = ip_rules class EndpointDependency(_serialization.Model): """A domain name and connection details used to access a dependency. Variables are only populated by the server, and will be ignored when sending a request. :ivar domain_name: The domain name of the dependency. Domain names may be fully qualified or may contain a * wildcard. :vartype domain_name: str :ivar description: Human-readable supplemental information about the dependency and when it is applicable. :vartype description: str :ivar endpoint_details: The list of connection details for this endpoint. :vartype endpoint_details: list[~azure.mgmt.batch.models.EndpointDetail] """ _validation = { "domain_name": {"readonly": True}, "description": {"readonly": True}, "endpoint_details": {"readonly": True}, } _attribute_map = { "domain_name": {"key": "domainName", "type": "str"}, "description": {"key": "description", "type": "str"}, "endpoint_details": {"key": "endpointDetails", "type": "[EndpointDetail]"}, } def __init__(self, **kwargs: Any) -> None: """ """ super().__init__(**kwargs) self.domain_name = None self.description = None self.endpoint_details = None class EndpointDetail(_serialization.Model): """Details about the connection between the Batch service and the endpoint. Variables are only populated by the server, and will be ignored when sending a request. :ivar port: The port an endpoint is connected to. :vartype port: int """ _validation = { "port": {"readonly": True}, } _attribute_map = { "port": {"key": "port", "type": "int"}, } def __init__(self, **kwargs: Any) -> None: """ """ super().__init__(**kwargs) self.port = None class EnvironmentSetting(_serialization.Model): """An environment variable to be set on a task process. All required parameters must be populated in order to send to Azure. :ivar name: The name of the environment variable. Required. :vartype name: str :ivar value: The value of the environment variable. :vartype value: str """ _validation = { "name": {"required": True}, } _attribute_map = { "name": {"key": "name", "type": "str"}, "value": {"key": "value", "type": "str"}, } def __init__(self, *, name: str, value: Optional[str] = None, **kwargs: Any) -> None: """ :keyword name: The name of the environment variable. Required. :paramtype name: str :keyword value: The value of the environment variable. :paramtype value: str """ super().__init__(**kwargs) self.name = name self.value = value class FixedScaleSettings(_serialization.Model): """Fixed scale settings for the pool. :ivar resize_timeout: The default value is 15 minutes. Timeout values use ISO 8601 format. For example, use PT10M for 10 minutes. The minimum value is 5 minutes. If you specify a value less than 5 minutes, the Batch service rejects the request with an error; if you are calling the REST API directly, the HTTP status code is 400 (Bad Request). :vartype resize_timeout: ~datetime.timedelta :ivar target_dedicated_nodes: At least one of targetDedicatedNodes, targetLowPriorityNodes must be set. :vartype target_dedicated_nodes: int :ivar target_low_priority_nodes: At least one of targetDedicatedNodes, targetLowPriorityNodes must be set. :vartype target_low_priority_nodes: int :ivar node_deallocation_option: If omitted, the default value is Requeue. Known values are: "Requeue", "Terminate", "TaskCompletion", and "RetainedData". :vartype node_deallocation_option: str or ~azure.mgmt.batch.models.ComputeNodeDeallocationOption """ _attribute_map = { "resize_timeout": {"key": "resizeTimeout", "type": "duration"}, "target_dedicated_nodes": {"key": "targetDedicatedNodes", "type": "int"}, "target_low_priority_nodes": {"key": "targetLowPriorityNodes", "type": "int"}, "node_deallocation_option": {"key": "nodeDeallocationOption", "type": "str"}, } def __init__( self, *, resize_timeout: Optional[datetime.timedelta] = None, target_dedicated_nodes: Optional[int] = None, target_low_priority_nodes: Optional[int] = None, node_deallocation_option: Optional[Union[str, "_models.ComputeNodeDeallocationOption"]] = None, **kwargs: Any ) -> None: """ :keyword resize_timeout: The default value is 15 minutes. Timeout values use ISO 8601 format. For example, use PT10M for 10 minutes. The minimum value is 5 minutes. If you specify a value less than 5 minutes, the Batch service rejects the request with an error; if you are calling the REST API directly, the HTTP status code is 400 (Bad Request). :paramtype resize_timeout: ~datetime.timedelta :keyword target_dedicated_nodes: At least one of targetDedicatedNodes, targetLowPriorityNodes must be set. :paramtype target_dedicated_nodes: int :keyword target_low_priority_nodes: At least one of targetDedicatedNodes, targetLowPriorityNodes must be set. :paramtype target_low_priority_nodes: int :keyword node_deallocation_option: If omitted, the default value is Requeue. Known values are: "Requeue", "Terminate", "TaskCompletion", and "RetainedData". :paramtype node_deallocation_option: str or ~azure.mgmt.batch.models.ComputeNodeDeallocationOption """ super().__init__(**kwargs) self.resize_timeout = resize_timeout self.target_dedicated_nodes = target_dedicated_nodes self.target_low_priority_nodes = target_low_priority_nodes self.node_deallocation_option = node_deallocation_option class ImageReference(_serialization.Model): """A reference to an Azure Virtual Machines Marketplace image or the Azure Image resource of a custom Virtual Machine. To get the list of all imageReferences verified by Azure Batch, see the 'List supported node agent SKUs' operation. :ivar publisher: For example, Canonical or MicrosoftWindowsServer. :vartype publisher: str :ivar offer: For example, UbuntuServer or WindowsServer. :vartype offer: str :ivar sku: For example, 18.04-LTS or 2022-datacenter. :vartype sku: str :ivar version: A value of 'latest' can be specified to select the latest version of an image. If omitted, the default is 'latest'. :vartype version: str :ivar id: This property is mutually exclusive with other properties. The Shared Image Gallery image must have replicas in the same region as the Azure Batch account. For information about the firewall settings for the Batch node agent to communicate with the Batch service see https://docs.microsoft.com/en-us/azure/batch/batch-api-basics#virtual-network-vnet-and-firewall-configuration. :vartype id: str """ _attribute_map = { "publisher": {"key": "publisher", "type": "str"}, "offer": {"key": "offer", "type": "str"}, "sku": {"key": "sku", "type": "str"}, "version": {"key": "version", "type": "str"}, "id": {"key": "id", "type": "str"}, } def __init__( self, *, publisher: Optional[str] = None, offer: Optional[str] = None, sku: Optional[str] = None, version: Optional[str] = None, id: Optional[str] = None, # pylint: disable=redefined-builtin **kwargs: Any ) -> None: """ :keyword publisher: For example, Canonical or MicrosoftWindowsServer. :paramtype publisher: str :keyword offer: For example, UbuntuServer or WindowsServer. :paramtype offer: str :keyword sku: For example, 18.04-LTS or 2022-datacenter. :paramtype sku: str :keyword version: A value of 'latest' can be specified to select the latest version of an image. If omitted, the default is 'latest'. :paramtype version: str :keyword id: This property is mutually exclusive with other properties. The Shared Image Gallery image must have replicas in the same region as the Azure Batch account. For information about the firewall settings for the Batch node agent to communicate with the Batch service see https://docs.microsoft.com/en-us/azure/batch/batch-api-basics#virtual-network-vnet-and-firewall-configuration. :paramtype id: str """ super().__init__(**kwargs) self.publisher = publisher self.offer = offer self.sku = sku self.version = version self.id = id class InboundNatPool(_serialization.Model): """A inbound NAT pool that can be used to address specific ports on compute nodes in a Batch pool externally. All required parameters must be populated in order to send to Azure. :ivar name: The name must be unique within a Batch pool, can contain letters, numbers, underscores, periods, and hyphens. Names must start with a letter or number, must end with a letter, number, or underscore, and cannot exceed 77 characters. If any invalid values are provided the request fails with HTTP status code 400. Required. :vartype name: str :ivar protocol: The protocol of the endpoint. Required. Known values are: "TCP" and "UDP". :vartype protocol: str or ~azure.mgmt.batch.models.InboundEndpointProtocol :ivar backend_port: This must be unique within a Batch pool. Acceptable values are between 1 and 65535 except for 22, 3389, 29876 and 29877 as these are reserved. If any reserved values are provided the request fails with HTTP status code 400. Required. :vartype backend_port: int :ivar frontend_port_range_start: Acceptable values range between 1 and 65534 except ports from 50000 to 55000 which are reserved. All ranges within a pool must be distinct and cannot overlap. If any reserved or overlapping values are provided the request fails with HTTP status code 400. Required. :vartype frontend_port_range_start: int :ivar frontend_port_range_end: Acceptable values range between 1 and 65534 except ports from 50000 to 55000 which are reserved by the Batch service. All ranges within a pool must be distinct and cannot overlap. If any reserved or overlapping values are provided the request fails with HTTP status code 400. Required. :vartype frontend_port_range_end: int :ivar network_security_group_rules: The maximum number of rules that can be specified across all the endpoints on a Batch pool is 25. If no network security group rules are specified, a default rule will be created to allow inbound access to the specified backendPort. If the maximum number of network security group rules is exceeded the request fails with HTTP status code 400. :vartype network_security_group_rules: list[~azure.mgmt.batch.models.NetworkSecurityGroupRule] """ _validation = { "name": {"required": True}, "protocol": {"required": True}, "backend_port": {"required": True}, "frontend_port_range_start": {"required": True}, "frontend_port_range_end": {"required": True}, } _attribute_map = { "name": {"key": "name", "type": "str"}, "protocol": {"key": "protocol", "type": "str"}, "backend_port": {"key": "backendPort", "type": "int"}, "frontend_port_range_start": {"key": "frontendPortRangeStart", "type": "int"}, "frontend_port_range_end": {"key": "frontendPortRangeEnd", "type": "int"}, "network_security_group_rules": {"key": "networkSecurityGroupRules", "type": "[NetworkSecurityGroupRule]"}, } def __init__( self, *, name: str, protocol: Union[str, "_models.InboundEndpointProtocol"], backend_port: int, frontend_port_range_start: int, frontend_port_range_end: int, network_security_group_rules: Optional[List["_models.NetworkSecurityGroupRule"]] = None, **kwargs: Any ) -> None: """ :keyword name: The name must be unique within a Batch pool, can contain letters, numbers, underscores, periods, and hyphens. Names must start with a letter or number, must end with a letter, number, or underscore, and cannot exceed 77 characters. If any invalid values are provided the request fails with HTTP status code 400. Required. :paramtype name: str :keyword protocol: The protocol of the endpoint. Required. Known values are: "TCP" and "UDP". :paramtype protocol: str or ~azure.mgmt.batch.models.InboundEndpointProtocol :keyword backend_port: This must be unique within a Batch pool. Acceptable values are between 1 and 65535 except for 22, 3389, 29876 and 29877 as these are reserved. If any reserved values are provided the request fails with HTTP status code 400. Required. :paramtype backend_port: int :keyword frontend_port_range_start: Acceptable values range between 1 and 65534 except ports from 50000 to 55000 which are reserved. All ranges within a pool must be distinct and cannot overlap. If any reserved or overlapping values are provided the request fails with HTTP status code 400. Required. :paramtype frontend_port_range_start: int :keyword frontend_port_range_end: Acceptable values range between 1 and 65534 except ports from 50000 to 55000 which are reserved by the Batch service. All ranges within a pool must be distinct and cannot overlap. If any reserved or overlapping values are provided the request fails with HTTP status code 400. Required. :paramtype frontend_port_range_end: int :keyword network_security_group_rules: The maximum number of rules that can be specified across all the endpoints on a Batch pool is 25. If no network security group rules are specified, a default rule will be created to allow inbound access to the specified backendPort. If the maximum number of network security group rules is exceeded the request fails with HTTP status code 400. :paramtype network_security_group_rules: list[~azure.mgmt.batch.models.NetworkSecurityGroupRule] """ super().__init__(**kwargs) self.name = name self.protocol = protocol self.backend_port = backend_port self.frontend_port_range_start = frontend_port_range_start self.frontend_port_range_end = frontend_port_range_end self.network_security_group_rules = network_security_group_rules class IPRule(_serialization.Model): """Rule to filter client IP address. Variables are only populated by the server, and will be ignored when sending a request. All required parameters must be populated in order to send to Azure. :ivar action: Action when client IP address is matched. Required. Default value is "Allow". :vartype action: str :ivar value: IPv4 address, or IPv4 address range in CIDR format. Required. :vartype value: str """ _validation = { "action": {"required": True, "constant": True}, "value": {"required": True}, } _attribute_map = { "action": {"key": "action", "type": "str"}, "value": {"key": "value", "type": "str"}, } action = "Allow" def __init__(self, *, value: str, **kwargs: Any) -> None: """ :keyword value: IPv4 address, or IPv4 address range in CIDR format. Required. :paramtype value: str """ super().__init__(**kwargs) self.value = value class KeyVaultProperties(_serialization.Model): """KeyVault configuration when using an encryption KeySource of Microsoft.KeyVault. :ivar key_identifier: Full path to the secret with or without version. Example https://mykeyvault.vault.azure.net/keys/testkey/6e34a81fef704045975661e297a4c053. or https://mykeyvault.vault.azure.net/keys/testkey. To be usable the following prerequisites must be met: The Batch Account has a System Assigned identity The account identity has been granted Key/Get, Key/Unwrap and Key/Wrap permissions The KeyVault has soft-delete and purge protection enabled. :vartype key_identifier: str """ _attribute_map = { "key_identifier": {"key": "keyIdentifier", "type": "str"}, } def __init__(self, *, key_identifier: Optional[str] = None, **kwargs: Any) -> None: """ :keyword key_identifier: Full path to the secret with or without version. Example https://mykeyvault.vault.azure.net/keys/testkey/6e34a81fef704045975661e297a4c053. or https://mykeyvault.vault.azure.net/keys/testkey. To be usable the following prerequisites must be met: The Batch Account has a System Assigned identity The account identity has been granted Key/Get, Key/Unwrap and Key/Wrap permissions The KeyVault has soft-delete and purge protection enabled. :paramtype key_identifier: str """ super().__init__(**kwargs) self.key_identifier = key_identifier class KeyVaultReference(_serialization.Model): """Identifies the Azure key vault associated with a Batch account. All required parameters must be populated in order to send to Azure. :ivar id: The resource ID of the Azure key vault associated with the Batch account. Required. :vartype id: str :ivar url: The URL of the Azure key vault associated with the Batch account. Required. :vartype url: str """ _validation = { "id": {"required": True}, "url": {"required": True}, } _attribute_map = { "id": {"key": "id", "type": "str"}, "url": {"key": "url", "type": "str"}, } def __init__(self, *, id: str, url: str, **kwargs: Any) -> None: # pylint: disable=redefined-builtin """ :keyword id: The resource ID of the Azure key vault associated with the Batch account. Required. :paramtype id: str :keyword url: The URL of the Azure key vault associated with the Batch account. Required. :paramtype url: str """ super().__init__(**kwargs) self.id = id self.url = url class LinuxUserConfiguration(_serialization.Model): """Properties used to create a user account on a Linux node. :ivar uid: The uid and gid properties must be specified together or not at all. If not specified the underlying operating system picks the uid. :vartype uid: int :ivar gid: The uid and gid properties must be specified together or not at all. If not specified the underlying operating system picks the gid. :vartype gid: int :ivar ssh_private_key: The private key must not be password protected. The private key is used to automatically configure asymmetric-key based authentication for SSH between nodes in a Linux pool when the pool's enableInterNodeCommunication property is true (it is ignored if enableInterNodeCommunication is false). It does this by placing the key pair into the user's .ssh directory. If not specified, password-less SSH is not configured between nodes (no modification of the user's .ssh directory is done). :vartype ssh_private_key: str """ _attribute_map = { "uid": {"key": "uid", "type": "int"}, "gid": {"key": "gid", "type": "int"}, "ssh_private_key": {"key": "sshPrivateKey", "type": "str"}, } def __init__( self, *, uid: Optional[int] = None, gid: Optional[int] = None, ssh_private_key: Optional[str] = None, **kwargs: Any ) -> None: """ :keyword uid: The uid and gid properties must be specified together or not at all. If not specified the underlying operating system picks the uid. :paramtype uid: int :keyword gid: The uid and gid properties must be specified together or not at all. If not specified the underlying operating system picks the gid. :paramtype gid: int :keyword ssh_private_key: The private key must not be password protected. The private key is used to automatically configure asymmetric-key based authentication for SSH between nodes in a Linux pool when the pool's enableInterNodeCommunication property is true (it is ignored if enableInterNodeCommunication is false). It does this by placing the key pair into the user's .ssh directory. If not specified, password-less SSH is not configured between nodes (no modification of the user's .ssh directory is done). :paramtype ssh_private_key: str """ super().__init__(**kwargs) self.uid = uid self.gid = gid self.ssh_private_key = ssh_private_key class ListApplicationPackagesResult(_serialization.Model): """The result of performing list application packages. :ivar value: The list of application packages. :vartype value: list[~azure.mgmt.batch.models.ApplicationPackage] :ivar next_link: The URL to get the next set of results. :vartype next_link: str """ _attribute_map = { "value": {"key": "value", "type": "[ApplicationPackage]"}, "next_link": {"key": "nextLink", "type": "str"}, } def __init__( self, *, value: Optional[List["_models.ApplicationPackage"]] = None, next_link: Optional[str] = None, **kwargs: Any ) -> None: """ :keyword value: The list of application packages. :paramtype value: list[~azure.mgmt.batch.models.ApplicationPackage] :keyword next_link: The URL to get the next set of results. :paramtype next_link: str """ super().__init__(**kwargs) self.value = value self.next_link = next_link class ListApplicationsResult(_serialization.Model): """The result of performing list applications. :ivar value: The list of applications. :vartype value: list[~azure.mgmt.batch.models.Application] :ivar next_link: The URL to get the next set of results. :vartype next_link: str """ _attribute_map = { "value": {"key": "value", "type": "[Application]"}, "next_link": {"key": "nextLink", "type": "str"}, } def __init__( self, *, value: Optional[List["_models.Application"]] = None, next_link: Optional[str] = None, **kwargs: Any ) -> None: """ :keyword value: The list of applications. :paramtype value: list[~azure.mgmt.batch.models.Application] :keyword next_link: The URL to get the next set of results. :paramtype next_link: str """ super().__init__(**kwargs) self.value = value self.next_link = next_link class ListCertificatesResult(_serialization.Model): """Values returned by the List operation. :ivar value: The collection of returned certificates. :vartype value: list[~azure.mgmt.batch.models.Certificate] :ivar next_link: The continuation token. :vartype next_link: str """ _attribute_map = { "value": {"key": "value", "type": "[Certificate]"}, "next_link": {"key": "nextLink", "type": "str"}, } def __init__( self, *, value: Optional[List["_models.Certificate"]] = None, next_link: Optional[str] = None, **kwargs: Any ) -> None: """ :keyword value: The collection of returned certificates. :paramtype value: list[~azure.mgmt.batch.models.Certificate] :keyword next_link: The continuation token. :paramtype next_link: str """ super().__init__(**kwargs) self.value = value self.next_link = next_link class ListPoolsResult(_serialization.Model): """Values returned by the List operation. :ivar value: The collection of returned pools. :vartype value: list[~azure.mgmt.batch.models.Pool] :ivar next_link: The continuation token. :vartype next_link: str """ _attribute_map = { "value": {"key": "value", "type": "[Pool]"}, "next_link": {"key": "nextLink", "type": "str"}, } def __init__( self, *, value: Optional[List["_models.Pool"]] = None, next_link: Optional[str] = None, **kwargs: Any ) -> None: """ :keyword value: The collection of returned pools. :paramtype value: list[~azure.mgmt.batch.models.Pool] :keyword next_link: The continuation token. :paramtype next_link: str """ super().__init__(**kwargs) self.value = value self.next_link = next_link class ListPrivateEndpointConnectionsResult(_serialization.Model): """Values returned by the List operation. :ivar value: The collection of returned private endpoint connection. :vartype value: list[~azure.mgmt.batch.models.PrivateEndpointConnection] :ivar next_link: The continuation token. :vartype next_link: str """ _attribute_map = { "value": {"key": "value", "type": "[PrivateEndpointConnection]"}, "next_link": {"key": "nextLink", "type": "str"}, } def __init__( self, *, value: Optional[List["_models.PrivateEndpointConnection"]] = None, next_link: Optional[str] = None, **kwargs: Any ) -> None: """ :keyword value: The collection of returned private endpoint connection. :paramtype value: list[~azure.mgmt.batch.models.PrivateEndpointConnection] :keyword next_link: The continuation token. :paramtype next_link: str """ super().__init__(**kwargs) self.value = value self.next_link = next_link class ListPrivateLinkResourcesResult(_serialization.Model): """Values returned by the List operation. :ivar value: The collection of returned private link resources. :vartype value: list[~azure.mgmt.batch.models.PrivateLinkResource] :ivar next_link: The continuation token. :vartype next_link: str """ _attribute_map = { "value": {"key": "value", "type": "[PrivateLinkResource]"}, "next_link": {"key": "nextLink", "type": "str"}, } def __init__( self, *, value: Optional[List["_models.PrivateLinkResource"]] = None, next_link: Optional[str] = None, **kwargs: Any ) -> None: """ :keyword value: The collection of returned private link resources. :paramtype value: list[~azure.mgmt.batch.models.PrivateLinkResource] :keyword next_link: The continuation token. :paramtype next_link: str """ super().__init__(**kwargs) self.value = value self.next_link = next_link class MetadataItem(_serialization.Model): """The Batch service does not assign any meaning to this metadata; it is solely for the use of user code. All required parameters must be populated in order to send to Azure. :ivar name: The name of the metadata item. Required. :vartype name: str :ivar value: The value of the metadata item. Required. :vartype value: str """ _validation = { "name": {"required": True}, "value": {"required": True}, } _attribute_map = { "name": {"key": "name", "type": "str"}, "value": {"key": "value", "type": "str"}, } def __init__(self, *, name: str, value: str, **kwargs: Any) -> None: """ :keyword name: The name of the metadata item. Required. :paramtype name: str :keyword value: The value of the metadata item. Required. :paramtype value: str """ super().__init__(**kwargs) self.name = name self.value = value class MountConfiguration(_serialization.Model): """The file system to mount on each node. :ivar azure_blob_file_system_configuration: This property is mutually exclusive with all other properties. :vartype azure_blob_file_system_configuration: ~azure.mgmt.batch.models.AzureBlobFileSystemConfiguration :ivar nfs_mount_configuration: This property is mutually exclusive with all other properties. :vartype nfs_mount_configuration: ~azure.mgmt.batch.models.NFSMountConfiguration :ivar cifs_mount_configuration: This property is mutually exclusive with all other properties. :vartype cifs_mount_configuration: ~azure.mgmt.batch.models.CIFSMountConfiguration :ivar azure_file_share_configuration: This property is mutually exclusive with all other properties. :vartype azure_file_share_configuration: ~azure.mgmt.batch.models.AzureFileShareConfiguration """ _attribute_map = { "azure_blob_file_system_configuration": { "key": "azureBlobFileSystemConfiguration", "type": "AzureBlobFileSystemConfiguration", }, "nfs_mount_configuration": {"key": "nfsMountConfiguration", "type": "NFSMountConfiguration"}, "cifs_mount_configuration": {"key": "cifsMountConfiguration", "type": "CIFSMountConfiguration"}, "azure_file_share_configuration": {"key": "azureFileShareConfiguration", "type": "AzureFileShareConfiguration"}, } def __init__( self, *, azure_blob_file_system_configuration: Optional["_models.AzureBlobFileSystemConfiguration"] = None, nfs_mount_configuration: Optional["_models.NFSMountConfiguration"] = None, cifs_mount_configuration: Optional["_models.CIFSMountConfiguration"] = None, azure_file_share_configuration: Optional["_models.AzureFileShareConfiguration"] = None, **kwargs: Any ) -> None: """ :keyword azure_blob_file_system_configuration: This property is mutually exclusive with all other properties. :paramtype azure_blob_file_system_configuration: ~azure.mgmt.batch.models.AzureBlobFileSystemConfiguration :keyword nfs_mount_configuration: This property is mutually exclusive with all other properties. :paramtype nfs_mount_configuration: ~azure.mgmt.batch.models.NFSMountConfiguration :keyword cifs_mount_configuration: This property is mutually exclusive with all other properties. :paramtype cifs_mount_configuration: ~azure.mgmt.batch.models.CIFSMountConfiguration :keyword azure_file_share_configuration: This property is mutually exclusive with all other properties. :paramtype azure_file_share_configuration: ~azure.mgmt.batch.models.AzureFileShareConfiguration """ super().__init__(**kwargs) self.azure_blob_file_system_configuration = azure_blob_file_system_configuration self.nfs_mount_configuration = nfs_mount_configuration self.cifs_mount_configuration = cifs_mount_configuration self.azure_file_share_configuration = azure_file_share_configuration class NetworkConfiguration(_serialization.Model): """The network configuration for a pool. :ivar subnet_id: The virtual network must be in the same region and subscription as the Azure Batch account. The specified subnet should have enough free IP addresses to accommodate the number of nodes in the pool. If the subnet doesn't have enough free IP addresses, the pool will partially allocate compute nodes and a resize error will occur. The 'MicrosoftAzureBatch' service principal must have the 'Classic Virtual Machine Contributor' Role-Based Access Control (RBAC) role for the specified VNet. The specified subnet must allow communication from the Azure Batch service to be able to schedule tasks on the compute nodes. This can be verified by checking if the specified VNet has any associated Network Security Groups (NSG). If communication to the compute nodes in the specified subnet is denied by an NSG, then the Batch service will set the state of the compute nodes to unusable. If the specified VNet has any associated Network Security Groups (NSG), then a few reserved system ports must be enabled for inbound communication. For pools created with a virtual machine configuration, enable ports 29876 and 29877, as well as port 22 for Linux and port 3389 for Windows. For pools created with a cloud service configuration, enable ports 10100, 20100, and 30100. Also enable outbound connections to Azure Storage on port 443. For cloudServiceConfiguration pools, only 'classic' VNETs are supported. For more details see: https://docs.microsoft.com/en-us/azure/batch/batch-api-basics#virtual-network-vnet-and-firewall-configuration. :vartype subnet_id: str :ivar dynamic_vnet_assignment_scope: The scope of dynamic vnet assignment. Known values are: "none" and "job". :vartype dynamic_vnet_assignment_scope: str or ~azure.mgmt.batch.models.DynamicVNetAssignmentScope :ivar endpoint_configuration: Pool endpoint configuration is only supported on pools with the virtualMachineConfiguration property. :vartype endpoint_configuration: ~azure.mgmt.batch.models.PoolEndpointConfiguration :ivar public_ip_address_configuration: This property is only supported on Pools with the virtualMachineConfiguration property. :vartype public_ip_address_configuration: ~azure.mgmt.batch.models.PublicIPAddressConfiguration :ivar enable_accelerated_networking: Accelerated networking enables single root I/O virtualization (SR-IOV) to a VM, which may lead to improved networking performance. For more details, see: https://learn.microsoft.com/azure/virtual-network/accelerated-networking-overview. :vartype enable_accelerated_networking: bool """ _attribute_map = { "subnet_id": {"key": "subnetId", "type": "str"}, "dynamic_vnet_assignment_scope": {"key": "dynamicVnetAssignmentScope", "type": "str"}, "endpoint_configuration": {"key": "endpointConfiguration", "type": "PoolEndpointConfiguration"}, "public_ip_address_configuration": { "key": "publicIPAddressConfiguration", "type": "PublicIPAddressConfiguration", }, "enable_accelerated_networking": {"key": "enableAcceleratedNetworking", "type": "bool"}, } def __init__( self, *, subnet_id: Optional[str] = None, dynamic_vnet_assignment_scope: Optional[Union[str, "_models.DynamicVNetAssignmentScope"]] = None, endpoint_configuration: Optional["_models.PoolEndpointConfiguration"] = None, public_ip_address_configuration: Optional["_models.PublicIPAddressConfiguration"] = None, enable_accelerated_networking: Optional[bool] = None, **kwargs: Any ) -> None: """ :keyword subnet_id: The virtual network must be in the same region and subscription as the Azure Batch account. The specified subnet should have enough free IP addresses to accommodate the number of nodes in the pool. If the subnet doesn't have enough free IP addresses, the pool will partially allocate compute nodes and a resize error will occur. The 'MicrosoftAzureBatch' service principal must have the 'Classic Virtual Machine Contributor' Role-Based Access Control (RBAC) role for the specified VNet. The specified subnet must allow communication from the Azure Batch service to be able to schedule tasks on the compute nodes. This can be verified by checking if the specified VNet has any associated Network Security Groups (NSG). If communication to the compute nodes in the specified subnet is denied by an NSG, then the Batch service will set the state of the compute nodes to unusable. If the specified VNet has any associated Network Security Groups (NSG), then a few reserved system ports must be enabled for inbound communication. For pools created with a virtual machine configuration, enable ports 29876 and 29877, as well as port 22 for Linux and port 3389 for Windows. For pools created with a cloud service configuration, enable ports 10100, 20100, and 30100. Also enable outbound connections to Azure Storage on port 443. For cloudServiceConfiguration pools, only 'classic' VNETs are supported. For more details see: https://docs.microsoft.com/en-us/azure/batch/batch-api-basics#virtual-network-vnet-and-firewall-configuration. :paramtype subnet_id: str :keyword dynamic_vnet_assignment_scope: The scope of dynamic vnet assignment. Known values are: "none" and "job". :paramtype dynamic_vnet_assignment_scope: str or ~azure.mgmt.batch.models.DynamicVNetAssignmentScope :keyword endpoint_configuration: Pool endpoint configuration is only supported on pools with the virtualMachineConfiguration property. :paramtype endpoint_configuration: ~azure.mgmt.batch.models.PoolEndpointConfiguration :keyword public_ip_address_configuration: This property is only supported on Pools with the virtualMachineConfiguration property. :paramtype public_ip_address_configuration: ~azure.mgmt.batch.models.PublicIPAddressConfiguration :keyword enable_accelerated_networking: Accelerated networking enables single root I/O virtualization (SR-IOV) to a VM, which may lead to improved networking performance. For more details, see: https://learn.microsoft.com/azure/virtual-network/accelerated-networking-overview. :paramtype enable_accelerated_networking: bool """ super().__init__(**kwargs) self.subnet_id = subnet_id self.dynamic_vnet_assignment_scope = dynamic_vnet_assignment_scope self.endpoint_configuration = endpoint_configuration self.public_ip_address_configuration = public_ip_address_configuration self.enable_accelerated_networking = enable_accelerated_networking class NetworkProfile(_serialization.Model): """Network profile for Batch account, which contains network rule settings for each endpoint. :ivar account_access: Network access profile for batchAccount endpoint (Batch account data plane API). :vartype account_access: ~azure.mgmt.batch.models.EndpointAccessProfile :ivar node_management_access: Network access profile for nodeManagement endpoint (Batch service managing compute nodes for Batch pools). :vartype node_management_access: ~azure.mgmt.batch.models.EndpointAccessProfile """ _attribute_map = { "account_access": {"key": "accountAccess", "type": "EndpointAccessProfile"}, "node_management_access": {"key": "nodeManagementAccess", "type": "EndpointAccessProfile"}, } def __init__( self, *, account_access: Optional["_models.EndpointAccessProfile"] = None, node_management_access: Optional["_models.EndpointAccessProfile"] = None, **kwargs: Any ) -> None: """ :keyword account_access: Network access profile for batchAccount endpoint (Batch account data plane API). :paramtype account_access: ~azure.mgmt.batch.models.EndpointAccessProfile :keyword node_management_access: Network access profile for nodeManagement endpoint (Batch service managing compute nodes for Batch pools). :paramtype node_management_access: ~azure.mgmt.batch.models.EndpointAccessProfile """ super().__init__(**kwargs) self.account_access = account_access self.node_management_access = node_management_access class NetworkSecurityGroupRule(_serialization.Model): """A network security group rule to apply to an inbound endpoint. All required parameters must be populated in order to send to Azure. :ivar priority: Priorities within a pool must be unique and are evaluated in order of priority. The lower the number the higher the priority. For example, rules could be specified with order numbers of 150, 250, and 350. The rule with the order number of 150 takes precedence over the rule that has an order of 250. Allowed priorities are 150 to 4096. If any reserved or duplicate values are provided the request fails with HTTP status code 400. Required. :vartype priority: int :ivar access: The action that should be taken for a specified IP address, subnet range or tag. Required. Known values are: "Allow" and "Deny". :vartype access: str or ~azure.mgmt.batch.models.NetworkSecurityGroupRuleAccess :ivar source_address_prefix: Valid values are a single IP address (i.e. 10.10.10.10), IP subnet (i.e. 192.168.1.0/24), default tag, or * (for all addresses). If any other values are provided the request fails with HTTP status code 400. Required. :vartype source_address_prefix: str :ivar source_port_ranges: Valid values are '\ *' (for all ports 0 - 65535) or arrays of ports or port ranges (i.e. 100-200). The ports should in the range of 0 to 65535 and the port ranges or ports can't overlap. If any other values are provided the request fails with HTTP status code 400. Default value will be *. :vartype source_port_ranges: list[str] """ _validation = { "priority": {"required": True}, "access": {"required": True}, "source_address_prefix": {"required": True}, } _attribute_map = { "priority": {"key": "priority", "type": "int"}, "access": {"key": "access", "type": "str"}, "source_address_prefix": {"key": "sourceAddressPrefix", "type": "str"}, "source_port_ranges": {"key": "sourcePortRanges", "type": "[str]"}, } def __init__( self, *, priority: int, access: Union[str, "_models.NetworkSecurityGroupRuleAccess"], source_address_prefix: str, source_port_ranges: Optional[List[str]] = None, **kwargs: Any ) -> None: """ :keyword priority: Priorities within a pool must be unique and are evaluated in order of priority. The lower the number the higher the priority. For example, rules could be specified with order numbers of 150, 250, and 350. The rule with the order number of 150 takes precedence over the rule that has an order of 250. Allowed priorities are 150 to 4096. If any reserved or duplicate values are provided the request fails with HTTP status code 400. Required. :paramtype priority: int :keyword access: The action that should be taken for a specified IP address, subnet range or tag. Required. Known values are: "Allow" and "Deny". :paramtype access: str or ~azure.mgmt.batch.models.NetworkSecurityGroupRuleAccess :keyword source_address_prefix: Valid values are a single IP address (i.e. 10.10.10.10), IP subnet (i.e. 192.168.1.0/24), default tag, or * (for all addresses). If any other values are provided the request fails with HTTP status code 400. Required. :paramtype source_address_prefix: str :keyword source_port_ranges: Valid values are '\ *' (for all ports 0 - 65535) or arrays of ports or port ranges (i.e. 100-200). The ports should in the range of 0 to 65535 and the port ranges or ports can't overlap. If any other values are provided the request fails with HTTP status code 400. Default value will be *. :paramtype source_port_ranges: list[str] """ super().__init__(**kwargs) self.priority = priority self.access = access self.source_address_prefix = source_address_prefix self.source_port_ranges = source_port_ranges class NFSMountConfiguration(_serialization.Model): """Information used to connect to an NFS file system. All required parameters must be populated in order to send to Azure. :ivar source: The URI of the file system to mount. Required. :vartype source: str :ivar relative_mount_path: All file systems are mounted relative to the Batch mounts directory, accessible via the AZ_BATCH_NODE_MOUNTS_DIR environment variable. Required. :vartype relative_mount_path: str :ivar mount_options: These are 'net use' options in Windows and 'mount' options in Linux. :vartype mount_options: str """ _validation = { "source": {"required": True}, "relative_mount_path": {"required": True}, } _attribute_map = { "source": {"key": "source", "type": "str"}, "relative_mount_path": {"key": "relativeMountPath", "type": "str"}, "mount_options": {"key": "mountOptions", "type": "str"}, } def __init__( self, *, source: str, relative_mount_path: str, mount_options: Optional[str] = None, **kwargs: Any ) -> None: """ :keyword source: The URI of the file system to mount. Required. :paramtype source: str :keyword relative_mount_path: All file systems are mounted relative to the Batch mounts directory, accessible via the AZ_BATCH_NODE_MOUNTS_DIR environment variable. Required. :paramtype relative_mount_path: str :keyword mount_options: These are 'net use' options in Windows and 'mount' options in Linux. :paramtype mount_options: str """ super().__init__(**kwargs) self.source = source self.relative_mount_path = relative_mount_path self.mount_options = mount_options class NodePlacementConfiguration(_serialization.Model): """Allocation configuration used by Batch Service to provision the nodes. :ivar policy: Allocation policy used by Batch Service to provision the nodes. If not specified, Batch will use the regional policy. Known values are: "Regional" and "Zonal". :vartype policy: str or ~azure.mgmt.batch.models.NodePlacementPolicyType """ _attribute_map = { "policy": {"key": "policy", "type": "str"}, } def __init__( self, *, policy: Optional[Union[str, "_models.NodePlacementPolicyType"]] = None, **kwargs: Any ) -> None: """ :keyword policy: Allocation policy used by Batch Service to provision the nodes. If not specified, Batch will use the regional policy. Known values are: "Regional" and "Zonal". :paramtype policy: str or ~azure.mgmt.batch.models.NodePlacementPolicyType """ super().__init__(**kwargs) self.policy = policy class Operation(_serialization.Model): """A REST API operation. :ivar name: This is of the format {provider}/{resource}/{operation}. :vartype name: str :ivar is_data_action: Indicates whether the operation is a data action. :vartype is_data_action: bool :ivar display: The object that describes the operation. :vartype display: ~azure.mgmt.batch.models.OperationDisplay :ivar origin: The intended executor of the operation. :vartype origin: str :ivar properties: Properties of the operation. :vartype properties: JSON """ _attribute_map = { "name": {"key": "name", "type": "str"}, "is_data_action": {"key": "isDataAction", "type": "bool"}, "display": {"key": "display", "type": "OperationDisplay"}, "origin": {"key": "origin", "type": "str"}, "properties": {"key": "properties", "type": "object"}, } def __init__( self, *, name: Optional[str] = None, is_data_action: Optional[bool] = None, display: Optional["_models.OperationDisplay"] = None, origin: Optional[str] = None, properties: Optional[JSON] = None, **kwargs: Any ) -> None: """ :keyword name: This is of the format {provider}/{resource}/{operation}. :paramtype name: str :keyword is_data_action: Indicates whether the operation is a data action. :paramtype is_data_action: bool :keyword display: The object that describes the operation. :paramtype display: ~azure.mgmt.batch.models.OperationDisplay :keyword origin: The intended executor of the operation. :paramtype origin: str :keyword properties: Properties of the operation. :paramtype properties: JSON """ super().__init__(**kwargs) self.name = name self.is_data_action = is_data_action self.display = display self.origin = origin self.properties = properties class OperationDisplay(_serialization.Model): """The object that describes the operation. :ivar provider: Friendly name of the resource provider. :vartype provider: str :ivar operation: For example: read, write, delete, or listKeys/action. :vartype operation: str :ivar resource: The resource type on which the operation is performed. :vartype resource: str :ivar description: The friendly name of the operation. :vartype description: str """ _attribute_map = { "provider": {"key": "provider", "type": "str"}, "operation": {"key": "operation", "type": "str"}, "resource": {"key": "resource", "type": "str"}, "description": {"key": "description", "type": "str"}, } def __init__( self, *, provider: Optional[str] = None, operation: Optional[str] = None, resource: Optional[str] = None, description: Optional[str] = None, **kwargs: Any ) -> None: """ :keyword provider: Friendly name of the resource provider. :paramtype provider: str :keyword operation: For example: read, write, delete, or listKeys/action. :paramtype operation: str :keyword resource: The resource type on which the operation is performed. :paramtype resource: str :keyword description: The friendly name of the operation. :paramtype description: str """ super().__init__(**kwargs) self.provider = provider self.operation = operation self.resource = resource self.description = description class OperationListResult(_serialization.Model): """Result of the request to list REST API operations. It contains a list of operations and a URL nextLink to get the next set of results. :ivar value: The list of operations supported by the resource provider. :vartype value: list[~azure.mgmt.batch.models.Operation] :ivar next_link: The URL to get the next set of operation list results if there are any. :vartype next_link: str """ _attribute_map = { "value": {"key": "value", "type": "[Operation]"}, "next_link": {"key": "nextLink", "type": "str"}, } def __init__( self, *, value: Optional[List["_models.Operation"]] = None, next_link: Optional[str] = None, **kwargs: Any ) -> None: """ :keyword value: The list of operations supported by the resource provider. :paramtype value: list[~azure.mgmt.batch.models.Operation] :keyword next_link: The URL to get the next set of operation list results if there are any. :paramtype next_link: str """ super().__init__(**kwargs) self.value = value self.next_link = next_link class OSDisk(_serialization.Model): """Settings for the operating system disk of the virtual machine. :ivar ephemeral_os_disk_settings: Specifies the ephemeral Disk Settings for the operating system disk used by the virtual machine. :vartype ephemeral_os_disk_settings: ~azure.mgmt.batch.models.DiffDiskSettings """ _attribute_map = { "ephemeral_os_disk_settings": {"key": "ephemeralOSDiskSettings", "type": "DiffDiskSettings"}, } def __init__( self, *, ephemeral_os_disk_settings: Optional["_models.DiffDiskSettings"] = None, **kwargs: Any ) -> None: """ :keyword ephemeral_os_disk_settings: Specifies the ephemeral Disk Settings for the operating system disk used by the virtual machine. :paramtype ephemeral_os_disk_settings: ~azure.mgmt.batch.models.DiffDiskSettings """ super().__init__(**kwargs) self.ephemeral_os_disk_settings = ephemeral_os_disk_settings class OutboundEnvironmentEndpoint(_serialization.Model): """A collection of related endpoints from the same service for which the Batch service requires outbound access. Variables are only populated by the server, and will be ignored when sending a request. :ivar category: The type of service that the Batch service connects to. :vartype category: str :ivar endpoints: The endpoints for this service to which the Batch service makes outbound calls. :vartype endpoints: list[~azure.mgmt.batch.models.EndpointDependency] """ _validation = { "category": {"readonly": True}, "endpoints": {"readonly": True}, } _attribute_map = { "category": {"key": "category", "type": "str"}, "endpoints": {"key": "endpoints", "type": "[EndpointDependency]"}, } def __init__(self, **kwargs: Any) -> None: """ """ super().__init__(**kwargs) self.category = None self.endpoints = None class OutboundEnvironmentEndpointCollection(_serialization.Model): """Values returned by the List operation. Variables are only populated by the server, and will be ignored when sending a request. :ivar value: The collection of outbound network dependency endpoints returned by the listing operation. :vartype value: list[~azure.mgmt.batch.models.OutboundEnvironmentEndpoint] :ivar next_link: The continuation token. :vartype next_link: str """ _validation = { "value": {"readonly": True}, } _attribute_map = { "value": {"key": "value", "type": "[OutboundEnvironmentEndpoint]"}, "next_link": {"key": "nextLink", "type": "str"}, } def __init__(self, *, next_link: Optional[str] = None, **kwargs: Any) -> None: """ :keyword next_link: The continuation token. :paramtype next_link: str """ super().__init__(**kwargs) self.value = None self.next_link = next_link class Pool(ProxyResource): # pylint: disable=too-many-instance-attributes """Contains information about a pool. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: The ID of the resource. :vartype id: str :ivar name: The name of the resource. :vartype name: str :ivar type: The type of the resource. :vartype type: str :ivar etag: The ETag of the resource, used for concurrency statements. :vartype etag: str :ivar identity: The type of identity used for the Batch Pool. :vartype identity: ~azure.mgmt.batch.models.BatchPoolIdentity :ivar display_name: The display name need not be unique and can contain any Unicode characters up to a maximum length of 1024. :vartype display_name: str :ivar last_modified: This is the last time at which the pool level data, such as the targetDedicatedNodes or autoScaleSettings, changed. It does not factor in node-level changes such as a compute node changing state. :vartype last_modified: ~datetime.datetime :ivar creation_time: The creation time of the pool. :vartype creation_time: ~datetime.datetime :ivar provisioning_state: The current state of the pool. Known values are: "Succeeded" and "Deleting". :vartype provisioning_state: str or ~azure.mgmt.batch.models.PoolProvisioningState :ivar provisioning_state_transition_time: The time at which the pool entered its current state. :vartype provisioning_state_transition_time: ~datetime.datetime :ivar allocation_state: Whether the pool is resizing. Known values are: "Steady", "Resizing", and "Stopping". :vartype allocation_state: str or ~azure.mgmt.batch.models.AllocationState :ivar allocation_state_transition_time: The time at which the pool entered its current allocation state. :vartype allocation_state_transition_time: ~datetime.datetime :ivar vm_size: For information about available sizes of virtual machines for Cloud Services pools (pools created with cloudServiceConfiguration), see Sizes for Cloud Services (https://azure.microsoft.com/documentation/articles/cloud-services-sizes-specs/). Batch supports all Cloud Services VM sizes except ExtraSmall. For information about available VM sizes for pools using images from the Virtual Machines Marketplace (pools created with virtualMachineConfiguration) see Sizes for Virtual Machines (Linux) (https://azure.microsoft.com/documentation/articles/virtual-machines-linux-sizes/) or Sizes for Virtual Machines (Windows) (https://azure.microsoft.com/documentation/articles/virtual-machines-windows-sizes/). Batch supports all Azure VM sizes except STANDARD_A0 and those with premium storage (STANDARD_GS, STANDARD_DS, and STANDARD_DSV2 series). :vartype vm_size: str :ivar deployment_configuration: Using CloudServiceConfiguration specifies that the nodes should be creating using Azure Cloud Services (PaaS), while VirtualMachineConfiguration uses Azure Virtual Machines (IaaS). :vartype deployment_configuration: ~azure.mgmt.batch.models.DeploymentConfiguration :ivar current_dedicated_nodes: The number of dedicated compute nodes currently in the pool. :vartype current_dedicated_nodes: int :ivar current_low_priority_nodes: The number of Spot/low-priority compute nodes currently in the pool. :vartype current_low_priority_nodes: int :ivar scale_settings: Defines the desired size of the pool. This can either be 'fixedScale' where the requested targetDedicatedNodes is specified, or 'autoScale' which defines a formula which is periodically reevaluated. If this property is not specified, the pool will have a fixed scale with 0 targetDedicatedNodes. :vartype scale_settings: ~azure.mgmt.batch.models.ScaleSettings :ivar auto_scale_run: This property is set only if the pool automatically scales, i.e. autoScaleSettings are used. :vartype auto_scale_run: ~azure.mgmt.batch.models.AutoScaleRun :ivar inter_node_communication: This imposes restrictions on which nodes can be assigned to the pool. Enabling this value can reduce the chance of the requested number of nodes to be allocated in the pool. If not specified, this value defaults to 'Disabled'. Known values are: "Enabled" and "Disabled". :vartype inter_node_communication: str or ~azure.mgmt.batch.models.InterNodeCommunicationState :ivar network_configuration: The network configuration for a pool. :vartype network_configuration: ~azure.mgmt.batch.models.NetworkConfiguration :ivar task_slots_per_node: The default value is 1. The maximum value is the smaller of 4 times the number of cores of the vmSize of the pool or 256. :vartype task_slots_per_node: int :ivar task_scheduling_policy: If not specified, the default is spread. :vartype task_scheduling_policy: ~azure.mgmt.batch.models.TaskSchedulingPolicy :ivar user_accounts: The list of user accounts to be created on each node in the pool. :vartype user_accounts: list[~azure.mgmt.batch.models.UserAccount] :ivar metadata: The Batch service does not assign any meaning to metadata; it is solely for the use of user code. :vartype metadata: list[~azure.mgmt.batch.models.MetadataItem] :ivar start_task: In an PATCH (update) operation, this property can be set to an empty object to remove the start task from the pool. :vartype start_task: ~azure.mgmt.batch.models.StartTask :ivar certificates: For Windows compute nodes, the Batch service installs the certificates to the specified certificate store and location. For Linux compute nodes, the certificates are stored in a directory inside the task working directory and an environment variable AZ_BATCH_CERTIFICATES_DIR is supplied to the task to query for this location. For certificates with visibility of 'remoteUser', a 'certs' directory is created in the user's home directory (e.g., /home/{user-name}/certs) and certificates are placed in that directory. Warning: This property is deprecated and will be removed after February, 2024. Please use the `Azure KeyVault Extension <https://learn.microsoft.com/azure/batch/batch-certificate-migration-guide>`_ instead. :vartype certificates: list[~azure.mgmt.batch.models.CertificateReference] :ivar application_packages: Changes to application package references affect all new compute nodes joining the pool, but do not affect compute nodes that are already in the pool until they are rebooted or reimaged. There is a maximum of 10 application package references on any given pool. :vartype application_packages: list[~azure.mgmt.batch.models.ApplicationPackageReference] :ivar application_licenses: The list of application licenses must be a subset of available Batch service application licenses. If a license is requested which is not supported, pool creation will fail. :vartype application_licenses: list[str] :ivar resize_operation_status: Describes either the current operation (if the pool AllocationState is Resizing) or the previously completed operation (if the AllocationState is Steady). :vartype resize_operation_status: ~azure.mgmt.batch.models.ResizeOperationStatus :ivar mount_configuration: This supports Azure Files, NFS, CIFS/SMB, and Blobfuse. :vartype mount_configuration: list[~azure.mgmt.batch.models.MountConfiguration] :ivar target_node_communication_mode: If omitted, the default value is Default. Known values are: "Default", "Classic", and "Simplified". :vartype target_node_communication_mode: str or ~azure.mgmt.batch.models.NodeCommunicationMode :ivar current_node_communication_mode: Determines how a pool communicates with the Batch service. Known values are: "Default", "Classic", and "Simplified". :vartype current_node_communication_mode: str or ~azure.mgmt.batch.models.NodeCommunicationMode """ _validation = { "id": {"readonly": True}, "name": {"readonly": True}, "type": {"readonly": True}, "etag": {"readonly": True}, "last_modified": {"readonly": True}, "creation_time": {"readonly": True}, "provisioning_state": {"readonly": True}, "provisioning_state_transition_time": {"readonly": True}, "allocation_state": {"readonly": True}, "allocation_state_transition_time": {"readonly": True}, "current_dedicated_nodes": {"readonly": True}, "current_low_priority_nodes": {"readonly": True}, "auto_scale_run": {"readonly": True}, "resize_operation_status": {"readonly": True}, "current_node_communication_mode": {"readonly": True}, } _attribute_map = { "id": {"key": "id", "type": "str"}, "name": {"key": "name", "type": "str"}, "type": {"key": "type", "type": "str"}, "etag": {"key": "etag", "type": "str"}, "identity": {"key": "identity", "type": "BatchPoolIdentity"}, "display_name": {"key": "properties.displayName", "type": "str"}, "last_modified": {"key": "properties.lastModified", "type": "iso-8601"}, "creation_time": {"key": "properties.creationTime", "type": "iso-8601"}, "provisioning_state": {"key": "properties.provisioningState", "type": "str"}, "provisioning_state_transition_time": {"key": "properties.provisioningStateTransitionTime", "type": "iso-8601"}, "allocation_state": {"key": "properties.allocationState", "type": "str"}, "allocation_state_transition_time": {"key": "properties.allocationStateTransitionTime", "type": "iso-8601"}, "vm_size": {"key": "properties.vmSize", "type": "str"}, "deployment_configuration": {"key": "properties.deploymentConfiguration", "type": "DeploymentConfiguration"}, "current_dedicated_nodes": {"key": "properties.currentDedicatedNodes", "type": "int"}, "current_low_priority_nodes": {"key": "properties.currentLowPriorityNodes", "type": "int"}, "scale_settings": {"key": "properties.scaleSettings", "type": "ScaleSettings"}, "auto_scale_run": {"key": "properties.autoScaleRun", "type": "AutoScaleRun"}, "inter_node_communication": {"key": "properties.interNodeCommunication", "type": "str"}, "network_configuration": {"key": "properties.networkConfiguration", "type": "NetworkConfiguration"}, "task_slots_per_node": {"key": "properties.taskSlotsPerNode", "type": "int"}, "task_scheduling_policy": {"key": "properties.taskSchedulingPolicy", "type": "TaskSchedulingPolicy"}, "user_accounts": {"key": "properties.userAccounts", "type": "[UserAccount]"}, "metadata": {"key": "properties.metadata", "type": "[MetadataItem]"}, "start_task": {"key": "properties.startTask", "type": "StartTask"}, "certificates": {"key": "properties.certificates", "type": "[CertificateReference]"}, "application_packages": {"key": "properties.applicationPackages", "type": "[ApplicationPackageReference]"}, "application_licenses": {"key": "properties.applicationLicenses", "type": "[str]"}, "resize_operation_status": {"key": "properties.resizeOperationStatus", "type": "ResizeOperationStatus"}, "mount_configuration": {"key": "properties.mountConfiguration", "type": "[MountConfiguration]"}, "target_node_communication_mode": {"key": "properties.targetNodeCommunicationMode", "type": "str"}, "current_node_communication_mode": {"key": "properties.currentNodeCommunicationMode", "type": "str"}, } def __init__( # pylint: disable=too-many-locals self, *, identity: Optional["_models.BatchPoolIdentity"] = None, display_name: Optional[str] = None, vm_size: Optional[str] = None, deployment_configuration: Optional["_models.DeploymentConfiguration"] = None, scale_settings: Optional["_models.ScaleSettings"] = None, inter_node_communication: Optional[Union[str, "_models.InterNodeCommunicationState"]] = None, network_configuration: Optional["_models.NetworkConfiguration"] = None, task_slots_per_node: Optional[int] = None, task_scheduling_policy: Optional["_models.TaskSchedulingPolicy"] = None, user_accounts: Optional[List["_models.UserAccount"]] = None, metadata: Optional[List["_models.MetadataItem"]] = None, start_task: Optional["_models.StartTask"] = None, certificates: Optional[List["_models.CertificateReference"]] = None, application_packages: Optional[List["_models.ApplicationPackageReference"]] = None, application_licenses: Optional[List[str]] = None, mount_configuration: Optional[List["_models.MountConfiguration"]] = None, target_node_communication_mode: Optional[Union[str, "_models.NodeCommunicationMode"]] = None, **kwargs: Any ) -> None: """ :keyword identity: The type of identity used for the Batch Pool. :paramtype identity: ~azure.mgmt.batch.models.BatchPoolIdentity :keyword display_name: The display name need not be unique and can contain any Unicode characters up to a maximum length of 1024. :paramtype display_name: str :keyword vm_size: For information about available sizes of virtual machines for Cloud Services pools (pools created with cloudServiceConfiguration), see Sizes for Cloud Services (https://azure.microsoft.com/documentation/articles/cloud-services-sizes-specs/). Batch supports all Cloud Services VM sizes except ExtraSmall. For information about available VM sizes for pools using images from the Virtual Machines Marketplace (pools created with virtualMachineConfiguration) see Sizes for Virtual Machines (Linux) (https://azure.microsoft.com/documentation/articles/virtual-machines-linux-sizes/) or Sizes for Virtual Machines (Windows) (https://azure.microsoft.com/documentation/articles/virtual-machines-windows-sizes/). Batch supports all Azure VM sizes except STANDARD_A0 and those with premium storage (STANDARD_GS, STANDARD_DS, and STANDARD_DSV2 series). :paramtype vm_size: str :keyword deployment_configuration: Using CloudServiceConfiguration specifies that the nodes should be creating using Azure Cloud Services (PaaS), while VirtualMachineConfiguration uses Azure Virtual Machines (IaaS). :paramtype deployment_configuration: ~azure.mgmt.batch.models.DeploymentConfiguration :keyword scale_settings: Defines the desired size of the pool. This can either be 'fixedScale' where the requested targetDedicatedNodes is specified, or 'autoScale' which defines a formula which is periodically reevaluated. If this property is not specified, the pool will have a fixed scale with 0 targetDedicatedNodes. :paramtype scale_settings: ~azure.mgmt.batch.models.ScaleSettings :keyword inter_node_communication: This imposes restrictions on which nodes can be assigned to the pool. Enabling this value can reduce the chance of the requested number of nodes to be allocated in the pool. If not specified, this value defaults to 'Disabled'. Known values are: "Enabled" and "Disabled". :paramtype inter_node_communication: str or ~azure.mgmt.batch.models.InterNodeCommunicationState :keyword network_configuration: The network configuration for a pool. :paramtype network_configuration: ~azure.mgmt.batch.models.NetworkConfiguration :keyword task_slots_per_node: The default value is 1. The maximum value is the smaller of 4 times the number of cores of the vmSize of the pool or 256. :paramtype task_slots_per_node: int :keyword task_scheduling_policy: If not specified, the default is spread. :paramtype task_scheduling_policy: ~azure.mgmt.batch.models.TaskSchedulingPolicy :keyword user_accounts: The list of user accounts to be created on each node in the pool. :paramtype user_accounts: list[~azure.mgmt.batch.models.UserAccount] :keyword metadata: The Batch service does not assign any meaning to metadata; it is solely for the use of user code. :paramtype metadata: list[~azure.mgmt.batch.models.MetadataItem] :keyword start_task: In an PATCH (update) operation, this property can be set to an empty object to remove the start task from the pool. :paramtype start_task: ~azure.mgmt.batch.models.StartTask :keyword certificates: For Windows compute nodes, the Batch service installs the certificates to the specified certificate store and location. For Linux compute nodes, the certificates are stored in a directory inside the task working directory and an environment variable AZ_BATCH_CERTIFICATES_DIR is supplied to the task to query for this location. For certificates with visibility of 'remoteUser', a 'certs' directory is created in the user's home directory (e.g., /home/{user-name}/certs) and certificates are placed in that directory. Warning: This property is deprecated and will be removed after February, 2024. Please use the `Azure KeyVault Extension <https://learn.microsoft.com/azure/batch/batch-certificate-migration-guide>`_ instead. :paramtype certificates: list[~azure.mgmt.batch.models.CertificateReference] :keyword application_packages: Changes to application package references affect all new compute nodes joining the pool, but do not affect compute nodes that are already in the pool until they are rebooted or reimaged. There is a maximum of 10 application package references on any given pool. :paramtype application_packages: list[~azure.mgmt.batch.models.ApplicationPackageReference] :keyword application_licenses: The list of application licenses must be a subset of available Batch service application licenses. If a license is requested which is not supported, pool creation will fail. :paramtype application_licenses: list[str] :keyword mount_configuration: This supports Azure Files, NFS, CIFS/SMB, and Blobfuse. :paramtype mount_configuration: list[~azure.mgmt.batch.models.MountConfiguration] :keyword target_node_communication_mode: If omitted, the default value is Default. Known values are: "Default", "Classic", and "Simplified". :paramtype target_node_communication_mode: str or ~azure.mgmt.batch.models.NodeCommunicationMode """ super().__init__(**kwargs) self.identity = identity self.display_name = display_name self.last_modified = None self.creation_time = None self.provisioning_state = None self.provisioning_state_transition_time = None self.allocation_state = None self.allocation_state_transition_time = None self.vm_size = vm_size self.deployment_configuration = deployment_configuration self.current_dedicated_nodes = None self.current_low_priority_nodes = None self.scale_settings = scale_settings self.auto_scale_run = None self.inter_node_communication = inter_node_communication self.network_configuration = network_configuration self.task_slots_per_node = task_slots_per_node self.task_scheduling_policy = task_scheduling_policy self.user_accounts = user_accounts self.metadata = metadata self.start_task = start_task self.certificates = certificates self.application_packages = application_packages self.application_licenses = application_licenses self.resize_operation_status = None self.mount_configuration = mount_configuration self.target_node_communication_mode = target_node_communication_mode self.current_node_communication_mode = None class PoolEndpointConfiguration(_serialization.Model): """The endpoint configuration for a pool. All required parameters must be populated in order to send to Azure. :ivar inbound_nat_pools: The maximum number of inbound NAT pools per Batch pool is 5. If the maximum number of inbound NAT pools is exceeded the request fails with HTTP status code 400. This cannot be specified if the IPAddressProvisioningType is NoPublicIPAddresses. Required. :vartype inbound_nat_pools: list[~azure.mgmt.batch.models.InboundNatPool] """ _validation = { "inbound_nat_pools": {"required": True}, } _attribute_map = { "inbound_nat_pools": {"key": "inboundNatPools", "type": "[InboundNatPool]"}, } def __init__(self, *, inbound_nat_pools: List["_models.InboundNatPool"], **kwargs: Any) -> None: """ :keyword inbound_nat_pools: The maximum number of inbound NAT pools per Batch pool is 5. If the maximum number of inbound NAT pools is exceeded the request fails with HTTP status code 400. This cannot be specified if the IPAddressProvisioningType is NoPublicIPAddresses. Required. :paramtype inbound_nat_pools: list[~azure.mgmt.batch.models.InboundNatPool] """ super().__init__(**kwargs) self.inbound_nat_pools = inbound_nat_pools class PrivateEndpoint(_serialization.Model): """The private endpoint of the private endpoint connection. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: The ARM resource identifier of the private endpoint. This is of the form /subscriptions/{subscription}/resourceGroups/{group}/providers/Microsoft.Network/privateEndpoints/{privateEndpoint}. :vartype id: str """ _validation = { "id": {"readonly": True}, } _attribute_map = { "id": {"key": "id", "type": "str"}, } def __init__(self, **kwargs: Any) -> None: """ """ super().__init__(**kwargs) self.id = None class PrivateEndpointConnection(ProxyResource): """Contains information about a private link resource. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: The ID of the resource. :vartype id: str :ivar name: The name of the resource. :vartype name: str :ivar type: The type of the resource. :vartype type: str :ivar etag: The ETag of the resource, used for concurrency statements. :vartype etag: str :ivar provisioning_state: The provisioning state of the private endpoint connection. Known values are: "Creating", "Updating", "Deleting", "Succeeded", "Failed", and "Cancelled". :vartype provisioning_state: str or ~azure.mgmt.batch.models.PrivateEndpointConnectionProvisioningState :ivar private_endpoint: The private endpoint of the private endpoint connection. :vartype private_endpoint: ~azure.mgmt.batch.models.PrivateEndpoint :ivar group_ids: The value has one and only one group id. :vartype group_ids: list[str] :ivar private_link_service_connection_state: The private link service connection state of the private endpoint connection. :vartype private_link_service_connection_state: ~azure.mgmt.batch.models.PrivateLinkServiceConnectionState """ _validation = { "id": {"readonly": True}, "name": {"readonly": True}, "type": {"readonly": True}, "etag": {"readonly": True}, "provisioning_state": {"readonly": True}, "private_endpoint": {"readonly": True}, "group_ids": {"readonly": True}, } _attribute_map = { "id": {"key": "id", "type": "str"}, "name": {"key": "name", "type": "str"}, "type": {"key": "type", "type": "str"}, "etag": {"key": "etag", "type": "str"}, "provisioning_state": {"key": "properties.provisioningState", "type": "str"}, "private_endpoint": {"key": "properties.privateEndpoint", "type": "PrivateEndpoint"}, "group_ids": {"key": "properties.groupIds", "type": "[str]"}, "private_link_service_connection_state": { "key": "properties.privateLinkServiceConnectionState", "type": "PrivateLinkServiceConnectionState", }, } def __init__( self, *, private_link_service_connection_state: Optional["_models.PrivateLinkServiceConnectionState"] = None, **kwargs: Any ) -> None: """ :keyword private_link_service_connection_state: The private link service connection state of the private endpoint connection. :paramtype private_link_service_connection_state: ~azure.mgmt.batch.models.PrivateLinkServiceConnectionState """ super().__init__(**kwargs) self.provisioning_state = None self.private_endpoint = None self.group_ids = None self.private_link_service_connection_state = private_link_service_connection_state class PrivateLinkResource(ProxyResource): """Contains information about a private link resource. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: The ID of the resource. :vartype id: str :ivar name: The name of the resource. :vartype name: str :ivar type: The type of the resource. :vartype type: str :ivar etag: The ETag of the resource, used for concurrency statements. :vartype etag: str :ivar group_id: The group id is used to establish the private link connection. :vartype group_id: str :ivar required_members: The list of required members that are used to establish the private link connection. :vartype required_members: list[str] :ivar required_zone_names: The list of required zone names for the private DNS resource name. :vartype required_zone_names: list[str] """ _validation = { "id": {"readonly": True}, "name": {"readonly": True}, "type": {"readonly": True}, "etag": {"readonly": True}, "group_id": {"readonly": True}, "required_members": {"readonly": True}, "required_zone_names": {"readonly": True}, } _attribute_map = { "id": {"key": "id", "type": "str"}, "name": {"key": "name", "type": "str"}, "type": {"key": "type", "type": "str"}, "etag": {"key": "etag", "type": "str"}, "group_id": {"key": "properties.groupId", "type": "str"}, "required_members": {"key": "properties.requiredMembers", "type": "[str]"}, "required_zone_names": {"key": "properties.requiredZoneNames", "type": "[str]"}, } def __init__(self, **kwargs: Any) -> None: """ """ super().__init__(**kwargs) self.group_id = None self.required_members = None self.required_zone_names = None class PrivateLinkServiceConnectionState(_serialization.Model): """The private link service connection state of the private endpoint connection. Variables are only populated by the server, and will be ignored when sending a request. All required parameters must be populated in order to send to Azure. :ivar status: The status of the Batch private endpoint connection. Required. Known values are: "Approved", "Pending", "Rejected", and "Disconnected". :vartype status: str or ~azure.mgmt.batch.models.PrivateLinkServiceConnectionStatus :ivar description: Description of the private Connection state. :vartype description: str :ivar actions_required: Action required on the private connection state. :vartype actions_required: str """ _validation = { "status": {"required": True}, "actions_required": {"readonly": True}, } _attribute_map = { "status": {"key": "status", "type": "str"}, "description": {"key": "description", "type": "str"}, "actions_required": {"key": "actionsRequired", "type": "str"}, } def __init__( self, *, status: Union[str, "_models.PrivateLinkServiceConnectionStatus"], description: Optional[str] = None, **kwargs: Any ) -> None: """ :keyword status: The status of the Batch private endpoint connection. Required. Known values are: "Approved", "Pending", "Rejected", and "Disconnected". :paramtype status: str or ~azure.mgmt.batch.models.PrivateLinkServiceConnectionStatus :keyword description: Description of the private Connection state. :paramtype description: str """ super().__init__(**kwargs) self.status = status self.description = description self.actions_required = None class PublicIPAddressConfiguration(_serialization.Model): """The public IP Address configuration of the networking configuration of a Pool. :ivar provision: The default value is BatchManaged. Known values are: "BatchManaged", "UserManaged", and "NoPublicIPAddresses". :vartype provision: str or ~azure.mgmt.batch.models.IPAddressProvisioningType :ivar ip_address_ids: The number of IPs specified here limits the maximum size of the Pool - 100 dedicated nodes or 100 Spot/low-priority nodes can be allocated for each public IP. For example, a pool needing 250 dedicated VMs would need at least 3 public IPs specified. Each element of this collection is of the form: /subscriptions/{subscription}/resourceGroups/{group}/providers/Microsoft.Network/publicIPAddresses/{ip}. :vartype ip_address_ids: list[str] """ _attribute_map = { "provision": {"key": "provision", "type": "str"}, "ip_address_ids": {"key": "ipAddressIds", "type": "[str]"}, } def __init__( self, *, provision: Optional[Union[str, "_models.IPAddressProvisioningType"]] = None, ip_address_ids: Optional[List[str]] = None, **kwargs: Any ) -> None: """ :keyword provision: The default value is BatchManaged. Known values are: "BatchManaged", "UserManaged", and "NoPublicIPAddresses". :paramtype provision: str or ~azure.mgmt.batch.models.IPAddressProvisioningType :keyword ip_address_ids: The number of IPs specified here limits the maximum size of the Pool - 100 dedicated nodes or 100 Spot/low-priority nodes can be allocated for each public IP. For example, a pool needing 250 dedicated VMs would need at least 3 public IPs specified. Each element of this collection is of the form: /subscriptions/{subscription}/resourceGroups/{group}/providers/Microsoft.Network/publicIPAddresses/{ip}. :paramtype ip_address_ids: list[str] """ super().__init__(**kwargs) self.provision = provision self.ip_address_ids = ip_address_ids class ResizeError(_serialization.Model): """An error that occurred when resizing a pool. All required parameters must be populated in order to send to Azure. :ivar code: An identifier for the error. Codes are invariant and are intended to be consumed programmatically. Required. :vartype code: str :ivar message: A message describing the error, intended to be suitable for display in a user interface. Required. :vartype message: str :ivar details: Additional details about the error. :vartype details: list[~azure.mgmt.batch.models.ResizeError] """ _validation = { "code": {"required": True}, "message": {"required": True}, } _attribute_map = { "code": {"key": "code", "type": "str"}, "message": {"key": "message", "type": "str"}, "details": {"key": "details", "type": "[ResizeError]"}, } def __init__( self, *, code: str, message: str, details: Optional[List["_models.ResizeError"]] = None, **kwargs: Any ) -> None: """ :keyword code: An identifier for the error. Codes are invariant and are intended to be consumed programmatically. Required. :paramtype code: str :keyword message: A message describing the error, intended to be suitable for display in a user interface. Required. :paramtype message: str :keyword details: Additional details about the error. :paramtype details: list[~azure.mgmt.batch.models.ResizeError] """ super().__init__(**kwargs) self.code = code self.message = message self.details = details class ResizeOperationStatus(_serialization.Model): """Describes either the current operation (if the pool AllocationState is Resizing) or the previously completed operation (if the AllocationState is Steady). :ivar target_dedicated_nodes: The desired number of dedicated compute nodes in the pool. :vartype target_dedicated_nodes: int :ivar target_low_priority_nodes: The desired number of Spot/low-priority compute nodes in the pool. :vartype target_low_priority_nodes: int :ivar resize_timeout: The default value is 15 minutes. The minimum value is 5 minutes. If you specify a value less than 5 minutes, the Batch service returns an error; if you are calling the REST API directly, the HTTP status code is 400 (Bad Request). :vartype resize_timeout: ~datetime.timedelta :ivar node_deallocation_option: The default value is requeue. Known values are: "Requeue", "Terminate", "TaskCompletion", and "RetainedData". :vartype node_deallocation_option: str or ~azure.mgmt.batch.models.ComputeNodeDeallocationOption :ivar start_time: The time when this resize operation was started. :vartype start_time: ~datetime.datetime :ivar errors: This property is set only if an error occurred during the last pool resize, and only when the pool allocationState is Steady. :vartype errors: list[~azure.mgmt.batch.models.ResizeError] """ _attribute_map = { "target_dedicated_nodes": {"key": "targetDedicatedNodes", "type": "int"}, "target_low_priority_nodes": {"key": "targetLowPriorityNodes", "type": "int"}, "resize_timeout": {"key": "resizeTimeout", "type": "duration"}, "node_deallocation_option": {"key": "nodeDeallocationOption", "type": "str"}, "start_time": {"key": "startTime", "type": "iso-8601"}, "errors": {"key": "errors", "type": "[ResizeError]"}, } def __init__( self, *, target_dedicated_nodes: Optional[int] = None, target_low_priority_nodes: Optional[int] = None, resize_timeout: Optional[datetime.timedelta] = None, node_deallocation_option: Optional[Union[str, "_models.ComputeNodeDeallocationOption"]] = None, start_time: Optional[datetime.datetime] = None, errors: Optional[List["_models.ResizeError"]] = None, **kwargs: Any ) -> None: """ :keyword target_dedicated_nodes: The desired number of dedicated compute nodes in the pool. :paramtype target_dedicated_nodes: int :keyword target_low_priority_nodes: The desired number of Spot/low-priority compute nodes in the pool. :paramtype target_low_priority_nodes: int :keyword resize_timeout: The default value is 15 minutes. The minimum value is 5 minutes. If you specify a value less than 5 minutes, the Batch service returns an error; if you are calling the REST API directly, the HTTP status code is 400 (Bad Request). :paramtype resize_timeout: ~datetime.timedelta :keyword node_deallocation_option: The default value is requeue. Known values are: "Requeue", "Terminate", "TaskCompletion", and "RetainedData". :paramtype node_deallocation_option: str or ~azure.mgmt.batch.models.ComputeNodeDeallocationOption :keyword start_time: The time when this resize operation was started. :paramtype start_time: ~datetime.datetime :keyword errors: This property is set only if an error occurred during the last pool resize, and only when the pool allocationState is Steady. :paramtype errors: list[~azure.mgmt.batch.models.ResizeError] """ super().__init__(**kwargs) self.target_dedicated_nodes = target_dedicated_nodes self.target_low_priority_nodes = target_low_priority_nodes self.resize_timeout = resize_timeout self.node_deallocation_option = node_deallocation_option self.start_time = start_time self.errors = errors class ResourceFile(_serialization.Model): """A single file or multiple files to be downloaded to a compute node. :ivar auto_storage_container_name: The autoStorageContainerName, storageContainerUrl and httpUrl properties are mutually exclusive and one of them must be specified. :vartype auto_storage_container_name: str :ivar storage_container_url: The autoStorageContainerName, storageContainerUrl and httpUrl properties are mutually exclusive and one of them must be specified. This URL must be readable and listable from compute nodes. There are three ways to get such a URL for a container in Azure storage: include a Shared Access Signature (SAS) granting read and list permissions on the container, use a managed identity with read and list permissions, or set the ACL for the container to allow public access. :vartype storage_container_url: str :ivar http_url: The autoStorageContainerName, storageContainerUrl and httpUrl properties are mutually exclusive and one of them must be specified. If the URL points to Azure Blob Storage, it must be readable from compute nodes. There are three ways to get such a URL for a blob in Azure storage: include a Shared Access Signature (SAS) granting read permissions on the blob, use a managed identity with read permission, or set the ACL for the blob or its container to allow public access. :vartype http_url: str :ivar blob_prefix: The property is valid only when autoStorageContainerName or storageContainerUrl is used. This prefix can be a partial filename or a subdirectory. If a prefix is not specified, all the files in the container will be downloaded. :vartype blob_prefix: str :ivar file_path: If the httpUrl property is specified, the filePath is required and describes the path which the file will be downloaded to, including the filename. Otherwise, if the autoStorageContainerName or storageContainerUrl property is specified, filePath is optional and is the directory to download the files to. In the case where filePath is used as a directory, any directory structure already associated with the input data will be retained in full and appended to the specified filePath directory. The specified relative path cannot break out of the task's working directory (for example by using '..'). :vartype file_path: str :ivar file_mode: This property applies only to files being downloaded to Linux compute nodes. It will be ignored if it is specified for a resourceFile which will be downloaded to a Windows node. If this property is not specified for a Linux node, then a default value of 0770 is applied to the file. :vartype file_mode: str :ivar identity_reference: The reference to a user assigned identity associated with the Batch pool which a compute node will use. :vartype identity_reference: ~azure.mgmt.batch.models.ComputeNodeIdentityReference """ _attribute_map = { "auto_storage_container_name": {"key": "autoStorageContainerName", "type": "str"}, "storage_container_url": {"key": "storageContainerUrl", "type": "str"}, "http_url": {"key": "httpUrl", "type": "str"}, "blob_prefix": {"key": "blobPrefix", "type": "str"}, "file_path": {"key": "filePath", "type": "str"}, "file_mode": {"key": "fileMode", "type": "str"}, "identity_reference": {"key": "identityReference", "type": "ComputeNodeIdentityReference"}, } def __init__( self, *, auto_storage_container_name: Optional[str] = None, storage_container_url: Optional[str] = None, http_url: Optional[str] = None, blob_prefix: Optional[str] = None, file_path: Optional[str] = None, file_mode: Optional[str] = None, identity_reference: Optional["_models.ComputeNodeIdentityReference"] = None, **kwargs: Any ) -> None: """ :keyword auto_storage_container_name: The autoStorageContainerName, storageContainerUrl and httpUrl properties are mutually exclusive and one of them must be specified. :paramtype auto_storage_container_name: str :keyword storage_container_url: The autoStorageContainerName, storageContainerUrl and httpUrl properties are mutually exclusive and one of them must be specified. This URL must be readable and listable from compute nodes. There are three ways to get such a URL for a container in Azure storage: include a Shared Access Signature (SAS) granting read and list permissions on the container, use a managed identity with read and list permissions, or set the ACL for the container to allow public access. :paramtype storage_container_url: str :keyword http_url: The autoStorageContainerName, storageContainerUrl and httpUrl properties are mutually exclusive and one of them must be specified. If the URL points to Azure Blob Storage, it must be readable from compute nodes. There are three ways to get such a URL for a blob in Azure storage: include a Shared Access Signature (SAS) granting read permissions on the blob, use a managed identity with read permission, or set the ACL for the blob or its container to allow public access. :paramtype http_url: str :keyword blob_prefix: The property is valid only when autoStorageContainerName or storageContainerUrl is used. This prefix can be a partial filename or a subdirectory. If a prefix is not specified, all the files in the container will be downloaded. :paramtype blob_prefix: str :keyword file_path: If the httpUrl property is specified, the filePath is required and describes the path which the file will be downloaded to, including the filename. Otherwise, if the autoStorageContainerName or storageContainerUrl property is specified, filePath is optional and is the directory to download the files to. In the case where filePath is used as a directory, any directory structure already associated with the input data will be retained in full and appended to the specified filePath directory. The specified relative path cannot break out of the task's working directory (for example by using '..'). :paramtype file_path: str :keyword file_mode: This property applies only to files being downloaded to Linux compute nodes. It will be ignored if it is specified for a resourceFile which will be downloaded to a Windows node. If this property is not specified for a Linux node, then a default value of 0770 is applied to the file. :paramtype file_mode: str :keyword identity_reference: The reference to a user assigned identity associated with the Batch pool which a compute node will use. :paramtype identity_reference: ~azure.mgmt.batch.models.ComputeNodeIdentityReference """ super().__init__(**kwargs) self.auto_storage_container_name = auto_storage_container_name self.storage_container_url = storage_container_url self.http_url = http_url self.blob_prefix = blob_prefix self.file_path = file_path self.file_mode = file_mode self.identity_reference = identity_reference class ScaleSettings(_serialization.Model): """Defines the desired size of the pool. This can either be 'fixedScale' where the requested targetDedicatedNodes is specified, or 'autoScale' which defines a formula which is periodically reevaluated. If this property is not specified, the pool will have a fixed scale with 0 targetDedicatedNodes. :ivar fixed_scale: This property and autoScale are mutually exclusive and one of the properties must be specified. :vartype fixed_scale: ~azure.mgmt.batch.models.FixedScaleSettings :ivar auto_scale: This property and fixedScale are mutually exclusive and one of the properties must be specified. :vartype auto_scale: ~azure.mgmt.batch.models.AutoScaleSettings """ _attribute_map = { "fixed_scale": {"key": "fixedScale", "type": "FixedScaleSettings"}, "auto_scale": {"key": "autoScale", "type": "AutoScaleSettings"}, } def __init__( self, *, fixed_scale: Optional["_models.FixedScaleSettings"] = None, auto_scale: Optional["_models.AutoScaleSettings"] = None, **kwargs: Any ) -> None: """ :keyword fixed_scale: This property and autoScale are mutually exclusive and one of the properties must be specified. :paramtype fixed_scale: ~azure.mgmt.batch.models.FixedScaleSettings :keyword auto_scale: This property and fixedScale are mutually exclusive and one of the properties must be specified. :paramtype auto_scale: ~azure.mgmt.batch.models.AutoScaleSettings """ super().__init__(**kwargs) self.fixed_scale = fixed_scale self.auto_scale = auto_scale class SkuCapability(_serialization.Model): """A SKU capability, such as the number of cores. Variables are only populated by the server, and will be ignored when sending a request. :ivar name: The name of the feature. :vartype name: str :ivar value: The value of the feature. :vartype value: str """ _validation = { "name": {"readonly": True}, "value": {"readonly": True}, } _attribute_map = { "name": {"key": "name", "type": "str"}, "value": {"key": "value", "type": "str"}, } def __init__(self, **kwargs: Any) -> None: """ """ super().__init__(**kwargs) self.name = None self.value = None class StartTask(_serialization.Model): """In some cases the start task may be re-run even though the node was not rebooted. Due to this, start tasks should be idempotent and exit gracefully if the setup they're performing has already been done. Special care should be taken to avoid start tasks which create breakaway process or install/launch services from the start task working directory, as this will block Batch from being able to re-run the start task. :ivar command_line: The command line does not run under a shell, and therefore cannot take advantage of shell features such as environment variable expansion. If you want to take advantage of such features, you should invoke the shell in the command line, for example using "cmd /c MyCommand" in Windows or "/bin/sh -c MyCommand" in Linux. Required if any other properties of the startTask are specified. :vartype command_line: str :ivar resource_files: A list of files that the Batch service will download to the compute node before running the command line. :vartype resource_files: list[~azure.mgmt.batch.models.ResourceFile] :ivar environment_settings: A list of environment variable settings for the start task. :vartype environment_settings: list[~azure.mgmt.batch.models.EnvironmentSetting] :ivar user_identity: If omitted, the task runs as a non-administrative user unique to the task. :vartype user_identity: ~azure.mgmt.batch.models.UserIdentity :ivar max_task_retry_count: The Batch service retries a task if its exit code is nonzero. Note that this value specifically controls the number of retries. The Batch service will try the task once, and may then retry up to this limit. For example, if the maximum retry count is 3, Batch tries the task up to 4 times (one initial try and 3 retries). If the maximum retry count is 0, the Batch service does not retry the task. If the maximum retry count is -1, the Batch service retries the task without limit. :vartype max_task_retry_count: int :ivar wait_for_success: If true and the start task fails on a compute node, the Batch service retries the start task up to its maximum retry count (maxTaskRetryCount). If the task has still not completed successfully after all retries, then the Batch service marks the compute node unusable, and will not schedule tasks to it. This condition can be detected via the node state and scheduling error detail. If false, the Batch service will not wait for the start task to complete. In this case, other tasks can start executing on the compute node while the start task is still running; and even if the start task fails, new tasks will continue to be scheduled on the node. The default is true. :vartype wait_for_success: bool :ivar container_settings: When this is specified, all directories recursively below the AZ_BATCH_NODE_ROOT_DIR (the root of Azure Batch directories on the node) are mapped into the container, all task environment variables are mapped into the container, and the task command line is executed in the container. :vartype container_settings: ~azure.mgmt.batch.models.TaskContainerSettings """ _attribute_map = { "command_line": {"key": "commandLine", "type": "str"}, "resource_files": {"key": "resourceFiles", "type": "[ResourceFile]"}, "environment_settings": {"key": "environmentSettings", "type": "[EnvironmentSetting]"}, "user_identity": {"key": "userIdentity", "type": "UserIdentity"}, "max_task_retry_count": {"key": "maxTaskRetryCount", "type": "int"}, "wait_for_success": {"key": "waitForSuccess", "type": "bool"}, "container_settings": {"key": "containerSettings", "type": "TaskContainerSettings"}, } def __init__( self, *, command_line: Optional[str] = None, resource_files: Optional[List["_models.ResourceFile"]] = None, environment_settings: Optional[List["_models.EnvironmentSetting"]] = None, user_identity: Optional["_models.UserIdentity"] = None, max_task_retry_count: Optional[int] = None, wait_for_success: Optional[bool] = None, container_settings: Optional["_models.TaskContainerSettings"] = None, **kwargs: Any ) -> None: """ :keyword command_line: The command line does not run under a shell, and therefore cannot take advantage of shell features such as environment variable expansion. If you want to take advantage of such features, you should invoke the shell in the command line, for example using "cmd /c MyCommand" in Windows or "/bin/sh -c MyCommand" in Linux. Required if any other properties of the startTask are specified. :paramtype command_line: str :keyword resource_files: A list of files that the Batch service will download to the compute node before running the command line. :paramtype resource_files: list[~azure.mgmt.batch.models.ResourceFile] :keyword environment_settings: A list of environment variable settings for the start task. :paramtype environment_settings: list[~azure.mgmt.batch.models.EnvironmentSetting] :keyword user_identity: If omitted, the task runs as a non-administrative user unique to the task. :paramtype user_identity: ~azure.mgmt.batch.models.UserIdentity :keyword max_task_retry_count: The Batch service retries a task if its exit code is nonzero. Note that this value specifically controls the number of retries. The Batch service will try the task once, and may then retry up to this limit. For example, if the maximum retry count is 3, Batch tries the task up to 4 times (one initial try and 3 retries). If the maximum retry count is 0, the Batch service does not retry the task. If the maximum retry count is -1, the Batch service retries the task without limit. :paramtype max_task_retry_count: int :keyword wait_for_success: If true and the start task fails on a compute node, the Batch service retries the start task up to its maximum retry count (maxTaskRetryCount). If the task has still not completed successfully after all retries, then the Batch service marks the compute node unusable, and will not schedule tasks to it. This condition can be detected via the node state and scheduling error detail. If false, the Batch service will not wait for the start task to complete. In this case, other tasks can start executing on the compute node while the start task is still running; and even if the start task fails, new tasks will continue to be scheduled on the node. The default is true. :paramtype wait_for_success: bool :keyword container_settings: When this is specified, all directories recursively below the AZ_BATCH_NODE_ROOT_DIR (the root of Azure Batch directories on the node) are mapped into the container, all task environment variables are mapped into the container, and the task command line is executed in the container. :paramtype container_settings: ~azure.mgmt.batch.models.TaskContainerSettings """ super().__init__(**kwargs) self.command_line = command_line self.resource_files = resource_files self.environment_settings = environment_settings self.user_identity = user_identity self.max_task_retry_count = max_task_retry_count self.wait_for_success = wait_for_success self.container_settings = container_settings class SupportedSku(_serialization.Model): """Describes a Batch supported SKU. Variables are only populated by the server, and will be ignored when sending a request. :ivar name: The name of the SKU. :vartype name: str :ivar family_name: The family name of the SKU. :vartype family_name: str :ivar capabilities: A collection of capabilities which this SKU supports. :vartype capabilities: list[~azure.mgmt.batch.models.SkuCapability] """ _validation = { "name": {"readonly": True}, "family_name": {"readonly": True}, "capabilities": {"readonly": True}, } _attribute_map = { "name": {"key": "name", "type": "str"}, "family_name": {"key": "familyName", "type": "str"}, "capabilities": {"key": "capabilities", "type": "[SkuCapability]"}, } def __init__(self, **kwargs: Any) -> None: """ """ super().__init__(**kwargs) self.name = None self.family_name = None self.capabilities = None class SupportedSkusResult(_serialization.Model): """The Batch List supported SKUs operation response. Variables are only populated by the server, and will be ignored when sending a request. All required parameters must be populated in order to send to Azure. :ivar value: The list of SKUs available for the Batch service in the location. Required. :vartype value: list[~azure.mgmt.batch.models.SupportedSku] :ivar next_link: The URL to use for getting the next set of results. :vartype next_link: str """ _validation = { "value": {"required": True}, "next_link": {"readonly": True}, } _attribute_map = { "value": {"key": "value", "type": "[SupportedSku]"}, "next_link": {"key": "nextLink", "type": "str"}, } def __init__(self, *, value: List["_models.SupportedSku"], **kwargs: Any) -> None: """ :keyword value: The list of SKUs available for the Batch service in the location. Required. :paramtype value: list[~azure.mgmt.batch.models.SupportedSku] """ super().__init__(**kwargs) self.value = value self.next_link = None class TaskContainerSettings(_serialization.Model): """The container settings for a task. All required parameters must be populated in order to send to Azure. :ivar container_run_options: These additional options are supplied as arguments to the "docker create" command, in addition to those controlled by the Batch Service. :vartype container_run_options: str :ivar image_name: This is the full image reference, as would be specified to "docker pull". If no tag is provided as part of the image name, the tag ":latest" is used as a default. Required. :vartype image_name: str :ivar registry: This setting can be omitted if was already provided at pool creation. :vartype registry: ~azure.mgmt.batch.models.ContainerRegistry :ivar working_directory: A flag to indicate where the container task working directory is. The default is 'taskWorkingDirectory'. Known values are: "TaskWorkingDirectory" and "ContainerImageDefault". :vartype working_directory: str or ~azure.mgmt.batch.models.ContainerWorkingDirectory """ _validation = { "image_name": {"required": True}, } _attribute_map = { "container_run_options": {"key": "containerRunOptions", "type": "str"}, "image_name": {"key": "imageName", "type": "str"}, "registry": {"key": "registry", "type": "ContainerRegistry"}, "working_directory": {"key": "workingDirectory", "type": "str"}, } def __init__( self, *, image_name: str, container_run_options: Optional[str] = None, registry: Optional["_models.ContainerRegistry"] = None, working_directory: Optional[Union[str, "_models.ContainerWorkingDirectory"]] = None, **kwargs: Any ) -> None: """ :keyword container_run_options: These additional options are supplied as arguments to the "docker create" command, in addition to those controlled by the Batch Service. :paramtype container_run_options: str :keyword image_name: This is the full image reference, as would be specified to "docker pull". If no tag is provided as part of the image name, the tag ":latest" is used as a default. Required. :paramtype image_name: str :keyword registry: This setting can be omitted if was already provided at pool creation. :paramtype registry: ~azure.mgmt.batch.models.ContainerRegistry :keyword working_directory: A flag to indicate where the container task working directory is. The default is 'taskWorkingDirectory'. Known values are: "TaskWorkingDirectory" and "ContainerImageDefault". :paramtype working_directory: str or ~azure.mgmt.batch.models.ContainerWorkingDirectory """ super().__init__(**kwargs) self.container_run_options = container_run_options self.image_name = image_name self.registry = registry self.working_directory = working_directory class TaskSchedulingPolicy(_serialization.Model): """Specifies how tasks should be distributed across compute nodes. All required parameters must be populated in order to send to Azure. :ivar node_fill_type: How tasks should be distributed across compute nodes. Required. Known values are: "Spread" and "Pack". :vartype node_fill_type: str or ~azure.mgmt.batch.models.ComputeNodeFillType """ _validation = { "node_fill_type": {"required": True}, } _attribute_map = { "node_fill_type": {"key": "nodeFillType", "type": "str"}, } def __init__(self, *, node_fill_type: Union[str, "_models.ComputeNodeFillType"], **kwargs: Any) -> None: """ :keyword node_fill_type: How tasks should be distributed across compute nodes. Required. Known values are: "Spread" and "Pack". :paramtype node_fill_type: str or ~azure.mgmt.batch.models.ComputeNodeFillType """ super().__init__(**kwargs) self.node_fill_type = node_fill_type class UserAccount(_serialization.Model): """Properties used to create a user on an Azure Batch node. All required parameters must be populated in order to send to Azure. :ivar name: The name of the user account. Names can contain any Unicode characters up to a maximum length of 20. Required. :vartype name: str :ivar password: The password for the user account. Required. :vartype password: str :ivar elevation_level: nonAdmin - The auto user is a standard user without elevated access. admin - The auto user is a user with elevated access and operates with full Administrator permissions. The default value is nonAdmin. Known values are: "NonAdmin" and "Admin". :vartype elevation_level: str or ~azure.mgmt.batch.models.ElevationLevel :ivar linux_user_configuration: This property is ignored if specified on a Windows pool. If not specified, the user is created with the default options. :vartype linux_user_configuration: ~azure.mgmt.batch.models.LinuxUserConfiguration :ivar windows_user_configuration: This property can only be specified if the user is on a Windows pool. If not specified and on a Windows pool, the user is created with the default options. :vartype windows_user_configuration: ~azure.mgmt.batch.models.WindowsUserConfiguration """ _validation = { "name": {"required": True}, "password": {"required": True}, } _attribute_map = { "name": {"key": "name", "type": "str"}, "password": {"key": "password", "type": "str"}, "elevation_level": {"key": "elevationLevel", "type": "str"}, "linux_user_configuration": {"key": "linuxUserConfiguration", "type": "LinuxUserConfiguration"}, "windows_user_configuration": {"key": "windowsUserConfiguration", "type": "WindowsUserConfiguration"}, } def __init__( self, *, name: str, password: str, elevation_level: Optional[Union[str, "_models.ElevationLevel"]] = None, linux_user_configuration: Optional["_models.LinuxUserConfiguration"] = None, windows_user_configuration: Optional["_models.WindowsUserConfiguration"] = None, **kwargs: Any ) -> None: """ :keyword name: The name of the user account. Names can contain any Unicode characters up to a maximum length of 20. Required. :paramtype name: str :keyword password: The password for the user account. Required. :paramtype password: str :keyword elevation_level: nonAdmin - The auto user is a standard user without elevated access. admin - The auto user is a user with elevated access and operates with full Administrator permissions. The default value is nonAdmin. Known values are: "NonAdmin" and "Admin". :paramtype elevation_level: str or ~azure.mgmt.batch.models.ElevationLevel :keyword linux_user_configuration: This property is ignored if specified on a Windows pool. If not specified, the user is created with the default options. :paramtype linux_user_configuration: ~azure.mgmt.batch.models.LinuxUserConfiguration :keyword windows_user_configuration: This property can only be specified if the user is on a Windows pool. If not specified and on a Windows pool, the user is created with the default options. :paramtype windows_user_configuration: ~azure.mgmt.batch.models.WindowsUserConfiguration """ super().__init__(**kwargs) self.name = name self.password = password self.elevation_level = elevation_level self.linux_user_configuration = linux_user_configuration self.windows_user_configuration = windows_user_configuration class UserAssignedIdentities(_serialization.Model): """The list of associated user identities. Variables are only populated by the server, and will be ignored when sending a request. :ivar principal_id: The principal id of user assigned identity. :vartype principal_id: str :ivar client_id: The client id of user assigned identity. :vartype client_id: str """ _validation = { "principal_id": {"readonly": True}, "client_id": {"readonly": True}, } _attribute_map = { "principal_id": {"key": "principalId", "type": "str"}, "client_id": {"key": "clientId", "type": "str"}, } def __init__(self, **kwargs: Any) -> None: """ """ super().__init__(**kwargs) self.principal_id = None self.client_id = None class UserIdentity(_serialization.Model): """Specify either the userName or autoUser property, but not both. :ivar user_name: The userName and autoUser properties are mutually exclusive; you must specify one but not both. :vartype user_name: str :ivar auto_user: The userName and autoUser properties are mutually exclusive; you must specify one but not both. :vartype auto_user: ~azure.mgmt.batch.models.AutoUserSpecification """ _attribute_map = { "user_name": {"key": "userName", "type": "str"}, "auto_user": {"key": "autoUser", "type": "AutoUserSpecification"}, } def __init__( self, *, user_name: Optional[str] = None, auto_user: Optional["_models.AutoUserSpecification"] = None, **kwargs: Any ) -> None: """ :keyword user_name: The userName and autoUser properties are mutually exclusive; you must specify one but not both. :paramtype user_name: str :keyword auto_user: The userName and autoUser properties are mutually exclusive; you must specify one but not both. :paramtype auto_user: ~azure.mgmt.batch.models.AutoUserSpecification """ super().__init__(**kwargs) self.user_name = user_name self.auto_user = auto_user class VirtualMachineConfiguration(_serialization.Model): """The configuration for compute nodes in a pool based on the Azure Virtual Machines infrastructure. All required parameters must be populated in order to send to Azure. :ivar image_reference: A reference to an Azure Virtual Machines Marketplace image or the Azure Image resource of a custom Virtual Machine. To get the list of all imageReferences verified by Azure Batch, see the 'List supported node agent SKUs' operation. Required. :vartype image_reference: ~azure.mgmt.batch.models.ImageReference :ivar node_agent_sku_id: The Batch node agent is a program that runs on each node in the pool, and provides the command-and-control interface between the node and the Batch service. There are different implementations of the node agent, known as SKUs, for different operating systems. You must specify a node agent SKU which matches the selected image reference. To get the list of supported node agent SKUs along with their list of verified image references, see the 'List supported node agent SKUs' operation. Required. :vartype node_agent_sku_id: str :ivar windows_configuration: This property must not be specified if the imageReference specifies a Linux OS image. :vartype windows_configuration: ~azure.mgmt.batch.models.WindowsConfiguration :ivar data_disks: This property must be specified if the compute nodes in the pool need to have empty data disks attached to them. :vartype data_disks: list[~azure.mgmt.batch.models.DataDisk] :ivar license_type: This only applies to images that contain the Windows operating system, and should only be used when you hold valid on-premises licenses for the nodes which will be deployed. If omitted, no on-premises licensing discount is applied. Values are: Windows_Server - The on-premises license is for Windows Server. Windows_Client - The on-premises license is for Windows Client. :vartype license_type: str :ivar container_configuration: If specified, setup is performed on each node in the pool to allow tasks to run in containers. All regular tasks and job manager tasks run on this pool must specify the containerSettings property, and all other tasks may specify it. :vartype container_configuration: ~azure.mgmt.batch.models.ContainerConfiguration :ivar disk_encryption_configuration: If specified, encryption is performed on each node in the pool during node provisioning. :vartype disk_encryption_configuration: ~azure.mgmt.batch.models.DiskEncryptionConfiguration :ivar node_placement_configuration: This configuration will specify rules on how nodes in the pool will be physically allocated. :vartype node_placement_configuration: ~azure.mgmt.batch.models.NodePlacementConfiguration :ivar extensions: If specified, the extensions mentioned in this configuration will be installed on each node. :vartype extensions: list[~azure.mgmt.batch.models.VMExtension] :ivar os_disk: Contains configuration for ephemeral OSDisk settings. :vartype os_disk: ~azure.mgmt.batch.models.OSDisk """ _validation = { "image_reference": {"required": True}, "node_agent_sku_id": {"required": True}, } _attribute_map = { "image_reference": {"key": "imageReference", "type": "ImageReference"}, "node_agent_sku_id": {"key": "nodeAgentSkuId", "type": "str"}, "windows_configuration": {"key": "windowsConfiguration", "type": "WindowsConfiguration"}, "data_disks": {"key": "dataDisks", "type": "[DataDisk]"}, "license_type": {"key": "licenseType", "type": "str"}, "container_configuration": {"key": "containerConfiguration", "type": "ContainerConfiguration"}, "disk_encryption_configuration": {"key": "diskEncryptionConfiguration", "type": "DiskEncryptionConfiguration"}, "node_placement_configuration": {"key": "nodePlacementConfiguration", "type": "NodePlacementConfiguration"}, "extensions": {"key": "extensions", "type": "[VMExtension]"}, "os_disk": {"key": "osDisk", "type": "OSDisk"}, } def __init__( self, *, image_reference: "_models.ImageReference", node_agent_sku_id: str, windows_configuration: Optional["_models.WindowsConfiguration"] = None, data_disks: Optional[List["_models.DataDisk"]] = None, license_type: Optional[str] = None, container_configuration: Optional["_models.ContainerConfiguration"] = None, disk_encryption_configuration: Optional["_models.DiskEncryptionConfiguration"] = None, node_placement_configuration: Optional["_models.NodePlacementConfiguration"] = None, extensions: Optional[List["_models.VMExtension"]] = None, os_disk: Optional["_models.OSDisk"] = None, **kwargs: Any ) -> None: """ :keyword image_reference: A reference to an Azure Virtual Machines Marketplace image or the Azure Image resource of a custom Virtual Machine. To get the list of all imageReferences verified by Azure Batch, see the 'List supported node agent SKUs' operation. Required. :paramtype image_reference: ~azure.mgmt.batch.models.ImageReference :keyword node_agent_sku_id: The Batch node agent is a program that runs on each node in the pool, and provides the command-and-control interface between the node and the Batch service. There are different implementations of the node agent, known as SKUs, for different operating systems. You must specify a node agent SKU which matches the selected image reference. To get the list of supported node agent SKUs along with their list of verified image references, see the 'List supported node agent SKUs' operation. Required. :paramtype node_agent_sku_id: str :keyword windows_configuration: This property must not be specified if the imageReference specifies a Linux OS image. :paramtype windows_configuration: ~azure.mgmt.batch.models.WindowsConfiguration :keyword data_disks: This property must be specified if the compute nodes in the pool need to have empty data disks attached to them. :paramtype data_disks: list[~azure.mgmt.batch.models.DataDisk] :keyword license_type: This only applies to images that contain the Windows operating system, and should only be used when you hold valid on-premises licenses for the nodes which will be deployed. If omitted, no on-premises licensing discount is applied. Values are: Windows_Server - The on-premises license is for Windows Server. Windows_Client - The on-premises license is for Windows Client. :paramtype license_type: str :keyword container_configuration: If specified, setup is performed on each node in the pool to allow tasks to run in containers. All regular tasks and job manager tasks run on this pool must specify the containerSettings property, and all other tasks may specify it. :paramtype container_configuration: ~azure.mgmt.batch.models.ContainerConfiguration :keyword disk_encryption_configuration: If specified, encryption is performed on each node in the pool during node provisioning. :paramtype disk_encryption_configuration: ~azure.mgmt.batch.models.DiskEncryptionConfiguration :keyword node_placement_configuration: This configuration will specify rules on how nodes in the pool will be physically allocated. :paramtype node_placement_configuration: ~azure.mgmt.batch.models.NodePlacementConfiguration :keyword extensions: If specified, the extensions mentioned in this configuration will be installed on each node. :paramtype extensions: list[~azure.mgmt.batch.models.VMExtension] :keyword os_disk: Contains configuration for ephemeral OSDisk settings. :paramtype os_disk: ~azure.mgmt.batch.models.OSDisk """ super().__init__(**kwargs) self.image_reference = image_reference self.node_agent_sku_id = node_agent_sku_id self.windows_configuration = windows_configuration self.data_disks = data_disks self.license_type = license_type self.container_configuration = container_configuration self.disk_encryption_configuration = disk_encryption_configuration self.node_placement_configuration = node_placement_configuration self.extensions = extensions self.os_disk = os_disk class VirtualMachineFamilyCoreQuota(_serialization.Model): """A VM Family and its associated core quota for the Batch account. Variables are only populated by the server, and will be ignored when sending a request. :ivar name: The Virtual Machine family name. :vartype name: str :ivar core_quota: The core quota for the VM family for the Batch account. :vartype core_quota: int """ _validation = { "name": {"readonly": True}, "core_quota": {"readonly": True}, } _attribute_map = { "name": {"key": "name", "type": "str"}, "core_quota": {"key": "coreQuota", "type": "int"}, } def __init__(self, **kwargs: Any) -> None: """ """ super().__init__(**kwargs) self.name = None self.core_quota = None class VMExtension(_serialization.Model): """The configuration for virtual machine extensions. All required parameters must be populated in order to send to Azure. :ivar name: The name of the virtual machine extension. Required. :vartype name: str :ivar publisher: The name of the extension handler publisher. Required. :vartype publisher: str :ivar type: The type of the extensions. Required. :vartype type: str :ivar type_handler_version: The version of script handler. :vartype type_handler_version: str :ivar auto_upgrade_minor_version: Indicates whether the extension should use a newer minor version if one is available at deployment time. Once deployed, however, the extension will not upgrade minor versions unless redeployed, even with this property set to true. :vartype auto_upgrade_minor_version: bool :ivar enable_automatic_upgrade: Indicates whether the extension should be automatically upgraded by the platform if there is a newer version of the extension available. :vartype enable_automatic_upgrade: bool :ivar settings: JSON formatted public settings for the extension. :vartype settings: JSON :ivar protected_settings: The extension can contain either protectedSettings or protectedSettingsFromKeyVault or no protected settings at all. :vartype protected_settings: JSON :ivar provision_after_extensions: Collection of extension names after which this extension needs to be provisioned. :vartype provision_after_extensions: list[str] """ _validation = { "name": {"required": True}, "publisher": {"required": True}, "type": {"required": True}, } _attribute_map = { "name": {"key": "name", "type": "str"}, "publisher": {"key": "publisher", "type": "str"}, "type": {"key": "type", "type": "str"}, "type_handler_version": {"key": "typeHandlerVersion", "type": "str"}, "auto_upgrade_minor_version": {"key": "autoUpgradeMinorVersion", "type": "bool"}, "enable_automatic_upgrade": {"key": "enableAutomaticUpgrade", "type": "bool"}, "settings": {"key": "settings", "type": "object"}, "protected_settings": {"key": "protectedSettings", "type": "object"}, "provision_after_extensions": {"key": "provisionAfterExtensions", "type": "[str]"}, } def __init__( self, *, name: str, publisher: str, type: str, type_handler_version: Optional[str] = None, auto_upgrade_minor_version: Optional[bool] = None, enable_automatic_upgrade: Optional[bool] = None, settings: Optional[JSON] = None, protected_settings: Optional[JSON] = None, provision_after_extensions: Optional[List[str]] = None, **kwargs: Any ) -> None: """ :keyword name: The name of the virtual machine extension. Required. :paramtype name: str :keyword publisher: The name of the extension handler publisher. Required. :paramtype publisher: str :keyword type: The type of the extensions. Required. :paramtype type: str :keyword type_handler_version: The version of script handler. :paramtype type_handler_version: str :keyword auto_upgrade_minor_version: Indicates whether the extension should use a newer minor version if one is available at deployment time. Once deployed, however, the extension will not upgrade minor versions unless redeployed, even with this property set to true. :paramtype auto_upgrade_minor_version: bool :keyword enable_automatic_upgrade: Indicates whether the extension should be automatically upgraded by the platform if there is a newer version of the extension available. :paramtype enable_automatic_upgrade: bool :keyword settings: JSON formatted public settings for the extension. :paramtype settings: JSON :keyword protected_settings: The extension can contain either protectedSettings or protectedSettingsFromKeyVault or no protected settings at all. :paramtype protected_settings: JSON :keyword provision_after_extensions: Collection of extension names after which this extension needs to be provisioned. :paramtype provision_after_extensions: list[str] """ super().__init__(**kwargs) self.name = name self.publisher = publisher self.type = type self.type_handler_version = type_handler_version self.auto_upgrade_minor_version = auto_upgrade_minor_version self.enable_automatic_upgrade = enable_automatic_upgrade self.settings = settings self.protected_settings = protected_settings self.provision_after_extensions = provision_after_extensions class WindowsConfiguration(_serialization.Model): """Windows operating system settings to apply to the virtual machine. :ivar enable_automatic_updates: If omitted, the default value is true. :vartype enable_automatic_updates: bool """ _attribute_map = { "enable_automatic_updates": {"key": "enableAutomaticUpdates", "type": "bool"}, } def __init__(self, *, enable_automatic_updates: Optional[bool] = None, **kwargs: Any) -> None: """ :keyword enable_automatic_updates: If omitted, the default value is true. :paramtype enable_automatic_updates: bool """ super().__init__(**kwargs) self.enable_automatic_updates = enable_automatic_updates class WindowsUserConfiguration(_serialization.Model): """Properties used to create a user account on a Windows node. :ivar login_mode: Specifies login mode for the user. The default value for VirtualMachineConfiguration pools is interactive mode and for CloudServiceConfiguration pools is batch mode. Known values are: "Batch" and "Interactive". :vartype login_mode: str or ~azure.mgmt.batch.models.LoginMode """ _attribute_map = { "login_mode": {"key": "loginMode", "type": "str"}, } def __init__(self, *, login_mode: Optional[Union[str, "_models.LoginMode"]] = None, **kwargs: Any) -> None: """ :keyword login_mode: Specifies login mode for the user. The default value for VirtualMachineConfiguration pools is interactive mode and for CloudServiceConfiguration pools is batch mode. Known values are: "Batch" and "Interactive". :paramtype login_mode: str or ~azure.mgmt.batch.models.LoginMode """ super().__init__(**kwargs) self.login_mode = login_mode
azure-mgmt-batch
/azure_mgmt_batch-17.1.0-py3-none-any.whl/azure/mgmt/batch/models/_models_py3.py
_models_py3.py
import datetime import sys from typing import Any, Dict, List, Optional, TYPE_CHECKING, Union from .. import _serialization if sys.version_info >= (3, 9): from collections.abc import MutableMapping else: from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports if sys.version_info >= (3, 8): from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports else: from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from .. import models as _models JSON = MutableMapping[str, Any] # pylint: disable=unsubscriptable-object class ActivateApplicationPackageParameters(_serialization.Model): """Parameters for an activating an application package. All required parameters must be populated in order to send to Azure. :ivar format: The format of the application package binary file. Required. :vartype format: str """ _validation = { "format": {"required": True}, } _attribute_map = { "format": {"key": "format", "type": "str"}, } def __init__(self, *, format: str, **kwargs: Any) -> None: """ :keyword format: The format of the application package binary file. Required. :paramtype format: str """ super().__init__(**kwargs) self.format = format class ProxyResource(_serialization.Model): """A definition of an Azure resource. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: The ID of the resource. :vartype id: str :ivar name: The name of the resource. :vartype name: str :ivar type: The type of the resource. :vartype type: str :ivar etag: The ETag of the resource, used for concurrency statements. :vartype etag: str """ _validation = { "id": {"readonly": True}, "name": {"readonly": True}, "type": {"readonly": True}, "etag": {"readonly": True}, } _attribute_map = { "id": {"key": "id", "type": "str"}, "name": {"key": "name", "type": "str"}, "type": {"key": "type", "type": "str"}, "etag": {"key": "etag", "type": "str"}, } def __init__(self, **kwargs: Any) -> None: """ """ super().__init__(**kwargs) self.id = None self.name = None self.type = None self.etag = None class Application(ProxyResource): """Contains information about an application in a Batch account. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: The ID of the resource. :vartype id: str :ivar name: The name of the resource. :vartype name: str :ivar type: The type of the resource. :vartype type: str :ivar etag: The ETag of the resource, used for concurrency statements. :vartype etag: str :ivar display_name: The display name for the application. :vartype display_name: str :ivar allow_updates: A value indicating whether packages within the application may be overwritten using the same version string. :vartype allow_updates: bool :ivar default_version: The package to use if a client requests the application but does not specify a version. This property can only be set to the name of an existing package. :vartype default_version: str """ _validation = { "id": {"readonly": True}, "name": {"readonly": True}, "type": {"readonly": True}, "etag": {"readonly": True}, } _attribute_map = { "id": {"key": "id", "type": "str"}, "name": {"key": "name", "type": "str"}, "type": {"key": "type", "type": "str"}, "etag": {"key": "etag", "type": "str"}, "display_name": {"key": "properties.displayName", "type": "str"}, "allow_updates": {"key": "properties.allowUpdates", "type": "bool"}, "default_version": {"key": "properties.defaultVersion", "type": "str"}, } def __init__( self, *, display_name: Optional[str] = None, allow_updates: Optional[bool] = None, default_version: Optional[str] = None, **kwargs: Any ) -> None: """ :keyword display_name: The display name for the application. :paramtype display_name: str :keyword allow_updates: A value indicating whether packages within the application may be overwritten using the same version string. :paramtype allow_updates: bool :keyword default_version: The package to use if a client requests the application but does not specify a version. This property can only be set to the name of an existing package. :paramtype default_version: str """ super().__init__(**kwargs) self.display_name = display_name self.allow_updates = allow_updates self.default_version = default_version class ApplicationPackage(ProxyResource): """An application package which represents a particular version of an application. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: The ID of the resource. :vartype id: str :ivar name: The name of the resource. :vartype name: str :ivar type: The type of the resource. :vartype type: str :ivar etag: The ETag of the resource, used for concurrency statements. :vartype etag: str :ivar state: The current state of the application package. Known values are: "Pending" and "Active". :vartype state: str or ~azure.mgmt.batch.models.PackageState :ivar format: The format of the application package, if the package is active. :vartype format: str :ivar storage_url: The URL for the application package in Azure Storage. :vartype storage_url: str :ivar storage_url_expiry: The UTC time at which the Azure Storage URL will expire. :vartype storage_url_expiry: ~datetime.datetime :ivar last_activation_time: The time at which the package was last activated, if the package is active. :vartype last_activation_time: ~datetime.datetime """ _validation = { "id": {"readonly": True}, "name": {"readonly": True}, "type": {"readonly": True}, "etag": {"readonly": True}, "state": {"readonly": True}, "format": {"readonly": True}, "storage_url": {"readonly": True}, "storage_url_expiry": {"readonly": True}, "last_activation_time": {"readonly": True}, } _attribute_map = { "id": {"key": "id", "type": "str"}, "name": {"key": "name", "type": "str"}, "type": {"key": "type", "type": "str"}, "etag": {"key": "etag", "type": "str"}, "state": {"key": "properties.state", "type": "str"}, "format": {"key": "properties.format", "type": "str"}, "storage_url": {"key": "properties.storageUrl", "type": "str"}, "storage_url_expiry": {"key": "properties.storageUrlExpiry", "type": "iso-8601"}, "last_activation_time": {"key": "properties.lastActivationTime", "type": "iso-8601"}, } def __init__(self, **kwargs: Any) -> None: """ """ super().__init__(**kwargs) self.state = None self.format = None self.storage_url = None self.storage_url_expiry = None self.last_activation_time = None class ApplicationPackageReference(_serialization.Model): """Link to an application package inside the batch account. All required parameters must be populated in order to send to Azure. :ivar id: The ID of the application package to install. This must be inside the same batch account as the pool. This can either be a reference to a specific version or the default version if one exists. Required. :vartype id: str :ivar version: If this is omitted, and no default version is specified for this application, the request fails with the error code InvalidApplicationPackageReferences. If you are calling the REST API directly, the HTTP status code is 409. :vartype version: str """ _validation = { "id": {"required": True}, } _attribute_map = { "id": {"key": "id", "type": "str"}, "version": {"key": "version", "type": "str"}, } def __init__( self, *, id: str, version: Optional[str] = None, **kwargs: Any # pylint: disable=redefined-builtin ) -> None: """ :keyword id: The ID of the application package to install. This must be inside the same batch account as the pool. This can either be a reference to a specific version or the default version if one exists. Required. :paramtype id: str :keyword version: If this is omitted, and no default version is specified for this application, the request fails with the error code InvalidApplicationPackageReferences. If you are calling the REST API directly, the HTTP status code is 409. :paramtype version: str """ super().__init__(**kwargs) self.id = id self.version = version class AutoScaleRun(_serialization.Model): """The results and errors from an execution of a pool autoscale formula. All required parameters must be populated in order to send to Azure. :ivar evaluation_time: The time at which the autoscale formula was last evaluated. Required. :vartype evaluation_time: ~datetime.datetime :ivar results: Each variable value is returned in the form $variable=value, and variables are separated by semicolons. :vartype results: str :ivar error: An error that occurred when autoscaling a pool. :vartype error: ~azure.mgmt.batch.models.AutoScaleRunError """ _validation = { "evaluation_time": {"required": True}, } _attribute_map = { "evaluation_time": {"key": "evaluationTime", "type": "iso-8601"}, "results": {"key": "results", "type": "str"}, "error": {"key": "error", "type": "AutoScaleRunError"}, } def __init__( self, *, evaluation_time: datetime.datetime, results: Optional[str] = None, error: Optional["_models.AutoScaleRunError"] = None, **kwargs: Any ) -> None: """ :keyword evaluation_time: The time at which the autoscale formula was last evaluated. Required. :paramtype evaluation_time: ~datetime.datetime :keyword results: Each variable value is returned in the form $variable=value, and variables are separated by semicolons. :paramtype results: str :keyword error: An error that occurred when autoscaling a pool. :paramtype error: ~azure.mgmt.batch.models.AutoScaleRunError """ super().__init__(**kwargs) self.evaluation_time = evaluation_time self.results = results self.error = error class AutoScaleRunError(_serialization.Model): """An error that occurred when autoscaling a pool. All required parameters must be populated in order to send to Azure. :ivar code: An identifier for the error. Codes are invariant and are intended to be consumed programmatically. Required. :vartype code: str :ivar message: A message describing the error, intended to be suitable for display in a user interface. Required. :vartype message: str :ivar details: Additional details about the error. :vartype details: list[~azure.mgmt.batch.models.AutoScaleRunError] """ _validation = { "code": {"required": True}, "message": {"required": True}, } _attribute_map = { "code": {"key": "code", "type": "str"}, "message": {"key": "message", "type": "str"}, "details": {"key": "details", "type": "[AutoScaleRunError]"}, } def __init__( self, *, code: str, message: str, details: Optional[List["_models.AutoScaleRunError"]] = None, **kwargs: Any ) -> None: """ :keyword code: An identifier for the error. Codes are invariant and are intended to be consumed programmatically. Required. :paramtype code: str :keyword message: A message describing the error, intended to be suitable for display in a user interface. Required. :paramtype message: str :keyword details: Additional details about the error. :paramtype details: list[~azure.mgmt.batch.models.AutoScaleRunError] """ super().__init__(**kwargs) self.code = code self.message = message self.details = details class AutoScaleSettings(_serialization.Model): """AutoScale settings for the pool. All required parameters must be populated in order to send to Azure. :ivar formula: A formula for the desired number of compute nodes in the pool. Required. :vartype formula: str :ivar evaluation_interval: If omitted, the default value is 15 minutes (PT15M). :vartype evaluation_interval: ~datetime.timedelta """ _validation = { "formula": {"required": True}, } _attribute_map = { "formula": {"key": "formula", "type": "str"}, "evaluation_interval": {"key": "evaluationInterval", "type": "duration"}, } def __init__( self, *, formula: str, evaluation_interval: Optional[datetime.timedelta] = None, **kwargs: Any ) -> None: """ :keyword formula: A formula for the desired number of compute nodes in the pool. Required. :paramtype formula: str :keyword evaluation_interval: If omitted, the default value is 15 minutes (PT15M). :paramtype evaluation_interval: ~datetime.timedelta """ super().__init__(**kwargs) self.formula = formula self.evaluation_interval = evaluation_interval class AutoStorageBaseProperties(_serialization.Model): """The properties related to the auto-storage account. All required parameters must be populated in order to send to Azure. :ivar storage_account_id: The resource ID of the storage account to be used for auto-storage account. Required. :vartype storage_account_id: str :ivar authentication_mode: The authentication mode which the Batch service will use to manage the auto-storage account. Known values are: "StorageKeys" and "BatchAccountManagedIdentity". :vartype authentication_mode: str or ~azure.mgmt.batch.models.AutoStorageAuthenticationMode :ivar node_identity_reference: The identity referenced here must be assigned to pools which have compute nodes that need access to auto-storage. :vartype node_identity_reference: ~azure.mgmt.batch.models.ComputeNodeIdentityReference """ _validation = { "storage_account_id": {"required": True}, } _attribute_map = { "storage_account_id": {"key": "storageAccountId", "type": "str"}, "authentication_mode": {"key": "authenticationMode", "type": "str"}, "node_identity_reference": {"key": "nodeIdentityReference", "type": "ComputeNodeIdentityReference"}, } def __init__( self, *, storage_account_id: str, authentication_mode: Union[str, "_models.AutoStorageAuthenticationMode"] = "StorageKeys", node_identity_reference: Optional["_models.ComputeNodeIdentityReference"] = None, **kwargs: Any ) -> None: """ :keyword storage_account_id: The resource ID of the storage account to be used for auto-storage account. Required. :paramtype storage_account_id: str :keyword authentication_mode: The authentication mode which the Batch service will use to manage the auto-storage account. Known values are: "StorageKeys" and "BatchAccountManagedIdentity". :paramtype authentication_mode: str or ~azure.mgmt.batch.models.AutoStorageAuthenticationMode :keyword node_identity_reference: The identity referenced here must be assigned to pools which have compute nodes that need access to auto-storage. :paramtype node_identity_reference: ~azure.mgmt.batch.models.ComputeNodeIdentityReference """ super().__init__(**kwargs) self.storage_account_id = storage_account_id self.authentication_mode = authentication_mode self.node_identity_reference = node_identity_reference class AutoStorageProperties(AutoStorageBaseProperties): """Contains information about the auto-storage account associated with a Batch account. All required parameters must be populated in order to send to Azure. :ivar storage_account_id: The resource ID of the storage account to be used for auto-storage account. Required. :vartype storage_account_id: str :ivar authentication_mode: The authentication mode which the Batch service will use to manage the auto-storage account. Known values are: "StorageKeys" and "BatchAccountManagedIdentity". :vartype authentication_mode: str or ~azure.mgmt.batch.models.AutoStorageAuthenticationMode :ivar node_identity_reference: The identity referenced here must be assigned to pools which have compute nodes that need access to auto-storage. :vartype node_identity_reference: ~azure.mgmt.batch.models.ComputeNodeIdentityReference :ivar last_key_sync: The UTC time at which storage keys were last synchronized with the Batch account. Required. :vartype last_key_sync: ~datetime.datetime """ _validation = { "storage_account_id": {"required": True}, "last_key_sync": {"required": True}, } _attribute_map = { "storage_account_id": {"key": "storageAccountId", "type": "str"}, "authentication_mode": {"key": "authenticationMode", "type": "str"}, "node_identity_reference": {"key": "nodeIdentityReference", "type": "ComputeNodeIdentityReference"}, "last_key_sync": {"key": "lastKeySync", "type": "iso-8601"}, } def __init__( self, *, storage_account_id: str, last_key_sync: datetime.datetime, authentication_mode: Union[str, "_models.AutoStorageAuthenticationMode"] = "StorageKeys", node_identity_reference: Optional["_models.ComputeNodeIdentityReference"] = None, **kwargs: Any ) -> None: """ :keyword storage_account_id: The resource ID of the storage account to be used for auto-storage account. Required. :paramtype storage_account_id: str :keyword authentication_mode: The authentication mode which the Batch service will use to manage the auto-storage account. Known values are: "StorageKeys" and "BatchAccountManagedIdentity". :paramtype authentication_mode: str or ~azure.mgmt.batch.models.AutoStorageAuthenticationMode :keyword node_identity_reference: The identity referenced here must be assigned to pools which have compute nodes that need access to auto-storage. :paramtype node_identity_reference: ~azure.mgmt.batch.models.ComputeNodeIdentityReference :keyword last_key_sync: The UTC time at which storage keys were last synchronized with the Batch account. Required. :paramtype last_key_sync: ~datetime.datetime """ super().__init__( storage_account_id=storage_account_id, authentication_mode=authentication_mode, node_identity_reference=node_identity_reference, **kwargs ) self.last_key_sync = last_key_sync class AutoUserSpecification(_serialization.Model): """Specifies the parameters for the auto user that runs a task on the Batch service. :ivar scope: The default value is Pool. If the pool is running Windows a value of Task should be specified if stricter isolation between tasks is required. For example, if the task mutates the registry in a way which could impact other tasks, or if certificates have been specified on the pool which should not be accessible by normal tasks but should be accessible by start tasks. Known values are: "Task" and "Pool". :vartype scope: str or ~azure.mgmt.batch.models.AutoUserScope :ivar elevation_level: The default value is nonAdmin. Known values are: "NonAdmin" and "Admin". :vartype elevation_level: str or ~azure.mgmt.batch.models.ElevationLevel """ _attribute_map = { "scope": {"key": "scope", "type": "str"}, "elevation_level": {"key": "elevationLevel", "type": "str"}, } def __init__( self, *, scope: Optional[Union[str, "_models.AutoUserScope"]] = None, elevation_level: Optional[Union[str, "_models.ElevationLevel"]] = None, **kwargs: Any ) -> None: """ :keyword scope: The default value is Pool. If the pool is running Windows a value of Task should be specified if stricter isolation between tasks is required. For example, if the task mutates the registry in a way which could impact other tasks, or if certificates have been specified on the pool which should not be accessible by normal tasks but should be accessible by start tasks. Known values are: "Task" and "Pool". :paramtype scope: str or ~azure.mgmt.batch.models.AutoUserScope :keyword elevation_level: The default value is nonAdmin. Known values are: "NonAdmin" and "Admin". :paramtype elevation_level: str or ~azure.mgmt.batch.models.ElevationLevel """ super().__init__(**kwargs) self.scope = scope self.elevation_level = elevation_level class AzureBlobFileSystemConfiguration(_serialization.Model): """Information used to connect to an Azure Storage Container using Blobfuse. All required parameters must be populated in order to send to Azure. :ivar account_name: The Azure Storage Account name. Required. :vartype account_name: str :ivar container_name: The Azure Blob Storage Container name. Required. :vartype container_name: str :ivar account_key: This property is mutually exclusive with both sasKey and identity; exactly one must be specified. :vartype account_key: str :ivar sas_key: This property is mutually exclusive with both accountKey and identity; exactly one must be specified. :vartype sas_key: str :ivar blobfuse_options: These are 'net use' options in Windows and 'mount' options in Linux. :vartype blobfuse_options: str :ivar relative_mount_path: All file systems are mounted relative to the Batch mounts directory, accessible via the AZ_BATCH_NODE_MOUNTS_DIR environment variable. Required. :vartype relative_mount_path: str :ivar identity_reference: This property is mutually exclusive with both accountKey and sasKey; exactly one must be specified. :vartype identity_reference: ~azure.mgmt.batch.models.ComputeNodeIdentityReference """ _validation = { "account_name": {"required": True}, "container_name": {"required": True}, "relative_mount_path": {"required": True}, } _attribute_map = { "account_name": {"key": "accountName", "type": "str"}, "container_name": {"key": "containerName", "type": "str"}, "account_key": {"key": "accountKey", "type": "str"}, "sas_key": {"key": "sasKey", "type": "str"}, "blobfuse_options": {"key": "blobfuseOptions", "type": "str"}, "relative_mount_path": {"key": "relativeMountPath", "type": "str"}, "identity_reference": {"key": "identityReference", "type": "ComputeNodeIdentityReference"}, } def __init__( self, *, account_name: str, container_name: str, relative_mount_path: str, account_key: Optional[str] = None, sas_key: Optional[str] = None, blobfuse_options: Optional[str] = None, identity_reference: Optional["_models.ComputeNodeIdentityReference"] = None, **kwargs: Any ) -> None: """ :keyword account_name: The Azure Storage Account name. Required. :paramtype account_name: str :keyword container_name: The Azure Blob Storage Container name. Required. :paramtype container_name: str :keyword account_key: This property is mutually exclusive with both sasKey and identity; exactly one must be specified. :paramtype account_key: str :keyword sas_key: This property is mutually exclusive with both accountKey and identity; exactly one must be specified. :paramtype sas_key: str :keyword blobfuse_options: These are 'net use' options in Windows and 'mount' options in Linux. :paramtype blobfuse_options: str :keyword relative_mount_path: All file systems are mounted relative to the Batch mounts directory, accessible via the AZ_BATCH_NODE_MOUNTS_DIR environment variable. Required. :paramtype relative_mount_path: str :keyword identity_reference: This property is mutually exclusive with both accountKey and sasKey; exactly one must be specified. :paramtype identity_reference: ~azure.mgmt.batch.models.ComputeNodeIdentityReference """ super().__init__(**kwargs) self.account_name = account_name self.container_name = container_name self.account_key = account_key self.sas_key = sas_key self.blobfuse_options = blobfuse_options self.relative_mount_path = relative_mount_path self.identity_reference = identity_reference class AzureFileShareConfiguration(_serialization.Model): """Information used to connect to an Azure Fileshare. All required parameters must be populated in order to send to Azure. :ivar account_name: The Azure Storage account name. Required. :vartype account_name: str :ivar azure_file_url: This is of the form 'https://{account}.file.core.windows.net/'. Required. :vartype azure_file_url: str :ivar account_key: The Azure Storage account key. Required. :vartype account_key: str :ivar relative_mount_path: All file systems are mounted relative to the Batch mounts directory, accessible via the AZ_BATCH_NODE_MOUNTS_DIR environment variable. Required. :vartype relative_mount_path: str :ivar mount_options: These are 'net use' options in Windows and 'mount' options in Linux. :vartype mount_options: str """ _validation = { "account_name": {"required": True}, "azure_file_url": {"required": True}, "account_key": {"required": True}, "relative_mount_path": {"required": True}, } _attribute_map = { "account_name": {"key": "accountName", "type": "str"}, "azure_file_url": {"key": "azureFileUrl", "type": "str"}, "account_key": {"key": "accountKey", "type": "str"}, "relative_mount_path": {"key": "relativeMountPath", "type": "str"}, "mount_options": {"key": "mountOptions", "type": "str"}, } def __init__( self, *, account_name: str, azure_file_url: str, account_key: str, relative_mount_path: str, mount_options: Optional[str] = None, **kwargs: Any ) -> None: """ :keyword account_name: The Azure Storage account name. Required. :paramtype account_name: str :keyword azure_file_url: This is of the form 'https://{account}.file.core.windows.net/'. Required. :paramtype azure_file_url: str :keyword account_key: The Azure Storage account key. Required. :paramtype account_key: str :keyword relative_mount_path: All file systems are mounted relative to the Batch mounts directory, accessible via the AZ_BATCH_NODE_MOUNTS_DIR environment variable. Required. :paramtype relative_mount_path: str :keyword mount_options: These are 'net use' options in Windows and 'mount' options in Linux. :paramtype mount_options: str """ super().__init__(**kwargs) self.account_name = account_name self.azure_file_url = azure_file_url self.account_key = account_key self.relative_mount_path = relative_mount_path self.mount_options = mount_options class Resource(_serialization.Model): """A definition of an Azure resource. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: The ID of the resource. :vartype id: str :ivar name: The name of the resource. :vartype name: str :ivar type: The type of the resource. :vartype type: str :ivar location: The location of the resource. :vartype location: str :ivar tags: The tags of the resource. :vartype tags: dict[str, str] """ _validation = { "id": {"readonly": True}, "name": {"readonly": True}, "type": {"readonly": True}, "location": {"readonly": True}, "tags": {"readonly": True}, } _attribute_map = { "id": {"key": "id", "type": "str"}, "name": {"key": "name", "type": "str"}, "type": {"key": "type", "type": "str"}, "location": {"key": "location", "type": "str"}, "tags": {"key": "tags", "type": "{str}"}, } def __init__(self, **kwargs: Any) -> None: """ """ super().__init__(**kwargs) self.id = None self.name = None self.type = None self.location = None self.tags = None class BatchAccount(Resource): # pylint: disable=too-many-instance-attributes """Contains information about an Azure Batch account. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: The ID of the resource. :vartype id: str :ivar name: The name of the resource. :vartype name: str :ivar type: The type of the resource. :vartype type: str :ivar location: The location of the resource. :vartype location: str :ivar tags: The tags of the resource. :vartype tags: dict[str, str] :ivar identity: The identity of the Batch account. :vartype identity: ~azure.mgmt.batch.models.BatchAccountIdentity :ivar account_endpoint: The account endpoint used to interact with the Batch service. :vartype account_endpoint: str :ivar node_management_endpoint: The endpoint used by compute node to connect to the Batch node management service. :vartype node_management_endpoint: str :ivar provisioning_state: The provisioned state of the resource. Known values are: "Invalid", "Creating", "Deleting", "Succeeded", "Failed", and "Cancelled". :vartype provisioning_state: str or ~azure.mgmt.batch.models.ProvisioningState :ivar pool_allocation_mode: The allocation mode for creating pools in the Batch account. Known values are: "BatchService" and "UserSubscription". :vartype pool_allocation_mode: str or ~azure.mgmt.batch.models.PoolAllocationMode :ivar key_vault_reference: Identifies the Azure key vault associated with a Batch account. :vartype key_vault_reference: ~azure.mgmt.batch.models.KeyVaultReference :ivar public_network_access: If not specified, the default value is 'enabled'. Known values are: "Enabled" and "Disabled". :vartype public_network_access: str or ~azure.mgmt.batch.models.PublicNetworkAccessType :ivar network_profile: The network profile only takes effect when publicNetworkAccess is enabled. :vartype network_profile: ~azure.mgmt.batch.models.NetworkProfile :ivar private_endpoint_connections: List of private endpoint connections associated with the Batch account. :vartype private_endpoint_connections: list[~azure.mgmt.batch.models.PrivateEndpointConnection] :ivar auto_storage: Contains information about the auto-storage account associated with a Batch account. :vartype auto_storage: ~azure.mgmt.batch.models.AutoStorageProperties :ivar encryption: Configures how customer data is encrypted inside the Batch account. By default, accounts are encrypted using a Microsoft managed key. For additional control, a customer-managed key can be used instead. :vartype encryption: ~azure.mgmt.batch.models.EncryptionProperties :ivar dedicated_core_quota: For accounts with PoolAllocationMode set to UserSubscription, quota is managed on the subscription so this value is not returned. :vartype dedicated_core_quota: int :ivar low_priority_core_quota: For accounts with PoolAllocationMode set to UserSubscription, quota is managed on the subscription so this value is not returned. :vartype low_priority_core_quota: int :ivar dedicated_core_quota_per_vm_family: A list of the dedicated core quota per Virtual Machine family for the Batch account. For accounts with PoolAllocationMode set to UserSubscription, quota is managed on the subscription so this value is not returned. :vartype dedicated_core_quota_per_vm_family: list[~azure.mgmt.batch.models.VirtualMachineFamilyCoreQuota] :ivar dedicated_core_quota_per_vm_family_enforced: If this flag is true, dedicated core quota is enforced via both the dedicatedCoreQuotaPerVMFamily and dedicatedCoreQuota properties on the account. If this flag is false, dedicated core quota is enforced only via the dedicatedCoreQuota property on the account and does not consider Virtual Machine family. :vartype dedicated_core_quota_per_vm_family_enforced: bool :ivar pool_quota: The pool quota for the Batch account. :vartype pool_quota: int :ivar active_job_and_job_schedule_quota: The active job and job schedule quota for the Batch account. :vartype active_job_and_job_schedule_quota: int :ivar allowed_authentication_modes: List of allowed authentication modes for the Batch account that can be used to authenticate with the data plane. This does not affect authentication with the control plane. :vartype allowed_authentication_modes: list[str or ~azure.mgmt.batch.models.AuthenticationMode] """ _validation = { "id": {"readonly": True}, "name": {"readonly": True}, "type": {"readonly": True}, "location": {"readonly": True}, "tags": {"readonly": True}, "account_endpoint": {"readonly": True}, "node_management_endpoint": {"readonly": True}, "provisioning_state": {"readonly": True}, "pool_allocation_mode": {"readonly": True}, "key_vault_reference": {"readonly": True}, "private_endpoint_connections": {"readonly": True}, "auto_storage": {"readonly": True}, "encryption": {"readonly": True}, "dedicated_core_quota": {"readonly": True}, "low_priority_core_quota": {"readonly": True}, "dedicated_core_quota_per_vm_family": {"readonly": True}, "dedicated_core_quota_per_vm_family_enforced": {"readonly": True}, "pool_quota": {"readonly": True}, "active_job_and_job_schedule_quota": {"readonly": True}, "allowed_authentication_modes": {"readonly": True}, } _attribute_map = { "id": {"key": "id", "type": "str"}, "name": {"key": "name", "type": "str"}, "type": {"key": "type", "type": "str"}, "location": {"key": "location", "type": "str"}, "tags": {"key": "tags", "type": "{str}"}, "identity": {"key": "identity", "type": "BatchAccountIdentity"}, "account_endpoint": {"key": "properties.accountEndpoint", "type": "str"}, "node_management_endpoint": {"key": "properties.nodeManagementEndpoint", "type": "str"}, "provisioning_state": {"key": "properties.provisioningState", "type": "str"}, "pool_allocation_mode": {"key": "properties.poolAllocationMode", "type": "str"}, "key_vault_reference": {"key": "properties.keyVaultReference", "type": "KeyVaultReference"}, "public_network_access": {"key": "properties.publicNetworkAccess", "type": "str"}, "network_profile": {"key": "properties.networkProfile", "type": "NetworkProfile"}, "private_endpoint_connections": { "key": "properties.privateEndpointConnections", "type": "[PrivateEndpointConnection]", }, "auto_storage": {"key": "properties.autoStorage", "type": "AutoStorageProperties"}, "encryption": {"key": "properties.encryption", "type": "EncryptionProperties"}, "dedicated_core_quota": {"key": "properties.dedicatedCoreQuota", "type": "int"}, "low_priority_core_quota": {"key": "properties.lowPriorityCoreQuota", "type": "int"}, "dedicated_core_quota_per_vm_family": { "key": "properties.dedicatedCoreQuotaPerVMFamily", "type": "[VirtualMachineFamilyCoreQuota]", }, "dedicated_core_quota_per_vm_family_enforced": { "key": "properties.dedicatedCoreQuotaPerVMFamilyEnforced", "type": "bool", }, "pool_quota": {"key": "properties.poolQuota", "type": "int"}, "active_job_and_job_schedule_quota": {"key": "properties.activeJobAndJobScheduleQuota", "type": "int"}, "allowed_authentication_modes": {"key": "properties.allowedAuthenticationModes", "type": "[str]"}, } def __init__( self, *, identity: Optional["_models.BatchAccountIdentity"] = None, public_network_access: Union[str, "_models.PublicNetworkAccessType"] = "Enabled", network_profile: Optional["_models.NetworkProfile"] = None, **kwargs: Any ) -> None: """ :keyword identity: The identity of the Batch account. :paramtype identity: ~azure.mgmt.batch.models.BatchAccountIdentity :keyword public_network_access: If not specified, the default value is 'enabled'. Known values are: "Enabled" and "Disabled". :paramtype public_network_access: str or ~azure.mgmt.batch.models.PublicNetworkAccessType :keyword network_profile: The network profile only takes effect when publicNetworkAccess is enabled. :paramtype network_profile: ~azure.mgmt.batch.models.NetworkProfile """ super().__init__(**kwargs) self.identity = identity self.account_endpoint = None self.node_management_endpoint = None self.provisioning_state = None self.pool_allocation_mode = None self.key_vault_reference = None self.public_network_access = public_network_access self.network_profile = network_profile self.private_endpoint_connections = None self.auto_storage = None self.encryption = None self.dedicated_core_quota = None self.low_priority_core_quota = None self.dedicated_core_quota_per_vm_family = None self.dedicated_core_quota_per_vm_family_enforced = None self.pool_quota = None self.active_job_and_job_schedule_quota = None self.allowed_authentication_modes = None class BatchAccountCreateParameters(_serialization.Model): """Parameters supplied to the Create operation. All required parameters must be populated in order to send to Azure. :ivar location: The region in which to create the account. Required. :vartype location: str :ivar tags: The user-specified tags associated with the account. :vartype tags: dict[str, str] :ivar identity: The identity of the Batch account. :vartype identity: ~azure.mgmt.batch.models.BatchAccountIdentity :ivar auto_storage: The properties related to the auto-storage account. :vartype auto_storage: ~azure.mgmt.batch.models.AutoStorageBaseProperties :ivar pool_allocation_mode: The pool allocation mode also affects how clients may authenticate to the Batch Service API. If the mode is BatchService, clients may authenticate using access keys or Azure Active Directory. If the mode is UserSubscription, clients must use Azure Active Directory. The default is BatchService. Known values are: "BatchService" and "UserSubscription". :vartype pool_allocation_mode: str or ~azure.mgmt.batch.models.PoolAllocationMode :ivar key_vault_reference: A reference to the Azure key vault associated with the Batch account. :vartype key_vault_reference: ~azure.mgmt.batch.models.KeyVaultReference :ivar public_network_access: If not specified, the default value is 'enabled'. Known values are: "Enabled" and "Disabled". :vartype public_network_access: str or ~azure.mgmt.batch.models.PublicNetworkAccessType :ivar network_profile: The network profile only takes effect when publicNetworkAccess is enabled. :vartype network_profile: ~azure.mgmt.batch.models.NetworkProfile :ivar encryption: Configures how customer data is encrypted inside the Batch account. By default, accounts are encrypted using a Microsoft managed key. For additional control, a customer-managed key can be used instead. :vartype encryption: ~azure.mgmt.batch.models.EncryptionProperties :ivar allowed_authentication_modes: List of allowed authentication modes for the Batch account that can be used to authenticate with the data plane. This does not affect authentication with the control plane. :vartype allowed_authentication_modes: list[str or ~azure.mgmt.batch.models.AuthenticationMode] """ _validation = { "location": {"required": True}, } _attribute_map = { "location": {"key": "location", "type": "str"}, "tags": {"key": "tags", "type": "{str}"}, "identity": {"key": "identity", "type": "BatchAccountIdentity"}, "auto_storage": {"key": "properties.autoStorage", "type": "AutoStorageBaseProperties"}, "pool_allocation_mode": {"key": "properties.poolAllocationMode", "type": "str"}, "key_vault_reference": {"key": "properties.keyVaultReference", "type": "KeyVaultReference"}, "public_network_access": {"key": "properties.publicNetworkAccess", "type": "str"}, "network_profile": {"key": "properties.networkProfile", "type": "NetworkProfile"}, "encryption": {"key": "properties.encryption", "type": "EncryptionProperties"}, "allowed_authentication_modes": {"key": "properties.allowedAuthenticationModes", "type": "[str]"}, } def __init__( self, *, location: str, tags: Optional[Dict[str, str]] = None, identity: Optional["_models.BatchAccountIdentity"] = None, auto_storage: Optional["_models.AutoStorageBaseProperties"] = None, pool_allocation_mode: Optional[Union[str, "_models.PoolAllocationMode"]] = None, key_vault_reference: Optional["_models.KeyVaultReference"] = None, public_network_access: Union[str, "_models.PublicNetworkAccessType"] = "Enabled", network_profile: Optional["_models.NetworkProfile"] = None, encryption: Optional["_models.EncryptionProperties"] = None, allowed_authentication_modes: Optional[List[Union[str, "_models.AuthenticationMode"]]] = None, **kwargs: Any ) -> None: """ :keyword location: The region in which to create the account. Required. :paramtype location: str :keyword tags: The user-specified tags associated with the account. :paramtype tags: dict[str, str] :keyword identity: The identity of the Batch account. :paramtype identity: ~azure.mgmt.batch.models.BatchAccountIdentity :keyword auto_storage: The properties related to the auto-storage account. :paramtype auto_storage: ~azure.mgmt.batch.models.AutoStorageBaseProperties :keyword pool_allocation_mode: The pool allocation mode also affects how clients may authenticate to the Batch Service API. If the mode is BatchService, clients may authenticate using access keys or Azure Active Directory. If the mode is UserSubscription, clients must use Azure Active Directory. The default is BatchService. Known values are: "BatchService" and "UserSubscription". :paramtype pool_allocation_mode: str or ~azure.mgmt.batch.models.PoolAllocationMode :keyword key_vault_reference: A reference to the Azure key vault associated with the Batch account. :paramtype key_vault_reference: ~azure.mgmt.batch.models.KeyVaultReference :keyword public_network_access: If not specified, the default value is 'enabled'. Known values are: "Enabled" and "Disabled". :paramtype public_network_access: str or ~azure.mgmt.batch.models.PublicNetworkAccessType :keyword network_profile: The network profile only takes effect when publicNetworkAccess is enabled. :paramtype network_profile: ~azure.mgmt.batch.models.NetworkProfile :keyword encryption: Configures how customer data is encrypted inside the Batch account. By default, accounts are encrypted using a Microsoft managed key. For additional control, a customer-managed key can be used instead. :paramtype encryption: ~azure.mgmt.batch.models.EncryptionProperties :keyword allowed_authentication_modes: List of allowed authentication modes for the Batch account that can be used to authenticate with the data plane. This does not affect authentication with the control plane. :paramtype allowed_authentication_modes: list[str or ~azure.mgmt.batch.models.AuthenticationMode] """ super().__init__(**kwargs) self.location = location self.tags = tags self.identity = identity self.auto_storage = auto_storage self.pool_allocation_mode = pool_allocation_mode self.key_vault_reference = key_vault_reference self.public_network_access = public_network_access self.network_profile = network_profile self.encryption = encryption self.allowed_authentication_modes = allowed_authentication_modes class BatchAccountIdentity(_serialization.Model): """The identity of the Batch account, if configured. This is used when the user specifies 'Microsoft.KeyVault' as their Batch account encryption configuration or when ``ManagedIdentity`` is selected as the auto-storage authentication mode. Variables are only populated by the server, and will be ignored when sending a request. All required parameters must be populated in order to send to Azure. :ivar principal_id: The principal id of the Batch account. This property will only be provided for a system assigned identity. :vartype principal_id: str :ivar tenant_id: The tenant id associated with the Batch account. This property will only be provided for a system assigned identity. :vartype tenant_id: str :ivar type: The type of identity used for the Batch account. Required. Known values are: "SystemAssigned", "UserAssigned", and "None". :vartype type: str or ~azure.mgmt.batch.models.ResourceIdentityType :ivar user_assigned_identities: The list of user identities associated with the Batch account. :vartype user_assigned_identities: dict[str, ~azure.mgmt.batch.models.UserAssignedIdentities] """ _validation = { "principal_id": {"readonly": True}, "tenant_id": {"readonly": True}, "type": {"required": True}, } _attribute_map = { "principal_id": {"key": "principalId", "type": "str"}, "tenant_id": {"key": "tenantId", "type": "str"}, "type": {"key": "type", "type": "str"}, "user_assigned_identities": {"key": "userAssignedIdentities", "type": "{UserAssignedIdentities}"}, } def __init__( self, *, type: Union[str, "_models.ResourceIdentityType"], user_assigned_identities: Optional[Dict[str, "_models.UserAssignedIdentities"]] = None, **kwargs: Any ) -> None: """ :keyword type: The type of identity used for the Batch account. Required. Known values are: "SystemAssigned", "UserAssigned", and "None". :paramtype type: str or ~azure.mgmt.batch.models.ResourceIdentityType :keyword user_assigned_identities: The list of user identities associated with the Batch account. :paramtype user_assigned_identities: dict[str, ~azure.mgmt.batch.models.UserAssignedIdentities] """ super().__init__(**kwargs) self.principal_id = None self.tenant_id = None self.type = type self.user_assigned_identities = user_assigned_identities class BatchAccountKeys(_serialization.Model): """A set of Azure Batch account keys. Variables are only populated by the server, and will be ignored when sending a request. :ivar account_name: The Batch account name. :vartype account_name: str :ivar primary: The primary key associated with the account. :vartype primary: str :ivar secondary: The secondary key associated with the account. :vartype secondary: str """ _validation = { "account_name": {"readonly": True}, "primary": {"readonly": True}, "secondary": {"readonly": True}, } _attribute_map = { "account_name": {"key": "accountName", "type": "str"}, "primary": {"key": "primary", "type": "str"}, "secondary": {"key": "secondary", "type": "str"}, } def __init__(self, **kwargs: Any) -> None: """ """ super().__init__(**kwargs) self.account_name = None self.primary = None self.secondary = None class BatchAccountListResult(_serialization.Model): """Values returned by the List operation. :ivar value: The collection of Batch accounts returned by the listing operation. :vartype value: list[~azure.mgmt.batch.models.BatchAccount] :ivar next_link: The continuation token. :vartype next_link: str """ _attribute_map = { "value": {"key": "value", "type": "[BatchAccount]"}, "next_link": {"key": "nextLink", "type": "str"}, } def __init__( self, *, value: Optional[List["_models.BatchAccount"]] = None, next_link: Optional[str] = None, **kwargs: Any ) -> None: """ :keyword value: The collection of Batch accounts returned by the listing operation. :paramtype value: list[~azure.mgmt.batch.models.BatchAccount] :keyword next_link: The continuation token. :paramtype next_link: str """ super().__init__(**kwargs) self.value = value self.next_link = next_link class BatchAccountRegenerateKeyParameters(_serialization.Model): """Parameters supplied to the RegenerateKey operation. All required parameters must be populated in order to send to Azure. :ivar key_name: The type of account key to regenerate. Required. Known values are: "Primary" and "Secondary". :vartype key_name: str or ~azure.mgmt.batch.models.AccountKeyType """ _validation = { "key_name": {"required": True}, } _attribute_map = { "key_name": {"key": "keyName", "type": "str"}, } def __init__(self, *, key_name: Union[str, "_models.AccountKeyType"], **kwargs: Any) -> None: """ :keyword key_name: The type of account key to regenerate. Required. Known values are: "Primary" and "Secondary". :paramtype key_name: str or ~azure.mgmt.batch.models.AccountKeyType """ super().__init__(**kwargs) self.key_name = key_name class BatchAccountUpdateParameters(_serialization.Model): """Parameters for updating an Azure Batch account. :ivar tags: The user-specified tags associated with the account. :vartype tags: dict[str, str] :ivar identity: The identity of the Batch account. :vartype identity: ~azure.mgmt.batch.models.BatchAccountIdentity :ivar auto_storage: The properties related to the auto-storage account. :vartype auto_storage: ~azure.mgmt.batch.models.AutoStorageBaseProperties :ivar encryption: Configures how customer data is encrypted inside the Batch account. By default, accounts are encrypted using a Microsoft managed key. For additional control, a customer-managed key can be used instead. :vartype encryption: ~azure.mgmt.batch.models.EncryptionProperties :ivar allowed_authentication_modes: List of allowed authentication modes for the Batch account that can be used to authenticate with the data plane. This does not affect authentication with the control plane. :vartype allowed_authentication_modes: list[str or ~azure.mgmt.batch.models.AuthenticationMode] :ivar public_network_access: If not specified, the default value is 'enabled'. Known values are: "Enabled" and "Disabled". :vartype public_network_access: str or ~azure.mgmt.batch.models.PublicNetworkAccessType :ivar network_profile: The network profile only takes effect when publicNetworkAccess is enabled. :vartype network_profile: ~azure.mgmt.batch.models.NetworkProfile """ _attribute_map = { "tags": {"key": "tags", "type": "{str}"}, "identity": {"key": "identity", "type": "BatchAccountIdentity"}, "auto_storage": {"key": "properties.autoStorage", "type": "AutoStorageBaseProperties"}, "encryption": {"key": "properties.encryption", "type": "EncryptionProperties"}, "allowed_authentication_modes": {"key": "properties.allowedAuthenticationModes", "type": "[str]"}, "public_network_access": {"key": "properties.publicNetworkAccess", "type": "str"}, "network_profile": {"key": "properties.networkProfile", "type": "NetworkProfile"}, } def __init__( self, *, tags: Optional[Dict[str, str]] = None, identity: Optional["_models.BatchAccountIdentity"] = None, auto_storage: Optional["_models.AutoStorageBaseProperties"] = None, encryption: Optional["_models.EncryptionProperties"] = None, allowed_authentication_modes: Optional[List[Union[str, "_models.AuthenticationMode"]]] = None, public_network_access: Union[str, "_models.PublicNetworkAccessType"] = "Enabled", network_profile: Optional["_models.NetworkProfile"] = None, **kwargs: Any ) -> None: """ :keyword tags: The user-specified tags associated with the account. :paramtype tags: dict[str, str] :keyword identity: The identity of the Batch account. :paramtype identity: ~azure.mgmt.batch.models.BatchAccountIdentity :keyword auto_storage: The properties related to the auto-storage account. :paramtype auto_storage: ~azure.mgmt.batch.models.AutoStorageBaseProperties :keyword encryption: Configures how customer data is encrypted inside the Batch account. By default, accounts are encrypted using a Microsoft managed key. For additional control, a customer-managed key can be used instead. :paramtype encryption: ~azure.mgmt.batch.models.EncryptionProperties :keyword allowed_authentication_modes: List of allowed authentication modes for the Batch account that can be used to authenticate with the data plane. This does not affect authentication with the control plane. :paramtype allowed_authentication_modes: list[str or ~azure.mgmt.batch.models.AuthenticationMode] :keyword public_network_access: If not specified, the default value is 'enabled'. Known values are: "Enabled" and "Disabled". :paramtype public_network_access: str or ~azure.mgmt.batch.models.PublicNetworkAccessType :keyword network_profile: The network profile only takes effect when publicNetworkAccess is enabled. :paramtype network_profile: ~azure.mgmt.batch.models.NetworkProfile """ super().__init__(**kwargs) self.tags = tags self.identity = identity self.auto_storage = auto_storage self.encryption = encryption self.allowed_authentication_modes = allowed_authentication_modes self.public_network_access = public_network_access self.network_profile = network_profile class BatchLocationQuota(_serialization.Model): """Quotas associated with a Batch region for a particular subscription. Variables are only populated by the server, and will be ignored when sending a request. :ivar account_quota: The number of Batch accounts that may be created under the subscription in the specified region. :vartype account_quota: int """ _validation = { "account_quota": {"readonly": True}, } _attribute_map = { "account_quota": {"key": "accountQuota", "type": "int"}, } def __init__(self, **kwargs: Any) -> None: """ """ super().__init__(**kwargs) self.account_quota = None class BatchPoolIdentity(_serialization.Model): """The identity of the Batch pool, if configured. If the pool identity is updated during update an existing pool, only the new vms which are created after the pool shrinks to 0 will have the updated identities. All required parameters must be populated in order to send to Azure. :ivar type: The type of identity used for the Batch Pool. Required. Known values are: "UserAssigned" and "None". :vartype type: str or ~azure.mgmt.batch.models.PoolIdentityType :ivar user_assigned_identities: The list of user identities associated with the Batch pool. :vartype user_assigned_identities: dict[str, ~azure.mgmt.batch.models.UserAssignedIdentities] """ _validation = { "type": {"required": True}, } _attribute_map = { "type": {"key": "type", "type": "str"}, "user_assigned_identities": {"key": "userAssignedIdentities", "type": "{UserAssignedIdentities}"}, } def __init__( self, *, type: Union[str, "_models.PoolIdentityType"], user_assigned_identities: Optional[Dict[str, "_models.UserAssignedIdentities"]] = None, **kwargs: Any ) -> None: """ :keyword type: The type of identity used for the Batch Pool. Required. Known values are: "UserAssigned" and "None". :paramtype type: str or ~azure.mgmt.batch.models.PoolIdentityType :keyword user_assigned_identities: The list of user identities associated with the Batch pool. :paramtype user_assigned_identities: dict[str, ~azure.mgmt.batch.models.UserAssignedIdentities] """ super().__init__(**kwargs) self.type = type self.user_assigned_identities = user_assigned_identities class Certificate(ProxyResource): # pylint: disable=too-many-instance-attributes """Contains information about a certificate. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: The ID of the resource. :vartype id: str :ivar name: The name of the resource. :vartype name: str :ivar type: The type of the resource. :vartype type: str :ivar etag: The ETag of the resource, used for concurrency statements. :vartype etag: str :ivar thumbprint_algorithm: This must match the first portion of the certificate name. Currently required to be 'SHA1'. :vartype thumbprint_algorithm: str :ivar thumbprint: This must match the thumbprint from the name. :vartype thumbprint: str :ivar format: The format of the certificate - either Pfx or Cer. If omitted, the default is Pfx. Known values are: "Pfx" and "Cer". :vartype format: str or ~azure.mgmt.batch.models.CertificateFormat :ivar provisioning_state: Known values are: "Succeeded", "Deleting", and "Failed". :vartype provisioning_state: str or ~azure.mgmt.batch.models.CertificateProvisioningState :ivar provisioning_state_transition_time: The time at which the certificate entered its current state. :vartype provisioning_state_transition_time: ~datetime.datetime :ivar previous_provisioning_state: The previous provisioned state of the resource. Known values are: "Succeeded", "Deleting", and "Failed". :vartype previous_provisioning_state: str or ~azure.mgmt.batch.models.CertificateProvisioningState :ivar previous_provisioning_state_transition_time: The time at which the certificate entered its previous state. :vartype previous_provisioning_state_transition_time: ~datetime.datetime :ivar public_data: The public key of the certificate. :vartype public_data: str :ivar delete_certificate_error: This is only returned when the certificate provisioningState is 'Failed'. :vartype delete_certificate_error: ~azure.mgmt.batch.models.DeleteCertificateError """ _validation = { "id": {"readonly": True}, "name": {"readonly": True}, "type": {"readonly": True}, "etag": {"readonly": True}, "provisioning_state": {"readonly": True}, "provisioning_state_transition_time": {"readonly": True}, "previous_provisioning_state": {"readonly": True}, "previous_provisioning_state_transition_time": {"readonly": True}, "public_data": {"readonly": True}, "delete_certificate_error": {"readonly": True}, } _attribute_map = { "id": {"key": "id", "type": "str"}, "name": {"key": "name", "type": "str"}, "type": {"key": "type", "type": "str"}, "etag": {"key": "etag", "type": "str"}, "thumbprint_algorithm": {"key": "properties.thumbprintAlgorithm", "type": "str"}, "thumbprint": {"key": "properties.thumbprint", "type": "str"}, "format": {"key": "properties.format", "type": "str"}, "provisioning_state": {"key": "properties.provisioningState", "type": "str"}, "provisioning_state_transition_time": {"key": "properties.provisioningStateTransitionTime", "type": "iso-8601"}, "previous_provisioning_state": {"key": "properties.previousProvisioningState", "type": "str"}, "previous_provisioning_state_transition_time": { "key": "properties.previousProvisioningStateTransitionTime", "type": "iso-8601", }, "public_data": {"key": "properties.publicData", "type": "str"}, "delete_certificate_error": {"key": "properties.deleteCertificateError", "type": "DeleteCertificateError"}, } def __init__( self, *, thumbprint_algorithm: Optional[str] = None, thumbprint: Optional[str] = None, format: Optional[Union[str, "_models.CertificateFormat"]] = None, **kwargs: Any ) -> None: """ :keyword thumbprint_algorithm: This must match the first portion of the certificate name. Currently required to be 'SHA1'. :paramtype thumbprint_algorithm: str :keyword thumbprint: This must match the thumbprint from the name. :paramtype thumbprint: str :keyword format: The format of the certificate - either Pfx or Cer. If omitted, the default is Pfx. Known values are: "Pfx" and "Cer". :paramtype format: str or ~azure.mgmt.batch.models.CertificateFormat """ super().__init__(**kwargs) self.thumbprint_algorithm = thumbprint_algorithm self.thumbprint = thumbprint self.format = format self.provisioning_state = None self.provisioning_state_transition_time = None self.previous_provisioning_state = None self.previous_provisioning_state_transition_time = None self.public_data = None self.delete_certificate_error = None class CertificateBaseProperties(_serialization.Model): """Base certificate properties. :ivar thumbprint_algorithm: This must match the first portion of the certificate name. Currently required to be 'SHA1'. :vartype thumbprint_algorithm: str :ivar thumbprint: This must match the thumbprint from the name. :vartype thumbprint: str :ivar format: The format of the certificate - either Pfx or Cer. If omitted, the default is Pfx. Known values are: "Pfx" and "Cer". :vartype format: str or ~azure.mgmt.batch.models.CertificateFormat """ _attribute_map = { "thumbprint_algorithm": {"key": "thumbprintAlgorithm", "type": "str"}, "thumbprint": {"key": "thumbprint", "type": "str"}, "format": {"key": "format", "type": "str"}, } def __init__( self, *, thumbprint_algorithm: Optional[str] = None, thumbprint: Optional[str] = None, format: Optional[Union[str, "_models.CertificateFormat"]] = None, **kwargs: Any ) -> None: """ :keyword thumbprint_algorithm: This must match the first portion of the certificate name. Currently required to be 'SHA1'. :paramtype thumbprint_algorithm: str :keyword thumbprint: This must match the thumbprint from the name. :paramtype thumbprint: str :keyword format: The format of the certificate - either Pfx or Cer. If omitted, the default is Pfx. Known values are: "Pfx" and "Cer". :paramtype format: str or ~azure.mgmt.batch.models.CertificateFormat """ super().__init__(**kwargs) self.thumbprint_algorithm = thumbprint_algorithm self.thumbprint = thumbprint self.format = format class CertificateCreateOrUpdateParameters(ProxyResource): """Contains information about a certificate. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: The ID of the resource. :vartype id: str :ivar name: The name of the resource. :vartype name: str :ivar type: The type of the resource. :vartype type: str :ivar etag: The ETag of the resource, used for concurrency statements. :vartype etag: str :ivar thumbprint_algorithm: This must match the first portion of the certificate name. Currently required to be 'SHA1'. :vartype thumbprint_algorithm: str :ivar thumbprint: This must match the thumbprint from the name. :vartype thumbprint: str :ivar format: The format of the certificate - either Pfx or Cer. If omitted, the default is Pfx. Known values are: "Pfx" and "Cer". :vartype format: str or ~azure.mgmt.batch.models.CertificateFormat :ivar data: The maximum size is 10KB. :vartype data: str :ivar password: This must not be specified if the certificate format is Cer. :vartype password: str """ _validation = { "id": {"readonly": True}, "name": {"readonly": True}, "type": {"readonly": True}, "etag": {"readonly": True}, } _attribute_map = { "id": {"key": "id", "type": "str"}, "name": {"key": "name", "type": "str"}, "type": {"key": "type", "type": "str"}, "etag": {"key": "etag", "type": "str"}, "thumbprint_algorithm": {"key": "properties.thumbprintAlgorithm", "type": "str"}, "thumbprint": {"key": "properties.thumbprint", "type": "str"}, "format": {"key": "properties.format", "type": "str"}, "data": {"key": "properties.data", "type": "str"}, "password": {"key": "properties.password", "type": "str"}, } def __init__( self, *, thumbprint_algorithm: Optional[str] = None, thumbprint: Optional[str] = None, format: Optional[Union[str, "_models.CertificateFormat"]] = None, data: Optional[str] = None, password: Optional[str] = None, **kwargs: Any ) -> None: """ :keyword thumbprint_algorithm: This must match the first portion of the certificate name. Currently required to be 'SHA1'. :paramtype thumbprint_algorithm: str :keyword thumbprint: This must match the thumbprint from the name. :paramtype thumbprint: str :keyword format: The format of the certificate - either Pfx or Cer. If omitted, the default is Pfx. Known values are: "Pfx" and "Cer". :paramtype format: str or ~azure.mgmt.batch.models.CertificateFormat :keyword data: The maximum size is 10KB. :paramtype data: str :keyword password: This must not be specified if the certificate format is Cer. :paramtype password: str """ super().__init__(**kwargs) self.thumbprint_algorithm = thumbprint_algorithm self.thumbprint = thumbprint self.format = format self.data = data self.password = password class CertificateCreateOrUpdateProperties(CertificateBaseProperties): """Certificate properties for create operations. All required parameters must be populated in order to send to Azure. :ivar thumbprint_algorithm: This must match the first portion of the certificate name. Currently required to be 'SHA1'. :vartype thumbprint_algorithm: str :ivar thumbprint: This must match the thumbprint from the name. :vartype thumbprint: str :ivar format: The format of the certificate - either Pfx or Cer. If omitted, the default is Pfx. Known values are: "Pfx" and "Cer". :vartype format: str or ~azure.mgmt.batch.models.CertificateFormat :ivar data: The maximum size is 10KB. Required. :vartype data: str :ivar password: This must not be specified if the certificate format is Cer. :vartype password: str """ _validation = { "data": {"required": True}, } _attribute_map = { "thumbprint_algorithm": {"key": "thumbprintAlgorithm", "type": "str"}, "thumbprint": {"key": "thumbprint", "type": "str"}, "format": {"key": "format", "type": "str"}, "data": {"key": "data", "type": "str"}, "password": {"key": "password", "type": "str"}, } def __init__( self, *, data: str, thumbprint_algorithm: Optional[str] = None, thumbprint: Optional[str] = None, format: Optional[Union[str, "_models.CertificateFormat"]] = None, password: Optional[str] = None, **kwargs: Any ) -> None: """ :keyword thumbprint_algorithm: This must match the first portion of the certificate name. Currently required to be 'SHA1'. :paramtype thumbprint_algorithm: str :keyword thumbprint: This must match the thumbprint from the name. :paramtype thumbprint: str :keyword format: The format of the certificate - either Pfx or Cer. If omitted, the default is Pfx. Known values are: "Pfx" and "Cer". :paramtype format: str or ~azure.mgmt.batch.models.CertificateFormat :keyword data: The maximum size is 10KB. Required. :paramtype data: str :keyword password: This must not be specified if the certificate format is Cer. :paramtype password: str """ super().__init__(thumbprint_algorithm=thumbprint_algorithm, thumbprint=thumbprint, format=format, **kwargs) self.data = data self.password = password class CertificateProperties(CertificateBaseProperties): """Certificate properties. Variables are only populated by the server, and will be ignored when sending a request. :ivar thumbprint_algorithm: This must match the first portion of the certificate name. Currently required to be 'SHA1'. :vartype thumbprint_algorithm: str :ivar thumbprint: This must match the thumbprint from the name. :vartype thumbprint: str :ivar format: The format of the certificate - either Pfx or Cer. If omitted, the default is Pfx. Known values are: "Pfx" and "Cer". :vartype format: str or ~azure.mgmt.batch.models.CertificateFormat :ivar provisioning_state: Known values are: "Succeeded", "Deleting", and "Failed". :vartype provisioning_state: str or ~azure.mgmt.batch.models.CertificateProvisioningState :ivar provisioning_state_transition_time: The time at which the certificate entered its current state. :vartype provisioning_state_transition_time: ~datetime.datetime :ivar previous_provisioning_state: The previous provisioned state of the resource. Known values are: "Succeeded", "Deleting", and "Failed". :vartype previous_provisioning_state: str or ~azure.mgmt.batch.models.CertificateProvisioningState :ivar previous_provisioning_state_transition_time: The time at which the certificate entered its previous state. :vartype previous_provisioning_state_transition_time: ~datetime.datetime :ivar public_data: The public key of the certificate. :vartype public_data: str :ivar delete_certificate_error: This is only returned when the certificate provisioningState is 'Failed'. :vartype delete_certificate_error: ~azure.mgmt.batch.models.DeleteCertificateError """ _validation = { "provisioning_state": {"readonly": True}, "provisioning_state_transition_time": {"readonly": True}, "previous_provisioning_state": {"readonly": True}, "previous_provisioning_state_transition_time": {"readonly": True}, "public_data": {"readonly": True}, "delete_certificate_error": {"readonly": True}, } _attribute_map = { "thumbprint_algorithm": {"key": "thumbprintAlgorithm", "type": "str"}, "thumbprint": {"key": "thumbprint", "type": "str"}, "format": {"key": "format", "type": "str"}, "provisioning_state": {"key": "provisioningState", "type": "str"}, "provisioning_state_transition_time": {"key": "provisioningStateTransitionTime", "type": "iso-8601"}, "previous_provisioning_state": {"key": "previousProvisioningState", "type": "str"}, "previous_provisioning_state_transition_time": { "key": "previousProvisioningStateTransitionTime", "type": "iso-8601", }, "public_data": {"key": "publicData", "type": "str"}, "delete_certificate_error": {"key": "deleteCertificateError", "type": "DeleteCertificateError"}, } def __init__( self, *, thumbprint_algorithm: Optional[str] = None, thumbprint: Optional[str] = None, format: Optional[Union[str, "_models.CertificateFormat"]] = None, **kwargs: Any ) -> None: """ :keyword thumbprint_algorithm: This must match the first portion of the certificate name. Currently required to be 'SHA1'. :paramtype thumbprint_algorithm: str :keyword thumbprint: This must match the thumbprint from the name. :paramtype thumbprint: str :keyword format: The format of the certificate - either Pfx or Cer. If omitted, the default is Pfx. Known values are: "Pfx" and "Cer". :paramtype format: str or ~azure.mgmt.batch.models.CertificateFormat """ super().__init__(thumbprint_algorithm=thumbprint_algorithm, thumbprint=thumbprint, format=format, **kwargs) self.provisioning_state = None self.provisioning_state_transition_time = None self.previous_provisioning_state = None self.previous_provisioning_state_transition_time = None self.public_data = None self.delete_certificate_error = None class CertificateReference(_serialization.Model): """Warning: This object is deprecated and will be removed after February, 2024. Please use the `Azure KeyVault Extension <https://learn.microsoft.com/azure/batch/batch-certificate-migration-guide>`_ instead. All required parameters must be populated in order to send to Azure. :ivar id: The fully qualified ID of the certificate to install on the pool. This must be inside the same batch account as the pool. Required. :vartype id: str :ivar store_location: The default value is currentUser. This property is applicable only for pools configured with Windows nodes (that is, created with cloudServiceConfiguration, or with virtualMachineConfiguration using a Windows image reference). For Linux compute nodes, the certificates are stored in a directory inside the task working directory and an environment variable AZ_BATCH_CERTIFICATES_DIR is supplied to the task to query for this location. For certificates with visibility of 'remoteUser', a 'certs' directory is created in the user's home directory (e.g., /home/{user-name}/certs) and certificates are placed in that directory. Known values are: "CurrentUser" and "LocalMachine". :vartype store_location: str or ~azure.mgmt.batch.models.CertificateStoreLocation :ivar store_name: This property is applicable only for pools configured with Windows nodes (that is, created with cloudServiceConfiguration, or with virtualMachineConfiguration using a Windows image reference). Common store names include: My, Root, CA, Trust, Disallowed, TrustedPeople, TrustedPublisher, AuthRoot, AddressBook, but any custom store name can also be used. The default value is My. :vartype store_name: str :ivar visibility: Which user accounts on the compute node should have access to the private data of the certificate. :vartype visibility: list[str or ~azure.mgmt.batch.models.CertificateVisibility] """ _validation = { "id": {"required": True}, } _attribute_map = { "id": {"key": "id", "type": "str"}, "store_location": {"key": "storeLocation", "type": "str"}, "store_name": {"key": "storeName", "type": "str"}, "visibility": {"key": "visibility", "type": "[str]"}, } def __init__( self, *, id: str, # pylint: disable=redefined-builtin store_location: Optional[Union[str, "_models.CertificateStoreLocation"]] = None, store_name: Optional[str] = None, visibility: Optional[List[Union[str, "_models.CertificateVisibility"]]] = None, **kwargs: Any ) -> None: """ :keyword id: The fully qualified ID of the certificate to install on the pool. This must be inside the same batch account as the pool. Required. :paramtype id: str :keyword store_location: The default value is currentUser. This property is applicable only for pools configured with Windows nodes (that is, created with cloudServiceConfiguration, or with virtualMachineConfiguration using a Windows image reference). For Linux compute nodes, the certificates are stored in a directory inside the task working directory and an environment variable AZ_BATCH_CERTIFICATES_DIR is supplied to the task to query for this location. For certificates with visibility of 'remoteUser', a 'certs' directory is created in the user's home directory (e.g., /home/{user-name}/certs) and certificates are placed in that directory. Known values are: "CurrentUser" and "LocalMachine". :paramtype store_location: str or ~azure.mgmt.batch.models.CertificateStoreLocation :keyword store_name: This property is applicable only for pools configured with Windows nodes (that is, created with cloudServiceConfiguration, or with virtualMachineConfiguration using a Windows image reference). Common store names include: My, Root, CA, Trust, Disallowed, TrustedPeople, TrustedPublisher, AuthRoot, AddressBook, but any custom store name can also be used. The default value is My. :paramtype store_name: str :keyword visibility: Which user accounts on the compute node should have access to the private data of the certificate. :paramtype visibility: list[str or ~azure.mgmt.batch.models.CertificateVisibility] """ super().__init__(**kwargs) self.id = id self.store_location = store_location self.store_name = store_name self.visibility = visibility class CheckNameAvailabilityParameters(_serialization.Model): """Parameters for a check name availability request. Variables are only populated by the server, and will be ignored when sending a request. All required parameters must be populated in order to send to Azure. :ivar name: The name to check for availability. Required. :vartype name: str :ivar type: The resource type. Required. Default value is "Microsoft.Batch/batchAccounts". :vartype type: str """ _validation = { "name": {"required": True}, "type": {"required": True, "constant": True}, } _attribute_map = { "name": {"key": "name", "type": "str"}, "type": {"key": "type", "type": "str"}, } type = "Microsoft.Batch/batchAccounts" def __init__(self, *, name: str, **kwargs: Any) -> None: """ :keyword name: The name to check for availability. Required. :paramtype name: str """ super().__init__(**kwargs) self.name = name class CheckNameAvailabilityResult(_serialization.Model): """The CheckNameAvailability operation response. Variables are only populated by the server, and will be ignored when sending a request. :ivar name_available: Gets a boolean value that indicates whether the name is available for you to use. If true, the name is available. If false, the name has already been taken or invalid and cannot be used. :vartype name_available: bool :ivar reason: Gets the reason that a Batch account name could not be used. The Reason element is only returned if NameAvailable is false. Known values are: "Invalid" and "AlreadyExists". :vartype reason: str or ~azure.mgmt.batch.models.NameAvailabilityReason :ivar message: Gets an error message explaining the Reason value in more detail. :vartype message: str """ _validation = { "name_available": {"readonly": True}, "reason": {"readonly": True}, "message": {"readonly": True}, } _attribute_map = { "name_available": {"key": "nameAvailable", "type": "bool"}, "reason": {"key": "reason", "type": "str"}, "message": {"key": "message", "type": "str"}, } def __init__(self, **kwargs: Any) -> None: """ """ super().__init__(**kwargs) self.name_available = None self.reason = None self.message = None class CIFSMountConfiguration(_serialization.Model): """Information used to connect to a CIFS file system. All required parameters must be populated in order to send to Azure. :ivar user_name: The user to use for authentication against the CIFS file system. Required. :vartype user_name: str :ivar source: The URI of the file system to mount. Required. :vartype source: str :ivar relative_mount_path: All file systems are mounted relative to the Batch mounts directory, accessible via the AZ_BATCH_NODE_MOUNTS_DIR environment variable. Required. :vartype relative_mount_path: str :ivar mount_options: These are 'net use' options in Windows and 'mount' options in Linux. :vartype mount_options: str :ivar password: The password to use for authentication against the CIFS file system. Required. :vartype password: str """ _validation = { "user_name": {"required": True}, "source": {"required": True}, "relative_mount_path": {"required": True}, "password": {"required": True}, } _attribute_map = { "user_name": {"key": "userName", "type": "str"}, "source": {"key": "source", "type": "str"}, "relative_mount_path": {"key": "relativeMountPath", "type": "str"}, "mount_options": {"key": "mountOptions", "type": "str"}, "password": {"key": "password", "type": "str"}, } def __init__( self, *, user_name: str, source: str, relative_mount_path: str, password: str, mount_options: Optional[str] = None, **kwargs: Any ) -> None: """ :keyword user_name: The user to use for authentication against the CIFS file system. Required. :paramtype user_name: str :keyword source: The URI of the file system to mount. Required. :paramtype source: str :keyword relative_mount_path: All file systems are mounted relative to the Batch mounts directory, accessible via the AZ_BATCH_NODE_MOUNTS_DIR environment variable. Required. :paramtype relative_mount_path: str :keyword mount_options: These are 'net use' options in Windows and 'mount' options in Linux. :paramtype mount_options: str :keyword password: The password to use for authentication against the CIFS file system. Required. :paramtype password: str """ super().__init__(**kwargs) self.user_name = user_name self.source = source self.relative_mount_path = relative_mount_path self.mount_options = mount_options self.password = password class CloudErrorBody(_serialization.Model): """An error response from the Batch service. :ivar code: An identifier for the error. Codes are invariant and are intended to be consumed programmatically. :vartype code: str :ivar message: A message describing the error, intended to be suitable for display in a user interface. :vartype message: str :ivar target: The target of the particular error. For example, the name of the property in error. :vartype target: str :ivar details: A list of additional details about the error. :vartype details: list[~azure.mgmt.batch.models.CloudErrorBody] """ _attribute_map = { "code": {"key": "code", "type": "str"}, "message": {"key": "message", "type": "str"}, "target": {"key": "target", "type": "str"}, "details": {"key": "details", "type": "[CloudErrorBody]"}, } def __init__( self, *, code: Optional[str] = None, message: Optional[str] = None, target: Optional[str] = None, details: Optional[List["_models.CloudErrorBody"]] = None, **kwargs: Any ) -> None: """ :keyword code: An identifier for the error. Codes are invariant and are intended to be consumed programmatically. :paramtype code: str :keyword message: A message describing the error, intended to be suitable for display in a user interface. :paramtype message: str :keyword target: The target of the particular error. For example, the name of the property in error. :paramtype target: str :keyword details: A list of additional details about the error. :paramtype details: list[~azure.mgmt.batch.models.CloudErrorBody] """ super().__init__(**kwargs) self.code = code self.message = message self.target = target self.details = details class CloudServiceConfiguration(_serialization.Model): """The configuration for nodes in a pool based on the Azure Cloud Services platform. All required parameters must be populated in order to send to Azure. :ivar os_family: Possible values are: 2 - OS Family 2, equivalent to Windows Server 2008 R2 SP1. 3 - OS Family 3, equivalent to Windows Server 2012. 4 - OS Family 4, equivalent to Windows Server 2012 R2. 5 - OS Family 5, equivalent to Windows Server 2016. 6 - OS Family 6, equivalent to Windows Server 2019. For more information, see Azure Guest OS Releases (https://azure.microsoft.com/documentation/articles/cloud-services-guestos-update-matrix/#releases). Required. :vartype os_family: str :ivar os_version: The default value is * which specifies the latest operating system version for the specified OS family. :vartype os_version: str """ _validation = { "os_family": {"required": True}, } _attribute_map = { "os_family": {"key": "osFamily", "type": "str"}, "os_version": {"key": "osVersion", "type": "str"}, } def __init__(self, *, os_family: str, os_version: Optional[str] = None, **kwargs: Any) -> None: """ :keyword os_family: Possible values are: 2 - OS Family 2, equivalent to Windows Server 2008 R2 SP1. 3 - OS Family 3, equivalent to Windows Server 2012. 4 - OS Family 4, equivalent to Windows Server 2012 R2. 5 - OS Family 5, equivalent to Windows Server 2016. 6 - OS Family 6, equivalent to Windows Server 2019. For more information, see Azure Guest OS Releases (https://azure.microsoft.com/documentation/articles/cloud-services-guestos-update-matrix/#releases). Required. :paramtype os_family: str :keyword os_version: The default value is * which specifies the latest operating system version for the specified OS family. :paramtype os_version: str """ super().__init__(**kwargs) self.os_family = os_family self.os_version = os_version class ComputeNodeIdentityReference(_serialization.Model): """The reference to a user assigned identity associated with the Batch pool which a compute node will use. :ivar resource_id: The ARM resource id of the user assigned identity. :vartype resource_id: str """ _attribute_map = { "resource_id": {"key": "resourceId", "type": "str"}, } def __init__(self, *, resource_id: Optional[str] = None, **kwargs: Any) -> None: """ :keyword resource_id: The ARM resource id of the user assigned identity. :paramtype resource_id: str """ super().__init__(**kwargs) self.resource_id = resource_id class ContainerConfiguration(_serialization.Model): """The configuration for container-enabled pools. All required parameters must be populated in order to send to Azure. :ivar type: The container technology to be used. Required. Known values are: "DockerCompatible" and "CriCompatible". :vartype type: str or ~azure.mgmt.batch.models.ContainerType :ivar container_image_names: This is the full image reference, as would be specified to "docker pull". An image will be sourced from the default Docker registry unless the image is fully qualified with an alternative registry. :vartype container_image_names: list[str] :ivar container_registries: If any images must be downloaded from a private registry which requires credentials, then those credentials must be provided here. :vartype container_registries: list[~azure.mgmt.batch.models.ContainerRegistry] """ _validation = { "type": {"required": True}, } _attribute_map = { "type": {"key": "type", "type": "str"}, "container_image_names": {"key": "containerImageNames", "type": "[str]"}, "container_registries": {"key": "containerRegistries", "type": "[ContainerRegistry]"}, } def __init__( self, *, type: Union[str, "_models.ContainerType"], container_image_names: Optional[List[str]] = None, container_registries: Optional[List["_models.ContainerRegistry"]] = None, **kwargs: Any ) -> None: """ :keyword type: The container technology to be used. Required. Known values are: "DockerCompatible" and "CriCompatible". :paramtype type: str or ~azure.mgmt.batch.models.ContainerType :keyword container_image_names: This is the full image reference, as would be specified to "docker pull". An image will be sourced from the default Docker registry unless the image is fully qualified with an alternative registry. :paramtype container_image_names: list[str] :keyword container_registries: If any images must be downloaded from a private registry which requires credentials, then those credentials must be provided here. :paramtype container_registries: list[~azure.mgmt.batch.models.ContainerRegistry] """ super().__init__(**kwargs) self.type = type self.container_image_names = container_image_names self.container_registries = container_registries class ContainerRegistry(_serialization.Model): """A private container registry. :ivar user_name: The user name to log into the registry server. :vartype user_name: str :ivar password: The password to log into the registry server. :vartype password: str :ivar registry_server: If omitted, the default is "docker.io". :vartype registry_server: str :ivar identity_reference: The reference to a user assigned identity associated with the Batch pool which a compute node will use. :vartype identity_reference: ~azure.mgmt.batch.models.ComputeNodeIdentityReference """ _attribute_map = { "user_name": {"key": "username", "type": "str"}, "password": {"key": "password", "type": "str"}, "registry_server": {"key": "registryServer", "type": "str"}, "identity_reference": {"key": "identityReference", "type": "ComputeNodeIdentityReference"}, } def __init__( self, *, user_name: Optional[str] = None, password: Optional[str] = None, registry_server: Optional[str] = None, identity_reference: Optional["_models.ComputeNodeIdentityReference"] = None, **kwargs: Any ) -> None: """ :keyword user_name: The user name to log into the registry server. :paramtype user_name: str :keyword password: The password to log into the registry server. :paramtype password: str :keyword registry_server: If omitted, the default is "docker.io". :paramtype registry_server: str :keyword identity_reference: The reference to a user assigned identity associated with the Batch pool which a compute node will use. :paramtype identity_reference: ~azure.mgmt.batch.models.ComputeNodeIdentityReference """ super().__init__(**kwargs) self.user_name = user_name self.password = password self.registry_server = registry_server self.identity_reference = identity_reference class DataDisk(_serialization.Model): """Settings which will be used by the data disks associated to Compute Nodes in the Pool. When using attached data disks, you need to mount and format the disks from within a VM to use them. All required parameters must be populated in order to send to Azure. :ivar lun: The lun is used to uniquely identify each data disk. If attaching multiple disks, each should have a distinct lun. The value must be between 0 and 63, inclusive. Required. :vartype lun: int :ivar caching: Values are: none - The caching mode for the disk is not enabled. readOnly - The caching mode for the disk is read only. readWrite - The caching mode for the disk is read and write. The default value for caching is none. For information about the caching options see: https://blogs.msdn.microsoft.com/windowsazurestorage/2012/06/27/exploring-windows-azure-drives-disks-and-images/. Known values are: "None", "ReadOnly", and "ReadWrite". :vartype caching: str or ~azure.mgmt.batch.models.CachingType :ivar disk_size_gb: The initial disk size in GB when creating new data disk. Required. :vartype disk_size_gb: int :ivar storage_account_type: If omitted, the default is "Standard_LRS". Values are: Standard_LRS - The data disk should use standard locally redundant storage. Premium_LRS - The data disk should use premium locally redundant storage. Known values are: "Standard_LRS" and "Premium_LRS". :vartype storage_account_type: str or ~azure.mgmt.batch.models.StorageAccountType """ _validation = { "lun": {"required": True}, "disk_size_gb": {"required": True}, } _attribute_map = { "lun": {"key": "lun", "type": "int"}, "caching": {"key": "caching", "type": "str"}, "disk_size_gb": {"key": "diskSizeGB", "type": "int"}, "storage_account_type": {"key": "storageAccountType", "type": "str"}, } def __init__( self, *, lun: int, disk_size_gb: int, caching: Optional[Union[str, "_models.CachingType"]] = None, storage_account_type: Optional[Union[str, "_models.StorageAccountType"]] = None, **kwargs: Any ) -> None: """ :keyword lun: The lun is used to uniquely identify each data disk. If attaching multiple disks, each should have a distinct lun. The value must be between 0 and 63, inclusive. Required. :paramtype lun: int :keyword caching: Values are: none - The caching mode for the disk is not enabled. readOnly - The caching mode for the disk is read only. readWrite - The caching mode for the disk is read and write. The default value for caching is none. For information about the caching options see: https://blogs.msdn.microsoft.com/windowsazurestorage/2012/06/27/exploring-windows-azure-drives-disks-and-images/. Known values are: "None", "ReadOnly", and "ReadWrite". :paramtype caching: str or ~azure.mgmt.batch.models.CachingType :keyword disk_size_gb: The initial disk size in GB when creating new data disk. Required. :paramtype disk_size_gb: int :keyword storage_account_type: If omitted, the default is "Standard_LRS". Values are: Standard_LRS - The data disk should use standard locally redundant storage. Premium_LRS - The data disk should use premium locally redundant storage. Known values are: "Standard_LRS" and "Premium_LRS". :paramtype storage_account_type: str or ~azure.mgmt.batch.models.StorageAccountType """ super().__init__(**kwargs) self.lun = lun self.caching = caching self.disk_size_gb = disk_size_gb self.storage_account_type = storage_account_type class DeleteCertificateError(_serialization.Model): """An error response from the Batch service. All required parameters must be populated in order to send to Azure. :ivar code: An identifier for the error. Codes are invariant and are intended to be consumed programmatically. Required. :vartype code: str :ivar message: A message describing the error, intended to be suitable for display in a user interface. Required. :vartype message: str :ivar target: The target of the particular error. For example, the name of the property in error. :vartype target: str :ivar details: A list of additional details about the error. :vartype details: list[~azure.mgmt.batch.models.DeleteCertificateError] """ _validation = { "code": {"required": True}, "message": {"required": True}, } _attribute_map = { "code": {"key": "code", "type": "str"}, "message": {"key": "message", "type": "str"}, "target": {"key": "target", "type": "str"}, "details": {"key": "details", "type": "[DeleteCertificateError]"}, } def __init__( self, *, code: str, message: str, target: Optional[str] = None, details: Optional[List["_models.DeleteCertificateError"]] = None, **kwargs: Any ) -> None: """ :keyword code: An identifier for the error. Codes are invariant and are intended to be consumed programmatically. Required. :paramtype code: str :keyword message: A message describing the error, intended to be suitable for display in a user interface. Required. :paramtype message: str :keyword target: The target of the particular error. For example, the name of the property in error. :paramtype target: str :keyword details: A list of additional details about the error. :paramtype details: list[~azure.mgmt.batch.models.DeleteCertificateError] """ super().__init__(**kwargs) self.code = code self.message = message self.target = target self.details = details class DeploymentConfiguration(_serialization.Model): """Deployment configuration properties. :ivar cloud_service_configuration: This property and virtualMachineConfiguration are mutually exclusive and one of the properties must be specified. This property cannot be specified if the Batch account was created with its poolAllocationMode property set to 'UserSubscription'. :vartype cloud_service_configuration: ~azure.mgmt.batch.models.CloudServiceConfiguration :ivar virtual_machine_configuration: This property and cloudServiceConfiguration are mutually exclusive and one of the properties must be specified. :vartype virtual_machine_configuration: ~azure.mgmt.batch.models.VirtualMachineConfiguration """ _attribute_map = { "cloud_service_configuration": {"key": "cloudServiceConfiguration", "type": "CloudServiceConfiguration"}, "virtual_machine_configuration": {"key": "virtualMachineConfiguration", "type": "VirtualMachineConfiguration"}, } def __init__( self, *, cloud_service_configuration: Optional["_models.CloudServiceConfiguration"] = None, virtual_machine_configuration: Optional["_models.VirtualMachineConfiguration"] = None, **kwargs: Any ) -> None: """ :keyword cloud_service_configuration: This property and virtualMachineConfiguration are mutually exclusive and one of the properties must be specified. This property cannot be specified if the Batch account was created with its poolAllocationMode property set to 'UserSubscription'. :paramtype cloud_service_configuration: ~azure.mgmt.batch.models.CloudServiceConfiguration :keyword virtual_machine_configuration: This property and cloudServiceConfiguration are mutually exclusive and one of the properties must be specified. :paramtype virtual_machine_configuration: ~azure.mgmt.batch.models.VirtualMachineConfiguration """ super().__init__(**kwargs) self.cloud_service_configuration = cloud_service_configuration self.virtual_machine_configuration = virtual_machine_configuration class DetectorListResult(_serialization.Model): """Values returned by the List operation. :ivar value: The collection of Batch account detectors returned by the listing operation. :vartype value: list[~azure.mgmt.batch.models.DetectorResponse] :ivar next_link: The URL to get the next set of results. :vartype next_link: str """ _attribute_map = { "value": {"key": "value", "type": "[DetectorResponse]"}, "next_link": {"key": "nextLink", "type": "str"}, } def __init__( self, *, value: Optional[List["_models.DetectorResponse"]] = None, next_link: Optional[str] = None, **kwargs: Any ) -> None: """ :keyword value: The collection of Batch account detectors returned by the listing operation. :paramtype value: list[~azure.mgmt.batch.models.DetectorResponse] :keyword next_link: The URL to get the next set of results. :paramtype next_link: str """ super().__init__(**kwargs) self.value = value self.next_link = next_link class DetectorResponse(ProxyResource): """Contains the information for a detector. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: The ID of the resource. :vartype id: str :ivar name: The name of the resource. :vartype name: str :ivar type: The type of the resource. :vartype type: str :ivar etag: The ETag of the resource, used for concurrency statements. :vartype etag: str :ivar value: A base64 encoded string that represents the content of a detector. :vartype value: str """ _validation = { "id": {"readonly": True}, "name": {"readonly": True}, "type": {"readonly": True}, "etag": {"readonly": True}, } _attribute_map = { "id": {"key": "id", "type": "str"}, "name": {"key": "name", "type": "str"}, "type": {"key": "type", "type": "str"}, "etag": {"key": "etag", "type": "str"}, "value": {"key": "properties.value", "type": "str"}, } def __init__(self, *, value: Optional[str] = None, **kwargs: Any) -> None: """ :keyword value: A base64 encoded string that represents the content of a detector. :paramtype value: str """ super().__init__(**kwargs) self.value = value class DiffDiskSettings(_serialization.Model): """Specifies the ephemeral Disk Settings for the operating system disk used by the virtual machine. :ivar placement: This property can be used by user in the request to choose which location the operating system should be in. e.g., cache disk space for Ephemeral OS disk provisioning. For more information on Ephemeral OS disk size requirements, please refer to Ephemeral OS disk size requirements for Windows VMs at https://docs.microsoft.com/en-us/azure/virtual-machines/windows/ephemeral-os-disks#size-requirements and Linux VMs at https://docs.microsoft.com/en-us/azure/virtual-machines/linux/ephemeral-os-disks#size-requirements. Default value is "CacheDisk". :vartype placement: str """ _attribute_map = { "placement": {"key": "placement", "type": "str"}, } def __init__(self, *, placement: Optional[Literal["CacheDisk"]] = None, **kwargs: Any) -> None: """ :keyword placement: This property can be used by user in the request to choose which location the operating system should be in. e.g., cache disk space for Ephemeral OS disk provisioning. For more information on Ephemeral OS disk size requirements, please refer to Ephemeral OS disk size requirements for Windows VMs at https://docs.microsoft.com/en-us/azure/virtual-machines/windows/ephemeral-os-disks#size-requirements and Linux VMs at https://docs.microsoft.com/en-us/azure/virtual-machines/linux/ephemeral-os-disks#size-requirements. Default value is "CacheDisk". :paramtype placement: str """ super().__init__(**kwargs) self.placement = placement class DiskEncryptionConfiguration(_serialization.Model): """The disk encryption configuration applied on compute nodes in the pool. Disk encryption configuration is not supported on Linux pool created with Virtual Machine Image or Shared Image Gallery Image. :ivar targets: On Linux pool, only "TemporaryDisk" is supported; on Windows pool, "OsDisk" and "TemporaryDisk" must be specified. :vartype targets: list[str or ~azure.mgmt.batch.models.DiskEncryptionTarget] """ _attribute_map = { "targets": {"key": "targets", "type": "[str]"}, } def __init__( self, *, targets: Optional[List[Union[str, "_models.DiskEncryptionTarget"]]] = None, **kwargs: Any ) -> None: """ :keyword targets: On Linux pool, only "TemporaryDisk" is supported; on Windows pool, "OsDisk" and "TemporaryDisk" must be specified. :paramtype targets: list[str or ~azure.mgmt.batch.models.DiskEncryptionTarget] """ super().__init__(**kwargs) self.targets = targets class EncryptionProperties(_serialization.Model): """Configures how customer data is encrypted inside the Batch account. By default, accounts are encrypted using a Microsoft managed key. For additional control, a customer-managed key can be used instead. :ivar key_source: Type of the key source. Known values are: "Microsoft.Batch" and "Microsoft.KeyVault". :vartype key_source: str or ~azure.mgmt.batch.models.KeySource :ivar key_vault_properties: Additional details when using Microsoft.KeyVault. :vartype key_vault_properties: ~azure.mgmt.batch.models.KeyVaultProperties """ _attribute_map = { "key_source": {"key": "keySource", "type": "str"}, "key_vault_properties": {"key": "keyVaultProperties", "type": "KeyVaultProperties"}, } def __init__( self, *, key_source: Optional[Union[str, "_models.KeySource"]] = None, key_vault_properties: Optional["_models.KeyVaultProperties"] = None, **kwargs: Any ) -> None: """ :keyword key_source: Type of the key source. Known values are: "Microsoft.Batch" and "Microsoft.KeyVault". :paramtype key_source: str or ~azure.mgmt.batch.models.KeySource :keyword key_vault_properties: Additional details when using Microsoft.KeyVault. :paramtype key_vault_properties: ~azure.mgmt.batch.models.KeyVaultProperties """ super().__init__(**kwargs) self.key_source = key_source self.key_vault_properties = key_vault_properties class EndpointAccessProfile(_serialization.Model): """Network access profile for Batch endpoint. All required parameters must be populated in order to send to Azure. :ivar default_action: Default action for endpoint access. It is only applicable when publicNetworkAccess is enabled. Required. Known values are: "Allow" and "Deny". :vartype default_action: str or ~azure.mgmt.batch.models.EndpointAccessDefaultAction :ivar ip_rules: Array of IP ranges to filter client IP address. :vartype ip_rules: list[~azure.mgmt.batch.models.IPRule] """ _validation = { "default_action": {"required": True}, } _attribute_map = { "default_action": {"key": "defaultAction", "type": "str"}, "ip_rules": {"key": "ipRules", "type": "[IPRule]"}, } def __init__( self, *, default_action: Union[str, "_models.EndpointAccessDefaultAction"], ip_rules: Optional[List["_models.IPRule"]] = None, **kwargs: Any ) -> None: """ :keyword default_action: Default action for endpoint access. It is only applicable when publicNetworkAccess is enabled. Required. Known values are: "Allow" and "Deny". :paramtype default_action: str or ~azure.mgmt.batch.models.EndpointAccessDefaultAction :keyword ip_rules: Array of IP ranges to filter client IP address. :paramtype ip_rules: list[~azure.mgmt.batch.models.IPRule] """ super().__init__(**kwargs) self.default_action = default_action self.ip_rules = ip_rules class EndpointDependency(_serialization.Model): """A domain name and connection details used to access a dependency. Variables are only populated by the server, and will be ignored when sending a request. :ivar domain_name: The domain name of the dependency. Domain names may be fully qualified or may contain a * wildcard. :vartype domain_name: str :ivar description: Human-readable supplemental information about the dependency and when it is applicable. :vartype description: str :ivar endpoint_details: The list of connection details for this endpoint. :vartype endpoint_details: list[~azure.mgmt.batch.models.EndpointDetail] """ _validation = { "domain_name": {"readonly": True}, "description": {"readonly": True}, "endpoint_details": {"readonly": True}, } _attribute_map = { "domain_name": {"key": "domainName", "type": "str"}, "description": {"key": "description", "type": "str"}, "endpoint_details": {"key": "endpointDetails", "type": "[EndpointDetail]"}, } def __init__(self, **kwargs: Any) -> None: """ """ super().__init__(**kwargs) self.domain_name = None self.description = None self.endpoint_details = None class EndpointDetail(_serialization.Model): """Details about the connection between the Batch service and the endpoint. Variables are only populated by the server, and will be ignored when sending a request. :ivar port: The port an endpoint is connected to. :vartype port: int """ _validation = { "port": {"readonly": True}, } _attribute_map = { "port": {"key": "port", "type": "int"}, } def __init__(self, **kwargs: Any) -> None: """ """ super().__init__(**kwargs) self.port = None class EnvironmentSetting(_serialization.Model): """An environment variable to be set on a task process. All required parameters must be populated in order to send to Azure. :ivar name: The name of the environment variable. Required. :vartype name: str :ivar value: The value of the environment variable. :vartype value: str """ _validation = { "name": {"required": True}, } _attribute_map = { "name": {"key": "name", "type": "str"}, "value": {"key": "value", "type": "str"}, } def __init__(self, *, name: str, value: Optional[str] = None, **kwargs: Any) -> None: """ :keyword name: The name of the environment variable. Required. :paramtype name: str :keyword value: The value of the environment variable. :paramtype value: str """ super().__init__(**kwargs) self.name = name self.value = value class FixedScaleSettings(_serialization.Model): """Fixed scale settings for the pool. :ivar resize_timeout: The default value is 15 minutes. Timeout values use ISO 8601 format. For example, use PT10M for 10 minutes. The minimum value is 5 minutes. If you specify a value less than 5 minutes, the Batch service rejects the request with an error; if you are calling the REST API directly, the HTTP status code is 400 (Bad Request). :vartype resize_timeout: ~datetime.timedelta :ivar target_dedicated_nodes: At least one of targetDedicatedNodes, targetLowPriorityNodes must be set. :vartype target_dedicated_nodes: int :ivar target_low_priority_nodes: At least one of targetDedicatedNodes, targetLowPriorityNodes must be set. :vartype target_low_priority_nodes: int :ivar node_deallocation_option: If omitted, the default value is Requeue. Known values are: "Requeue", "Terminate", "TaskCompletion", and "RetainedData". :vartype node_deallocation_option: str or ~azure.mgmt.batch.models.ComputeNodeDeallocationOption """ _attribute_map = { "resize_timeout": {"key": "resizeTimeout", "type": "duration"}, "target_dedicated_nodes": {"key": "targetDedicatedNodes", "type": "int"}, "target_low_priority_nodes": {"key": "targetLowPriorityNodes", "type": "int"}, "node_deallocation_option": {"key": "nodeDeallocationOption", "type": "str"}, } def __init__( self, *, resize_timeout: Optional[datetime.timedelta] = None, target_dedicated_nodes: Optional[int] = None, target_low_priority_nodes: Optional[int] = None, node_deallocation_option: Optional[Union[str, "_models.ComputeNodeDeallocationOption"]] = None, **kwargs: Any ) -> None: """ :keyword resize_timeout: The default value is 15 minutes. Timeout values use ISO 8601 format. For example, use PT10M for 10 minutes. The minimum value is 5 minutes. If you specify a value less than 5 minutes, the Batch service rejects the request with an error; if you are calling the REST API directly, the HTTP status code is 400 (Bad Request). :paramtype resize_timeout: ~datetime.timedelta :keyword target_dedicated_nodes: At least one of targetDedicatedNodes, targetLowPriorityNodes must be set. :paramtype target_dedicated_nodes: int :keyword target_low_priority_nodes: At least one of targetDedicatedNodes, targetLowPriorityNodes must be set. :paramtype target_low_priority_nodes: int :keyword node_deallocation_option: If omitted, the default value is Requeue. Known values are: "Requeue", "Terminate", "TaskCompletion", and "RetainedData". :paramtype node_deallocation_option: str or ~azure.mgmt.batch.models.ComputeNodeDeallocationOption """ super().__init__(**kwargs) self.resize_timeout = resize_timeout self.target_dedicated_nodes = target_dedicated_nodes self.target_low_priority_nodes = target_low_priority_nodes self.node_deallocation_option = node_deallocation_option class ImageReference(_serialization.Model): """A reference to an Azure Virtual Machines Marketplace image or the Azure Image resource of a custom Virtual Machine. To get the list of all imageReferences verified by Azure Batch, see the 'List supported node agent SKUs' operation. :ivar publisher: For example, Canonical or MicrosoftWindowsServer. :vartype publisher: str :ivar offer: For example, UbuntuServer or WindowsServer. :vartype offer: str :ivar sku: For example, 18.04-LTS or 2022-datacenter. :vartype sku: str :ivar version: A value of 'latest' can be specified to select the latest version of an image. If omitted, the default is 'latest'. :vartype version: str :ivar id: This property is mutually exclusive with other properties. The Shared Image Gallery image must have replicas in the same region as the Azure Batch account. For information about the firewall settings for the Batch node agent to communicate with the Batch service see https://docs.microsoft.com/en-us/azure/batch/batch-api-basics#virtual-network-vnet-and-firewall-configuration. :vartype id: str """ _attribute_map = { "publisher": {"key": "publisher", "type": "str"}, "offer": {"key": "offer", "type": "str"}, "sku": {"key": "sku", "type": "str"}, "version": {"key": "version", "type": "str"}, "id": {"key": "id", "type": "str"}, } def __init__( self, *, publisher: Optional[str] = None, offer: Optional[str] = None, sku: Optional[str] = None, version: Optional[str] = None, id: Optional[str] = None, # pylint: disable=redefined-builtin **kwargs: Any ) -> None: """ :keyword publisher: For example, Canonical or MicrosoftWindowsServer. :paramtype publisher: str :keyword offer: For example, UbuntuServer or WindowsServer. :paramtype offer: str :keyword sku: For example, 18.04-LTS or 2022-datacenter. :paramtype sku: str :keyword version: A value of 'latest' can be specified to select the latest version of an image. If omitted, the default is 'latest'. :paramtype version: str :keyword id: This property is mutually exclusive with other properties. The Shared Image Gallery image must have replicas in the same region as the Azure Batch account. For information about the firewall settings for the Batch node agent to communicate with the Batch service see https://docs.microsoft.com/en-us/azure/batch/batch-api-basics#virtual-network-vnet-and-firewall-configuration. :paramtype id: str """ super().__init__(**kwargs) self.publisher = publisher self.offer = offer self.sku = sku self.version = version self.id = id class InboundNatPool(_serialization.Model): """A inbound NAT pool that can be used to address specific ports on compute nodes in a Batch pool externally. All required parameters must be populated in order to send to Azure. :ivar name: The name must be unique within a Batch pool, can contain letters, numbers, underscores, periods, and hyphens. Names must start with a letter or number, must end with a letter, number, or underscore, and cannot exceed 77 characters. If any invalid values are provided the request fails with HTTP status code 400. Required. :vartype name: str :ivar protocol: The protocol of the endpoint. Required. Known values are: "TCP" and "UDP". :vartype protocol: str or ~azure.mgmt.batch.models.InboundEndpointProtocol :ivar backend_port: This must be unique within a Batch pool. Acceptable values are between 1 and 65535 except for 22, 3389, 29876 and 29877 as these are reserved. If any reserved values are provided the request fails with HTTP status code 400. Required. :vartype backend_port: int :ivar frontend_port_range_start: Acceptable values range between 1 and 65534 except ports from 50000 to 55000 which are reserved. All ranges within a pool must be distinct and cannot overlap. If any reserved or overlapping values are provided the request fails with HTTP status code 400. Required. :vartype frontend_port_range_start: int :ivar frontend_port_range_end: Acceptable values range between 1 and 65534 except ports from 50000 to 55000 which are reserved by the Batch service. All ranges within a pool must be distinct and cannot overlap. If any reserved or overlapping values are provided the request fails with HTTP status code 400. Required. :vartype frontend_port_range_end: int :ivar network_security_group_rules: The maximum number of rules that can be specified across all the endpoints on a Batch pool is 25. If no network security group rules are specified, a default rule will be created to allow inbound access to the specified backendPort. If the maximum number of network security group rules is exceeded the request fails with HTTP status code 400. :vartype network_security_group_rules: list[~azure.mgmt.batch.models.NetworkSecurityGroupRule] """ _validation = { "name": {"required": True}, "protocol": {"required": True}, "backend_port": {"required": True}, "frontend_port_range_start": {"required": True}, "frontend_port_range_end": {"required": True}, } _attribute_map = { "name": {"key": "name", "type": "str"}, "protocol": {"key": "protocol", "type": "str"}, "backend_port": {"key": "backendPort", "type": "int"}, "frontend_port_range_start": {"key": "frontendPortRangeStart", "type": "int"}, "frontend_port_range_end": {"key": "frontendPortRangeEnd", "type": "int"}, "network_security_group_rules": {"key": "networkSecurityGroupRules", "type": "[NetworkSecurityGroupRule]"}, } def __init__( self, *, name: str, protocol: Union[str, "_models.InboundEndpointProtocol"], backend_port: int, frontend_port_range_start: int, frontend_port_range_end: int, network_security_group_rules: Optional[List["_models.NetworkSecurityGroupRule"]] = None, **kwargs: Any ) -> None: """ :keyword name: The name must be unique within a Batch pool, can contain letters, numbers, underscores, periods, and hyphens. Names must start with a letter or number, must end with a letter, number, or underscore, and cannot exceed 77 characters. If any invalid values are provided the request fails with HTTP status code 400. Required. :paramtype name: str :keyword protocol: The protocol of the endpoint. Required. Known values are: "TCP" and "UDP". :paramtype protocol: str or ~azure.mgmt.batch.models.InboundEndpointProtocol :keyword backend_port: This must be unique within a Batch pool. Acceptable values are between 1 and 65535 except for 22, 3389, 29876 and 29877 as these are reserved. If any reserved values are provided the request fails with HTTP status code 400. Required. :paramtype backend_port: int :keyword frontend_port_range_start: Acceptable values range between 1 and 65534 except ports from 50000 to 55000 which are reserved. All ranges within a pool must be distinct and cannot overlap. If any reserved or overlapping values are provided the request fails with HTTP status code 400. Required. :paramtype frontend_port_range_start: int :keyword frontend_port_range_end: Acceptable values range between 1 and 65534 except ports from 50000 to 55000 which are reserved by the Batch service. All ranges within a pool must be distinct and cannot overlap. If any reserved or overlapping values are provided the request fails with HTTP status code 400. Required. :paramtype frontend_port_range_end: int :keyword network_security_group_rules: The maximum number of rules that can be specified across all the endpoints on a Batch pool is 25. If no network security group rules are specified, a default rule will be created to allow inbound access to the specified backendPort. If the maximum number of network security group rules is exceeded the request fails with HTTP status code 400. :paramtype network_security_group_rules: list[~azure.mgmt.batch.models.NetworkSecurityGroupRule] """ super().__init__(**kwargs) self.name = name self.protocol = protocol self.backend_port = backend_port self.frontend_port_range_start = frontend_port_range_start self.frontend_port_range_end = frontend_port_range_end self.network_security_group_rules = network_security_group_rules class IPRule(_serialization.Model): """Rule to filter client IP address. Variables are only populated by the server, and will be ignored when sending a request. All required parameters must be populated in order to send to Azure. :ivar action: Action when client IP address is matched. Required. Default value is "Allow". :vartype action: str :ivar value: IPv4 address, or IPv4 address range in CIDR format. Required. :vartype value: str """ _validation = { "action": {"required": True, "constant": True}, "value": {"required": True}, } _attribute_map = { "action": {"key": "action", "type": "str"}, "value": {"key": "value", "type": "str"}, } action = "Allow" def __init__(self, *, value: str, **kwargs: Any) -> None: """ :keyword value: IPv4 address, or IPv4 address range in CIDR format. Required. :paramtype value: str """ super().__init__(**kwargs) self.value = value class KeyVaultProperties(_serialization.Model): """KeyVault configuration when using an encryption KeySource of Microsoft.KeyVault. :ivar key_identifier: Full path to the secret with or without version. Example https://mykeyvault.vault.azure.net/keys/testkey/6e34a81fef704045975661e297a4c053. or https://mykeyvault.vault.azure.net/keys/testkey. To be usable the following prerequisites must be met: The Batch Account has a System Assigned identity The account identity has been granted Key/Get, Key/Unwrap and Key/Wrap permissions The KeyVault has soft-delete and purge protection enabled. :vartype key_identifier: str """ _attribute_map = { "key_identifier": {"key": "keyIdentifier", "type": "str"}, } def __init__(self, *, key_identifier: Optional[str] = None, **kwargs: Any) -> None: """ :keyword key_identifier: Full path to the secret with or without version. Example https://mykeyvault.vault.azure.net/keys/testkey/6e34a81fef704045975661e297a4c053. or https://mykeyvault.vault.azure.net/keys/testkey. To be usable the following prerequisites must be met: The Batch Account has a System Assigned identity The account identity has been granted Key/Get, Key/Unwrap and Key/Wrap permissions The KeyVault has soft-delete and purge protection enabled. :paramtype key_identifier: str """ super().__init__(**kwargs) self.key_identifier = key_identifier class KeyVaultReference(_serialization.Model): """Identifies the Azure key vault associated with a Batch account. All required parameters must be populated in order to send to Azure. :ivar id: The resource ID of the Azure key vault associated with the Batch account. Required. :vartype id: str :ivar url: The URL of the Azure key vault associated with the Batch account. Required. :vartype url: str """ _validation = { "id": {"required": True}, "url": {"required": True}, } _attribute_map = { "id": {"key": "id", "type": "str"}, "url": {"key": "url", "type": "str"}, } def __init__(self, *, id: str, url: str, **kwargs: Any) -> None: # pylint: disable=redefined-builtin """ :keyword id: The resource ID of the Azure key vault associated with the Batch account. Required. :paramtype id: str :keyword url: The URL of the Azure key vault associated with the Batch account. Required. :paramtype url: str """ super().__init__(**kwargs) self.id = id self.url = url class LinuxUserConfiguration(_serialization.Model): """Properties used to create a user account on a Linux node. :ivar uid: The uid and gid properties must be specified together or not at all. If not specified the underlying operating system picks the uid. :vartype uid: int :ivar gid: The uid and gid properties must be specified together or not at all. If not specified the underlying operating system picks the gid. :vartype gid: int :ivar ssh_private_key: The private key must not be password protected. The private key is used to automatically configure asymmetric-key based authentication for SSH between nodes in a Linux pool when the pool's enableInterNodeCommunication property is true (it is ignored if enableInterNodeCommunication is false). It does this by placing the key pair into the user's .ssh directory. If not specified, password-less SSH is not configured between nodes (no modification of the user's .ssh directory is done). :vartype ssh_private_key: str """ _attribute_map = { "uid": {"key": "uid", "type": "int"}, "gid": {"key": "gid", "type": "int"}, "ssh_private_key": {"key": "sshPrivateKey", "type": "str"}, } def __init__( self, *, uid: Optional[int] = None, gid: Optional[int] = None, ssh_private_key: Optional[str] = None, **kwargs: Any ) -> None: """ :keyword uid: The uid and gid properties must be specified together or not at all. If not specified the underlying operating system picks the uid. :paramtype uid: int :keyword gid: The uid and gid properties must be specified together or not at all. If not specified the underlying operating system picks the gid. :paramtype gid: int :keyword ssh_private_key: The private key must not be password protected. The private key is used to automatically configure asymmetric-key based authentication for SSH between nodes in a Linux pool when the pool's enableInterNodeCommunication property is true (it is ignored if enableInterNodeCommunication is false). It does this by placing the key pair into the user's .ssh directory. If not specified, password-less SSH is not configured between nodes (no modification of the user's .ssh directory is done). :paramtype ssh_private_key: str """ super().__init__(**kwargs) self.uid = uid self.gid = gid self.ssh_private_key = ssh_private_key class ListApplicationPackagesResult(_serialization.Model): """The result of performing list application packages. :ivar value: The list of application packages. :vartype value: list[~azure.mgmt.batch.models.ApplicationPackage] :ivar next_link: The URL to get the next set of results. :vartype next_link: str """ _attribute_map = { "value": {"key": "value", "type": "[ApplicationPackage]"}, "next_link": {"key": "nextLink", "type": "str"}, } def __init__( self, *, value: Optional[List["_models.ApplicationPackage"]] = None, next_link: Optional[str] = None, **kwargs: Any ) -> None: """ :keyword value: The list of application packages. :paramtype value: list[~azure.mgmt.batch.models.ApplicationPackage] :keyword next_link: The URL to get the next set of results. :paramtype next_link: str """ super().__init__(**kwargs) self.value = value self.next_link = next_link class ListApplicationsResult(_serialization.Model): """The result of performing list applications. :ivar value: The list of applications. :vartype value: list[~azure.mgmt.batch.models.Application] :ivar next_link: The URL to get the next set of results. :vartype next_link: str """ _attribute_map = { "value": {"key": "value", "type": "[Application]"}, "next_link": {"key": "nextLink", "type": "str"}, } def __init__( self, *, value: Optional[List["_models.Application"]] = None, next_link: Optional[str] = None, **kwargs: Any ) -> None: """ :keyword value: The list of applications. :paramtype value: list[~azure.mgmt.batch.models.Application] :keyword next_link: The URL to get the next set of results. :paramtype next_link: str """ super().__init__(**kwargs) self.value = value self.next_link = next_link class ListCertificatesResult(_serialization.Model): """Values returned by the List operation. :ivar value: The collection of returned certificates. :vartype value: list[~azure.mgmt.batch.models.Certificate] :ivar next_link: The continuation token. :vartype next_link: str """ _attribute_map = { "value": {"key": "value", "type": "[Certificate]"}, "next_link": {"key": "nextLink", "type": "str"}, } def __init__( self, *, value: Optional[List["_models.Certificate"]] = None, next_link: Optional[str] = None, **kwargs: Any ) -> None: """ :keyword value: The collection of returned certificates. :paramtype value: list[~azure.mgmt.batch.models.Certificate] :keyword next_link: The continuation token. :paramtype next_link: str """ super().__init__(**kwargs) self.value = value self.next_link = next_link class ListPoolsResult(_serialization.Model): """Values returned by the List operation. :ivar value: The collection of returned pools. :vartype value: list[~azure.mgmt.batch.models.Pool] :ivar next_link: The continuation token. :vartype next_link: str """ _attribute_map = { "value": {"key": "value", "type": "[Pool]"}, "next_link": {"key": "nextLink", "type": "str"}, } def __init__( self, *, value: Optional[List["_models.Pool"]] = None, next_link: Optional[str] = None, **kwargs: Any ) -> None: """ :keyword value: The collection of returned pools. :paramtype value: list[~azure.mgmt.batch.models.Pool] :keyword next_link: The continuation token. :paramtype next_link: str """ super().__init__(**kwargs) self.value = value self.next_link = next_link class ListPrivateEndpointConnectionsResult(_serialization.Model): """Values returned by the List operation. :ivar value: The collection of returned private endpoint connection. :vartype value: list[~azure.mgmt.batch.models.PrivateEndpointConnection] :ivar next_link: The continuation token. :vartype next_link: str """ _attribute_map = { "value": {"key": "value", "type": "[PrivateEndpointConnection]"}, "next_link": {"key": "nextLink", "type": "str"}, } def __init__( self, *, value: Optional[List["_models.PrivateEndpointConnection"]] = None, next_link: Optional[str] = None, **kwargs: Any ) -> None: """ :keyword value: The collection of returned private endpoint connection. :paramtype value: list[~azure.mgmt.batch.models.PrivateEndpointConnection] :keyword next_link: The continuation token. :paramtype next_link: str """ super().__init__(**kwargs) self.value = value self.next_link = next_link class ListPrivateLinkResourcesResult(_serialization.Model): """Values returned by the List operation. :ivar value: The collection of returned private link resources. :vartype value: list[~azure.mgmt.batch.models.PrivateLinkResource] :ivar next_link: The continuation token. :vartype next_link: str """ _attribute_map = { "value": {"key": "value", "type": "[PrivateLinkResource]"}, "next_link": {"key": "nextLink", "type": "str"}, } def __init__( self, *, value: Optional[List["_models.PrivateLinkResource"]] = None, next_link: Optional[str] = None, **kwargs: Any ) -> None: """ :keyword value: The collection of returned private link resources. :paramtype value: list[~azure.mgmt.batch.models.PrivateLinkResource] :keyword next_link: The continuation token. :paramtype next_link: str """ super().__init__(**kwargs) self.value = value self.next_link = next_link class MetadataItem(_serialization.Model): """The Batch service does not assign any meaning to this metadata; it is solely for the use of user code. All required parameters must be populated in order to send to Azure. :ivar name: The name of the metadata item. Required. :vartype name: str :ivar value: The value of the metadata item. Required. :vartype value: str """ _validation = { "name": {"required": True}, "value": {"required": True}, } _attribute_map = { "name": {"key": "name", "type": "str"}, "value": {"key": "value", "type": "str"}, } def __init__(self, *, name: str, value: str, **kwargs: Any) -> None: """ :keyword name: The name of the metadata item. Required. :paramtype name: str :keyword value: The value of the metadata item. Required. :paramtype value: str """ super().__init__(**kwargs) self.name = name self.value = value class MountConfiguration(_serialization.Model): """The file system to mount on each node. :ivar azure_blob_file_system_configuration: This property is mutually exclusive with all other properties. :vartype azure_blob_file_system_configuration: ~azure.mgmt.batch.models.AzureBlobFileSystemConfiguration :ivar nfs_mount_configuration: This property is mutually exclusive with all other properties. :vartype nfs_mount_configuration: ~azure.mgmt.batch.models.NFSMountConfiguration :ivar cifs_mount_configuration: This property is mutually exclusive with all other properties. :vartype cifs_mount_configuration: ~azure.mgmt.batch.models.CIFSMountConfiguration :ivar azure_file_share_configuration: This property is mutually exclusive with all other properties. :vartype azure_file_share_configuration: ~azure.mgmt.batch.models.AzureFileShareConfiguration """ _attribute_map = { "azure_blob_file_system_configuration": { "key": "azureBlobFileSystemConfiguration", "type": "AzureBlobFileSystemConfiguration", }, "nfs_mount_configuration": {"key": "nfsMountConfiguration", "type": "NFSMountConfiguration"}, "cifs_mount_configuration": {"key": "cifsMountConfiguration", "type": "CIFSMountConfiguration"}, "azure_file_share_configuration": {"key": "azureFileShareConfiguration", "type": "AzureFileShareConfiguration"}, } def __init__( self, *, azure_blob_file_system_configuration: Optional["_models.AzureBlobFileSystemConfiguration"] = None, nfs_mount_configuration: Optional["_models.NFSMountConfiguration"] = None, cifs_mount_configuration: Optional["_models.CIFSMountConfiguration"] = None, azure_file_share_configuration: Optional["_models.AzureFileShareConfiguration"] = None, **kwargs: Any ) -> None: """ :keyword azure_blob_file_system_configuration: This property is mutually exclusive with all other properties. :paramtype azure_blob_file_system_configuration: ~azure.mgmt.batch.models.AzureBlobFileSystemConfiguration :keyword nfs_mount_configuration: This property is mutually exclusive with all other properties. :paramtype nfs_mount_configuration: ~azure.mgmt.batch.models.NFSMountConfiguration :keyword cifs_mount_configuration: This property is mutually exclusive with all other properties. :paramtype cifs_mount_configuration: ~azure.mgmt.batch.models.CIFSMountConfiguration :keyword azure_file_share_configuration: This property is mutually exclusive with all other properties. :paramtype azure_file_share_configuration: ~azure.mgmt.batch.models.AzureFileShareConfiguration """ super().__init__(**kwargs) self.azure_blob_file_system_configuration = azure_blob_file_system_configuration self.nfs_mount_configuration = nfs_mount_configuration self.cifs_mount_configuration = cifs_mount_configuration self.azure_file_share_configuration = azure_file_share_configuration class NetworkConfiguration(_serialization.Model): """The network configuration for a pool. :ivar subnet_id: The virtual network must be in the same region and subscription as the Azure Batch account. The specified subnet should have enough free IP addresses to accommodate the number of nodes in the pool. If the subnet doesn't have enough free IP addresses, the pool will partially allocate compute nodes and a resize error will occur. The 'MicrosoftAzureBatch' service principal must have the 'Classic Virtual Machine Contributor' Role-Based Access Control (RBAC) role for the specified VNet. The specified subnet must allow communication from the Azure Batch service to be able to schedule tasks on the compute nodes. This can be verified by checking if the specified VNet has any associated Network Security Groups (NSG). If communication to the compute nodes in the specified subnet is denied by an NSG, then the Batch service will set the state of the compute nodes to unusable. If the specified VNet has any associated Network Security Groups (NSG), then a few reserved system ports must be enabled for inbound communication. For pools created with a virtual machine configuration, enable ports 29876 and 29877, as well as port 22 for Linux and port 3389 for Windows. For pools created with a cloud service configuration, enable ports 10100, 20100, and 30100. Also enable outbound connections to Azure Storage on port 443. For cloudServiceConfiguration pools, only 'classic' VNETs are supported. For more details see: https://docs.microsoft.com/en-us/azure/batch/batch-api-basics#virtual-network-vnet-and-firewall-configuration. :vartype subnet_id: str :ivar dynamic_vnet_assignment_scope: The scope of dynamic vnet assignment. Known values are: "none" and "job". :vartype dynamic_vnet_assignment_scope: str or ~azure.mgmt.batch.models.DynamicVNetAssignmentScope :ivar endpoint_configuration: Pool endpoint configuration is only supported on pools with the virtualMachineConfiguration property. :vartype endpoint_configuration: ~azure.mgmt.batch.models.PoolEndpointConfiguration :ivar public_ip_address_configuration: This property is only supported on Pools with the virtualMachineConfiguration property. :vartype public_ip_address_configuration: ~azure.mgmt.batch.models.PublicIPAddressConfiguration :ivar enable_accelerated_networking: Accelerated networking enables single root I/O virtualization (SR-IOV) to a VM, which may lead to improved networking performance. For more details, see: https://learn.microsoft.com/azure/virtual-network/accelerated-networking-overview. :vartype enable_accelerated_networking: bool """ _attribute_map = { "subnet_id": {"key": "subnetId", "type": "str"}, "dynamic_vnet_assignment_scope": {"key": "dynamicVnetAssignmentScope", "type": "str"}, "endpoint_configuration": {"key": "endpointConfiguration", "type": "PoolEndpointConfiguration"}, "public_ip_address_configuration": { "key": "publicIPAddressConfiguration", "type": "PublicIPAddressConfiguration", }, "enable_accelerated_networking": {"key": "enableAcceleratedNetworking", "type": "bool"}, } def __init__( self, *, subnet_id: Optional[str] = None, dynamic_vnet_assignment_scope: Optional[Union[str, "_models.DynamicVNetAssignmentScope"]] = None, endpoint_configuration: Optional["_models.PoolEndpointConfiguration"] = None, public_ip_address_configuration: Optional["_models.PublicIPAddressConfiguration"] = None, enable_accelerated_networking: Optional[bool] = None, **kwargs: Any ) -> None: """ :keyword subnet_id: The virtual network must be in the same region and subscription as the Azure Batch account. The specified subnet should have enough free IP addresses to accommodate the number of nodes in the pool. If the subnet doesn't have enough free IP addresses, the pool will partially allocate compute nodes and a resize error will occur. The 'MicrosoftAzureBatch' service principal must have the 'Classic Virtual Machine Contributor' Role-Based Access Control (RBAC) role for the specified VNet. The specified subnet must allow communication from the Azure Batch service to be able to schedule tasks on the compute nodes. This can be verified by checking if the specified VNet has any associated Network Security Groups (NSG). If communication to the compute nodes in the specified subnet is denied by an NSG, then the Batch service will set the state of the compute nodes to unusable. If the specified VNet has any associated Network Security Groups (NSG), then a few reserved system ports must be enabled for inbound communication. For pools created with a virtual machine configuration, enable ports 29876 and 29877, as well as port 22 for Linux and port 3389 for Windows. For pools created with a cloud service configuration, enable ports 10100, 20100, and 30100. Also enable outbound connections to Azure Storage on port 443. For cloudServiceConfiguration pools, only 'classic' VNETs are supported. For more details see: https://docs.microsoft.com/en-us/azure/batch/batch-api-basics#virtual-network-vnet-and-firewall-configuration. :paramtype subnet_id: str :keyword dynamic_vnet_assignment_scope: The scope of dynamic vnet assignment. Known values are: "none" and "job". :paramtype dynamic_vnet_assignment_scope: str or ~azure.mgmt.batch.models.DynamicVNetAssignmentScope :keyword endpoint_configuration: Pool endpoint configuration is only supported on pools with the virtualMachineConfiguration property. :paramtype endpoint_configuration: ~azure.mgmt.batch.models.PoolEndpointConfiguration :keyword public_ip_address_configuration: This property is only supported on Pools with the virtualMachineConfiguration property. :paramtype public_ip_address_configuration: ~azure.mgmt.batch.models.PublicIPAddressConfiguration :keyword enable_accelerated_networking: Accelerated networking enables single root I/O virtualization (SR-IOV) to a VM, which may lead to improved networking performance. For more details, see: https://learn.microsoft.com/azure/virtual-network/accelerated-networking-overview. :paramtype enable_accelerated_networking: bool """ super().__init__(**kwargs) self.subnet_id = subnet_id self.dynamic_vnet_assignment_scope = dynamic_vnet_assignment_scope self.endpoint_configuration = endpoint_configuration self.public_ip_address_configuration = public_ip_address_configuration self.enable_accelerated_networking = enable_accelerated_networking class NetworkProfile(_serialization.Model): """Network profile for Batch account, which contains network rule settings for each endpoint. :ivar account_access: Network access profile for batchAccount endpoint (Batch account data plane API). :vartype account_access: ~azure.mgmt.batch.models.EndpointAccessProfile :ivar node_management_access: Network access profile for nodeManagement endpoint (Batch service managing compute nodes for Batch pools). :vartype node_management_access: ~azure.mgmt.batch.models.EndpointAccessProfile """ _attribute_map = { "account_access": {"key": "accountAccess", "type": "EndpointAccessProfile"}, "node_management_access": {"key": "nodeManagementAccess", "type": "EndpointAccessProfile"}, } def __init__( self, *, account_access: Optional["_models.EndpointAccessProfile"] = None, node_management_access: Optional["_models.EndpointAccessProfile"] = None, **kwargs: Any ) -> None: """ :keyword account_access: Network access profile for batchAccount endpoint (Batch account data plane API). :paramtype account_access: ~azure.mgmt.batch.models.EndpointAccessProfile :keyword node_management_access: Network access profile for nodeManagement endpoint (Batch service managing compute nodes for Batch pools). :paramtype node_management_access: ~azure.mgmt.batch.models.EndpointAccessProfile """ super().__init__(**kwargs) self.account_access = account_access self.node_management_access = node_management_access class NetworkSecurityGroupRule(_serialization.Model): """A network security group rule to apply to an inbound endpoint. All required parameters must be populated in order to send to Azure. :ivar priority: Priorities within a pool must be unique and are evaluated in order of priority. The lower the number the higher the priority. For example, rules could be specified with order numbers of 150, 250, and 350. The rule with the order number of 150 takes precedence over the rule that has an order of 250. Allowed priorities are 150 to 4096. If any reserved or duplicate values are provided the request fails with HTTP status code 400. Required. :vartype priority: int :ivar access: The action that should be taken for a specified IP address, subnet range or tag. Required. Known values are: "Allow" and "Deny". :vartype access: str or ~azure.mgmt.batch.models.NetworkSecurityGroupRuleAccess :ivar source_address_prefix: Valid values are a single IP address (i.e. 10.10.10.10), IP subnet (i.e. 192.168.1.0/24), default tag, or * (for all addresses). If any other values are provided the request fails with HTTP status code 400. Required. :vartype source_address_prefix: str :ivar source_port_ranges: Valid values are '\ *' (for all ports 0 - 65535) or arrays of ports or port ranges (i.e. 100-200). The ports should in the range of 0 to 65535 and the port ranges or ports can't overlap. If any other values are provided the request fails with HTTP status code 400. Default value will be *. :vartype source_port_ranges: list[str] """ _validation = { "priority": {"required": True}, "access": {"required": True}, "source_address_prefix": {"required": True}, } _attribute_map = { "priority": {"key": "priority", "type": "int"}, "access": {"key": "access", "type": "str"}, "source_address_prefix": {"key": "sourceAddressPrefix", "type": "str"}, "source_port_ranges": {"key": "sourcePortRanges", "type": "[str]"}, } def __init__( self, *, priority: int, access: Union[str, "_models.NetworkSecurityGroupRuleAccess"], source_address_prefix: str, source_port_ranges: Optional[List[str]] = None, **kwargs: Any ) -> None: """ :keyword priority: Priorities within a pool must be unique and are evaluated in order of priority. The lower the number the higher the priority. For example, rules could be specified with order numbers of 150, 250, and 350. The rule with the order number of 150 takes precedence over the rule that has an order of 250. Allowed priorities are 150 to 4096. If any reserved or duplicate values are provided the request fails with HTTP status code 400. Required. :paramtype priority: int :keyword access: The action that should be taken for a specified IP address, subnet range or tag. Required. Known values are: "Allow" and "Deny". :paramtype access: str or ~azure.mgmt.batch.models.NetworkSecurityGroupRuleAccess :keyword source_address_prefix: Valid values are a single IP address (i.e. 10.10.10.10), IP subnet (i.e. 192.168.1.0/24), default tag, or * (for all addresses). If any other values are provided the request fails with HTTP status code 400. Required. :paramtype source_address_prefix: str :keyword source_port_ranges: Valid values are '\ *' (for all ports 0 - 65535) or arrays of ports or port ranges (i.e. 100-200). The ports should in the range of 0 to 65535 and the port ranges or ports can't overlap. If any other values are provided the request fails with HTTP status code 400. Default value will be *. :paramtype source_port_ranges: list[str] """ super().__init__(**kwargs) self.priority = priority self.access = access self.source_address_prefix = source_address_prefix self.source_port_ranges = source_port_ranges class NFSMountConfiguration(_serialization.Model): """Information used to connect to an NFS file system. All required parameters must be populated in order to send to Azure. :ivar source: The URI of the file system to mount. Required. :vartype source: str :ivar relative_mount_path: All file systems are mounted relative to the Batch mounts directory, accessible via the AZ_BATCH_NODE_MOUNTS_DIR environment variable. Required. :vartype relative_mount_path: str :ivar mount_options: These are 'net use' options in Windows and 'mount' options in Linux. :vartype mount_options: str """ _validation = { "source": {"required": True}, "relative_mount_path": {"required": True}, } _attribute_map = { "source": {"key": "source", "type": "str"}, "relative_mount_path": {"key": "relativeMountPath", "type": "str"}, "mount_options": {"key": "mountOptions", "type": "str"}, } def __init__( self, *, source: str, relative_mount_path: str, mount_options: Optional[str] = None, **kwargs: Any ) -> None: """ :keyword source: The URI of the file system to mount. Required. :paramtype source: str :keyword relative_mount_path: All file systems are mounted relative to the Batch mounts directory, accessible via the AZ_BATCH_NODE_MOUNTS_DIR environment variable. Required. :paramtype relative_mount_path: str :keyword mount_options: These are 'net use' options in Windows and 'mount' options in Linux. :paramtype mount_options: str """ super().__init__(**kwargs) self.source = source self.relative_mount_path = relative_mount_path self.mount_options = mount_options class NodePlacementConfiguration(_serialization.Model): """Allocation configuration used by Batch Service to provision the nodes. :ivar policy: Allocation policy used by Batch Service to provision the nodes. If not specified, Batch will use the regional policy. Known values are: "Regional" and "Zonal". :vartype policy: str or ~azure.mgmt.batch.models.NodePlacementPolicyType """ _attribute_map = { "policy": {"key": "policy", "type": "str"}, } def __init__( self, *, policy: Optional[Union[str, "_models.NodePlacementPolicyType"]] = None, **kwargs: Any ) -> None: """ :keyword policy: Allocation policy used by Batch Service to provision the nodes. If not specified, Batch will use the regional policy. Known values are: "Regional" and "Zonal". :paramtype policy: str or ~azure.mgmt.batch.models.NodePlacementPolicyType """ super().__init__(**kwargs) self.policy = policy class Operation(_serialization.Model): """A REST API operation. :ivar name: This is of the format {provider}/{resource}/{operation}. :vartype name: str :ivar is_data_action: Indicates whether the operation is a data action. :vartype is_data_action: bool :ivar display: The object that describes the operation. :vartype display: ~azure.mgmt.batch.models.OperationDisplay :ivar origin: The intended executor of the operation. :vartype origin: str :ivar properties: Properties of the operation. :vartype properties: JSON """ _attribute_map = { "name": {"key": "name", "type": "str"}, "is_data_action": {"key": "isDataAction", "type": "bool"}, "display": {"key": "display", "type": "OperationDisplay"}, "origin": {"key": "origin", "type": "str"}, "properties": {"key": "properties", "type": "object"}, } def __init__( self, *, name: Optional[str] = None, is_data_action: Optional[bool] = None, display: Optional["_models.OperationDisplay"] = None, origin: Optional[str] = None, properties: Optional[JSON] = None, **kwargs: Any ) -> None: """ :keyword name: This is of the format {provider}/{resource}/{operation}. :paramtype name: str :keyword is_data_action: Indicates whether the operation is a data action. :paramtype is_data_action: bool :keyword display: The object that describes the operation. :paramtype display: ~azure.mgmt.batch.models.OperationDisplay :keyword origin: The intended executor of the operation. :paramtype origin: str :keyword properties: Properties of the operation. :paramtype properties: JSON """ super().__init__(**kwargs) self.name = name self.is_data_action = is_data_action self.display = display self.origin = origin self.properties = properties class OperationDisplay(_serialization.Model): """The object that describes the operation. :ivar provider: Friendly name of the resource provider. :vartype provider: str :ivar operation: For example: read, write, delete, or listKeys/action. :vartype operation: str :ivar resource: The resource type on which the operation is performed. :vartype resource: str :ivar description: The friendly name of the operation. :vartype description: str """ _attribute_map = { "provider": {"key": "provider", "type": "str"}, "operation": {"key": "operation", "type": "str"}, "resource": {"key": "resource", "type": "str"}, "description": {"key": "description", "type": "str"}, } def __init__( self, *, provider: Optional[str] = None, operation: Optional[str] = None, resource: Optional[str] = None, description: Optional[str] = None, **kwargs: Any ) -> None: """ :keyword provider: Friendly name of the resource provider. :paramtype provider: str :keyword operation: For example: read, write, delete, or listKeys/action. :paramtype operation: str :keyword resource: The resource type on which the operation is performed. :paramtype resource: str :keyword description: The friendly name of the operation. :paramtype description: str """ super().__init__(**kwargs) self.provider = provider self.operation = operation self.resource = resource self.description = description class OperationListResult(_serialization.Model): """Result of the request to list REST API operations. It contains a list of operations and a URL nextLink to get the next set of results. :ivar value: The list of operations supported by the resource provider. :vartype value: list[~azure.mgmt.batch.models.Operation] :ivar next_link: The URL to get the next set of operation list results if there are any. :vartype next_link: str """ _attribute_map = { "value": {"key": "value", "type": "[Operation]"}, "next_link": {"key": "nextLink", "type": "str"}, } def __init__( self, *, value: Optional[List["_models.Operation"]] = None, next_link: Optional[str] = None, **kwargs: Any ) -> None: """ :keyword value: The list of operations supported by the resource provider. :paramtype value: list[~azure.mgmt.batch.models.Operation] :keyword next_link: The URL to get the next set of operation list results if there are any. :paramtype next_link: str """ super().__init__(**kwargs) self.value = value self.next_link = next_link class OSDisk(_serialization.Model): """Settings for the operating system disk of the virtual machine. :ivar ephemeral_os_disk_settings: Specifies the ephemeral Disk Settings for the operating system disk used by the virtual machine. :vartype ephemeral_os_disk_settings: ~azure.mgmt.batch.models.DiffDiskSettings """ _attribute_map = { "ephemeral_os_disk_settings": {"key": "ephemeralOSDiskSettings", "type": "DiffDiskSettings"}, } def __init__( self, *, ephemeral_os_disk_settings: Optional["_models.DiffDiskSettings"] = None, **kwargs: Any ) -> None: """ :keyword ephemeral_os_disk_settings: Specifies the ephemeral Disk Settings for the operating system disk used by the virtual machine. :paramtype ephemeral_os_disk_settings: ~azure.mgmt.batch.models.DiffDiskSettings """ super().__init__(**kwargs) self.ephemeral_os_disk_settings = ephemeral_os_disk_settings class OutboundEnvironmentEndpoint(_serialization.Model): """A collection of related endpoints from the same service for which the Batch service requires outbound access. Variables are only populated by the server, and will be ignored when sending a request. :ivar category: The type of service that the Batch service connects to. :vartype category: str :ivar endpoints: The endpoints for this service to which the Batch service makes outbound calls. :vartype endpoints: list[~azure.mgmt.batch.models.EndpointDependency] """ _validation = { "category": {"readonly": True}, "endpoints": {"readonly": True}, } _attribute_map = { "category": {"key": "category", "type": "str"}, "endpoints": {"key": "endpoints", "type": "[EndpointDependency]"}, } def __init__(self, **kwargs: Any) -> None: """ """ super().__init__(**kwargs) self.category = None self.endpoints = None class OutboundEnvironmentEndpointCollection(_serialization.Model): """Values returned by the List operation. Variables are only populated by the server, and will be ignored when sending a request. :ivar value: The collection of outbound network dependency endpoints returned by the listing operation. :vartype value: list[~azure.mgmt.batch.models.OutboundEnvironmentEndpoint] :ivar next_link: The continuation token. :vartype next_link: str """ _validation = { "value": {"readonly": True}, } _attribute_map = { "value": {"key": "value", "type": "[OutboundEnvironmentEndpoint]"}, "next_link": {"key": "nextLink", "type": "str"}, } def __init__(self, *, next_link: Optional[str] = None, **kwargs: Any) -> None: """ :keyword next_link: The continuation token. :paramtype next_link: str """ super().__init__(**kwargs) self.value = None self.next_link = next_link class Pool(ProxyResource): # pylint: disable=too-many-instance-attributes """Contains information about a pool. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: The ID of the resource. :vartype id: str :ivar name: The name of the resource. :vartype name: str :ivar type: The type of the resource. :vartype type: str :ivar etag: The ETag of the resource, used for concurrency statements. :vartype etag: str :ivar identity: The type of identity used for the Batch Pool. :vartype identity: ~azure.mgmt.batch.models.BatchPoolIdentity :ivar display_name: The display name need not be unique and can contain any Unicode characters up to a maximum length of 1024. :vartype display_name: str :ivar last_modified: This is the last time at which the pool level data, such as the targetDedicatedNodes or autoScaleSettings, changed. It does not factor in node-level changes such as a compute node changing state. :vartype last_modified: ~datetime.datetime :ivar creation_time: The creation time of the pool. :vartype creation_time: ~datetime.datetime :ivar provisioning_state: The current state of the pool. Known values are: "Succeeded" and "Deleting". :vartype provisioning_state: str or ~azure.mgmt.batch.models.PoolProvisioningState :ivar provisioning_state_transition_time: The time at which the pool entered its current state. :vartype provisioning_state_transition_time: ~datetime.datetime :ivar allocation_state: Whether the pool is resizing. Known values are: "Steady", "Resizing", and "Stopping". :vartype allocation_state: str or ~azure.mgmt.batch.models.AllocationState :ivar allocation_state_transition_time: The time at which the pool entered its current allocation state. :vartype allocation_state_transition_time: ~datetime.datetime :ivar vm_size: For information about available sizes of virtual machines for Cloud Services pools (pools created with cloudServiceConfiguration), see Sizes for Cloud Services (https://azure.microsoft.com/documentation/articles/cloud-services-sizes-specs/). Batch supports all Cloud Services VM sizes except ExtraSmall. For information about available VM sizes for pools using images from the Virtual Machines Marketplace (pools created with virtualMachineConfiguration) see Sizes for Virtual Machines (Linux) (https://azure.microsoft.com/documentation/articles/virtual-machines-linux-sizes/) or Sizes for Virtual Machines (Windows) (https://azure.microsoft.com/documentation/articles/virtual-machines-windows-sizes/). Batch supports all Azure VM sizes except STANDARD_A0 and those with premium storage (STANDARD_GS, STANDARD_DS, and STANDARD_DSV2 series). :vartype vm_size: str :ivar deployment_configuration: Using CloudServiceConfiguration specifies that the nodes should be creating using Azure Cloud Services (PaaS), while VirtualMachineConfiguration uses Azure Virtual Machines (IaaS). :vartype deployment_configuration: ~azure.mgmt.batch.models.DeploymentConfiguration :ivar current_dedicated_nodes: The number of dedicated compute nodes currently in the pool. :vartype current_dedicated_nodes: int :ivar current_low_priority_nodes: The number of Spot/low-priority compute nodes currently in the pool. :vartype current_low_priority_nodes: int :ivar scale_settings: Defines the desired size of the pool. This can either be 'fixedScale' where the requested targetDedicatedNodes is specified, or 'autoScale' which defines a formula which is periodically reevaluated. If this property is not specified, the pool will have a fixed scale with 0 targetDedicatedNodes. :vartype scale_settings: ~azure.mgmt.batch.models.ScaleSettings :ivar auto_scale_run: This property is set only if the pool automatically scales, i.e. autoScaleSettings are used. :vartype auto_scale_run: ~azure.mgmt.batch.models.AutoScaleRun :ivar inter_node_communication: This imposes restrictions on which nodes can be assigned to the pool. Enabling this value can reduce the chance of the requested number of nodes to be allocated in the pool. If not specified, this value defaults to 'Disabled'. Known values are: "Enabled" and "Disabled". :vartype inter_node_communication: str or ~azure.mgmt.batch.models.InterNodeCommunicationState :ivar network_configuration: The network configuration for a pool. :vartype network_configuration: ~azure.mgmt.batch.models.NetworkConfiguration :ivar task_slots_per_node: The default value is 1. The maximum value is the smaller of 4 times the number of cores of the vmSize of the pool or 256. :vartype task_slots_per_node: int :ivar task_scheduling_policy: If not specified, the default is spread. :vartype task_scheduling_policy: ~azure.mgmt.batch.models.TaskSchedulingPolicy :ivar user_accounts: The list of user accounts to be created on each node in the pool. :vartype user_accounts: list[~azure.mgmt.batch.models.UserAccount] :ivar metadata: The Batch service does not assign any meaning to metadata; it is solely for the use of user code. :vartype metadata: list[~azure.mgmt.batch.models.MetadataItem] :ivar start_task: In an PATCH (update) operation, this property can be set to an empty object to remove the start task from the pool. :vartype start_task: ~azure.mgmt.batch.models.StartTask :ivar certificates: For Windows compute nodes, the Batch service installs the certificates to the specified certificate store and location. For Linux compute nodes, the certificates are stored in a directory inside the task working directory and an environment variable AZ_BATCH_CERTIFICATES_DIR is supplied to the task to query for this location. For certificates with visibility of 'remoteUser', a 'certs' directory is created in the user's home directory (e.g., /home/{user-name}/certs) and certificates are placed in that directory. Warning: This property is deprecated and will be removed after February, 2024. Please use the `Azure KeyVault Extension <https://learn.microsoft.com/azure/batch/batch-certificate-migration-guide>`_ instead. :vartype certificates: list[~azure.mgmt.batch.models.CertificateReference] :ivar application_packages: Changes to application package references affect all new compute nodes joining the pool, but do not affect compute nodes that are already in the pool until they are rebooted or reimaged. There is a maximum of 10 application package references on any given pool. :vartype application_packages: list[~azure.mgmt.batch.models.ApplicationPackageReference] :ivar application_licenses: The list of application licenses must be a subset of available Batch service application licenses. If a license is requested which is not supported, pool creation will fail. :vartype application_licenses: list[str] :ivar resize_operation_status: Describes either the current operation (if the pool AllocationState is Resizing) or the previously completed operation (if the AllocationState is Steady). :vartype resize_operation_status: ~azure.mgmt.batch.models.ResizeOperationStatus :ivar mount_configuration: This supports Azure Files, NFS, CIFS/SMB, and Blobfuse. :vartype mount_configuration: list[~azure.mgmt.batch.models.MountConfiguration] :ivar target_node_communication_mode: If omitted, the default value is Default. Known values are: "Default", "Classic", and "Simplified". :vartype target_node_communication_mode: str or ~azure.mgmt.batch.models.NodeCommunicationMode :ivar current_node_communication_mode: Determines how a pool communicates with the Batch service. Known values are: "Default", "Classic", and "Simplified". :vartype current_node_communication_mode: str or ~azure.mgmt.batch.models.NodeCommunicationMode """ _validation = { "id": {"readonly": True}, "name": {"readonly": True}, "type": {"readonly": True}, "etag": {"readonly": True}, "last_modified": {"readonly": True}, "creation_time": {"readonly": True}, "provisioning_state": {"readonly": True}, "provisioning_state_transition_time": {"readonly": True}, "allocation_state": {"readonly": True}, "allocation_state_transition_time": {"readonly": True}, "current_dedicated_nodes": {"readonly": True}, "current_low_priority_nodes": {"readonly": True}, "auto_scale_run": {"readonly": True}, "resize_operation_status": {"readonly": True}, "current_node_communication_mode": {"readonly": True}, } _attribute_map = { "id": {"key": "id", "type": "str"}, "name": {"key": "name", "type": "str"}, "type": {"key": "type", "type": "str"}, "etag": {"key": "etag", "type": "str"}, "identity": {"key": "identity", "type": "BatchPoolIdentity"}, "display_name": {"key": "properties.displayName", "type": "str"}, "last_modified": {"key": "properties.lastModified", "type": "iso-8601"}, "creation_time": {"key": "properties.creationTime", "type": "iso-8601"}, "provisioning_state": {"key": "properties.provisioningState", "type": "str"}, "provisioning_state_transition_time": {"key": "properties.provisioningStateTransitionTime", "type": "iso-8601"}, "allocation_state": {"key": "properties.allocationState", "type": "str"}, "allocation_state_transition_time": {"key": "properties.allocationStateTransitionTime", "type": "iso-8601"}, "vm_size": {"key": "properties.vmSize", "type": "str"}, "deployment_configuration": {"key": "properties.deploymentConfiguration", "type": "DeploymentConfiguration"}, "current_dedicated_nodes": {"key": "properties.currentDedicatedNodes", "type": "int"}, "current_low_priority_nodes": {"key": "properties.currentLowPriorityNodes", "type": "int"}, "scale_settings": {"key": "properties.scaleSettings", "type": "ScaleSettings"}, "auto_scale_run": {"key": "properties.autoScaleRun", "type": "AutoScaleRun"}, "inter_node_communication": {"key": "properties.interNodeCommunication", "type": "str"}, "network_configuration": {"key": "properties.networkConfiguration", "type": "NetworkConfiguration"}, "task_slots_per_node": {"key": "properties.taskSlotsPerNode", "type": "int"}, "task_scheduling_policy": {"key": "properties.taskSchedulingPolicy", "type": "TaskSchedulingPolicy"}, "user_accounts": {"key": "properties.userAccounts", "type": "[UserAccount]"}, "metadata": {"key": "properties.metadata", "type": "[MetadataItem]"}, "start_task": {"key": "properties.startTask", "type": "StartTask"}, "certificates": {"key": "properties.certificates", "type": "[CertificateReference]"}, "application_packages": {"key": "properties.applicationPackages", "type": "[ApplicationPackageReference]"}, "application_licenses": {"key": "properties.applicationLicenses", "type": "[str]"}, "resize_operation_status": {"key": "properties.resizeOperationStatus", "type": "ResizeOperationStatus"}, "mount_configuration": {"key": "properties.mountConfiguration", "type": "[MountConfiguration]"}, "target_node_communication_mode": {"key": "properties.targetNodeCommunicationMode", "type": "str"}, "current_node_communication_mode": {"key": "properties.currentNodeCommunicationMode", "type": "str"}, } def __init__( # pylint: disable=too-many-locals self, *, identity: Optional["_models.BatchPoolIdentity"] = None, display_name: Optional[str] = None, vm_size: Optional[str] = None, deployment_configuration: Optional["_models.DeploymentConfiguration"] = None, scale_settings: Optional["_models.ScaleSettings"] = None, inter_node_communication: Optional[Union[str, "_models.InterNodeCommunicationState"]] = None, network_configuration: Optional["_models.NetworkConfiguration"] = None, task_slots_per_node: Optional[int] = None, task_scheduling_policy: Optional["_models.TaskSchedulingPolicy"] = None, user_accounts: Optional[List["_models.UserAccount"]] = None, metadata: Optional[List["_models.MetadataItem"]] = None, start_task: Optional["_models.StartTask"] = None, certificates: Optional[List["_models.CertificateReference"]] = None, application_packages: Optional[List["_models.ApplicationPackageReference"]] = None, application_licenses: Optional[List[str]] = None, mount_configuration: Optional[List["_models.MountConfiguration"]] = None, target_node_communication_mode: Optional[Union[str, "_models.NodeCommunicationMode"]] = None, **kwargs: Any ) -> None: """ :keyword identity: The type of identity used for the Batch Pool. :paramtype identity: ~azure.mgmt.batch.models.BatchPoolIdentity :keyword display_name: The display name need not be unique and can contain any Unicode characters up to a maximum length of 1024. :paramtype display_name: str :keyword vm_size: For information about available sizes of virtual machines for Cloud Services pools (pools created with cloudServiceConfiguration), see Sizes for Cloud Services (https://azure.microsoft.com/documentation/articles/cloud-services-sizes-specs/). Batch supports all Cloud Services VM sizes except ExtraSmall. For information about available VM sizes for pools using images from the Virtual Machines Marketplace (pools created with virtualMachineConfiguration) see Sizes for Virtual Machines (Linux) (https://azure.microsoft.com/documentation/articles/virtual-machines-linux-sizes/) or Sizes for Virtual Machines (Windows) (https://azure.microsoft.com/documentation/articles/virtual-machines-windows-sizes/). Batch supports all Azure VM sizes except STANDARD_A0 and those with premium storage (STANDARD_GS, STANDARD_DS, and STANDARD_DSV2 series). :paramtype vm_size: str :keyword deployment_configuration: Using CloudServiceConfiguration specifies that the nodes should be creating using Azure Cloud Services (PaaS), while VirtualMachineConfiguration uses Azure Virtual Machines (IaaS). :paramtype deployment_configuration: ~azure.mgmt.batch.models.DeploymentConfiguration :keyword scale_settings: Defines the desired size of the pool. This can either be 'fixedScale' where the requested targetDedicatedNodes is specified, or 'autoScale' which defines a formula which is periodically reevaluated. If this property is not specified, the pool will have a fixed scale with 0 targetDedicatedNodes. :paramtype scale_settings: ~azure.mgmt.batch.models.ScaleSettings :keyword inter_node_communication: This imposes restrictions on which nodes can be assigned to the pool. Enabling this value can reduce the chance of the requested number of nodes to be allocated in the pool. If not specified, this value defaults to 'Disabled'. Known values are: "Enabled" and "Disabled". :paramtype inter_node_communication: str or ~azure.mgmt.batch.models.InterNodeCommunicationState :keyword network_configuration: The network configuration for a pool. :paramtype network_configuration: ~azure.mgmt.batch.models.NetworkConfiguration :keyword task_slots_per_node: The default value is 1. The maximum value is the smaller of 4 times the number of cores of the vmSize of the pool or 256. :paramtype task_slots_per_node: int :keyword task_scheduling_policy: If not specified, the default is spread. :paramtype task_scheduling_policy: ~azure.mgmt.batch.models.TaskSchedulingPolicy :keyword user_accounts: The list of user accounts to be created on each node in the pool. :paramtype user_accounts: list[~azure.mgmt.batch.models.UserAccount] :keyword metadata: The Batch service does not assign any meaning to metadata; it is solely for the use of user code. :paramtype metadata: list[~azure.mgmt.batch.models.MetadataItem] :keyword start_task: In an PATCH (update) operation, this property can be set to an empty object to remove the start task from the pool. :paramtype start_task: ~azure.mgmt.batch.models.StartTask :keyword certificates: For Windows compute nodes, the Batch service installs the certificates to the specified certificate store and location. For Linux compute nodes, the certificates are stored in a directory inside the task working directory and an environment variable AZ_BATCH_CERTIFICATES_DIR is supplied to the task to query for this location. For certificates with visibility of 'remoteUser', a 'certs' directory is created in the user's home directory (e.g., /home/{user-name}/certs) and certificates are placed in that directory. Warning: This property is deprecated and will be removed after February, 2024. Please use the `Azure KeyVault Extension <https://learn.microsoft.com/azure/batch/batch-certificate-migration-guide>`_ instead. :paramtype certificates: list[~azure.mgmt.batch.models.CertificateReference] :keyword application_packages: Changes to application package references affect all new compute nodes joining the pool, but do not affect compute nodes that are already in the pool until they are rebooted or reimaged. There is a maximum of 10 application package references on any given pool. :paramtype application_packages: list[~azure.mgmt.batch.models.ApplicationPackageReference] :keyword application_licenses: The list of application licenses must be a subset of available Batch service application licenses. If a license is requested which is not supported, pool creation will fail. :paramtype application_licenses: list[str] :keyword mount_configuration: This supports Azure Files, NFS, CIFS/SMB, and Blobfuse. :paramtype mount_configuration: list[~azure.mgmt.batch.models.MountConfiguration] :keyword target_node_communication_mode: If omitted, the default value is Default. Known values are: "Default", "Classic", and "Simplified". :paramtype target_node_communication_mode: str or ~azure.mgmt.batch.models.NodeCommunicationMode """ super().__init__(**kwargs) self.identity = identity self.display_name = display_name self.last_modified = None self.creation_time = None self.provisioning_state = None self.provisioning_state_transition_time = None self.allocation_state = None self.allocation_state_transition_time = None self.vm_size = vm_size self.deployment_configuration = deployment_configuration self.current_dedicated_nodes = None self.current_low_priority_nodes = None self.scale_settings = scale_settings self.auto_scale_run = None self.inter_node_communication = inter_node_communication self.network_configuration = network_configuration self.task_slots_per_node = task_slots_per_node self.task_scheduling_policy = task_scheduling_policy self.user_accounts = user_accounts self.metadata = metadata self.start_task = start_task self.certificates = certificates self.application_packages = application_packages self.application_licenses = application_licenses self.resize_operation_status = None self.mount_configuration = mount_configuration self.target_node_communication_mode = target_node_communication_mode self.current_node_communication_mode = None class PoolEndpointConfiguration(_serialization.Model): """The endpoint configuration for a pool. All required parameters must be populated in order to send to Azure. :ivar inbound_nat_pools: The maximum number of inbound NAT pools per Batch pool is 5. If the maximum number of inbound NAT pools is exceeded the request fails with HTTP status code 400. This cannot be specified if the IPAddressProvisioningType is NoPublicIPAddresses. Required. :vartype inbound_nat_pools: list[~azure.mgmt.batch.models.InboundNatPool] """ _validation = { "inbound_nat_pools": {"required": True}, } _attribute_map = { "inbound_nat_pools": {"key": "inboundNatPools", "type": "[InboundNatPool]"}, } def __init__(self, *, inbound_nat_pools: List["_models.InboundNatPool"], **kwargs: Any) -> None: """ :keyword inbound_nat_pools: The maximum number of inbound NAT pools per Batch pool is 5. If the maximum number of inbound NAT pools is exceeded the request fails with HTTP status code 400. This cannot be specified if the IPAddressProvisioningType is NoPublicIPAddresses. Required. :paramtype inbound_nat_pools: list[~azure.mgmt.batch.models.InboundNatPool] """ super().__init__(**kwargs) self.inbound_nat_pools = inbound_nat_pools class PrivateEndpoint(_serialization.Model): """The private endpoint of the private endpoint connection. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: The ARM resource identifier of the private endpoint. This is of the form /subscriptions/{subscription}/resourceGroups/{group}/providers/Microsoft.Network/privateEndpoints/{privateEndpoint}. :vartype id: str """ _validation = { "id": {"readonly": True}, } _attribute_map = { "id": {"key": "id", "type": "str"}, } def __init__(self, **kwargs: Any) -> None: """ """ super().__init__(**kwargs) self.id = None class PrivateEndpointConnection(ProxyResource): """Contains information about a private link resource. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: The ID of the resource. :vartype id: str :ivar name: The name of the resource. :vartype name: str :ivar type: The type of the resource. :vartype type: str :ivar etag: The ETag of the resource, used for concurrency statements. :vartype etag: str :ivar provisioning_state: The provisioning state of the private endpoint connection. Known values are: "Creating", "Updating", "Deleting", "Succeeded", "Failed", and "Cancelled". :vartype provisioning_state: str or ~azure.mgmt.batch.models.PrivateEndpointConnectionProvisioningState :ivar private_endpoint: The private endpoint of the private endpoint connection. :vartype private_endpoint: ~azure.mgmt.batch.models.PrivateEndpoint :ivar group_ids: The value has one and only one group id. :vartype group_ids: list[str] :ivar private_link_service_connection_state: The private link service connection state of the private endpoint connection. :vartype private_link_service_connection_state: ~azure.mgmt.batch.models.PrivateLinkServiceConnectionState """ _validation = { "id": {"readonly": True}, "name": {"readonly": True}, "type": {"readonly": True}, "etag": {"readonly": True}, "provisioning_state": {"readonly": True}, "private_endpoint": {"readonly": True}, "group_ids": {"readonly": True}, } _attribute_map = { "id": {"key": "id", "type": "str"}, "name": {"key": "name", "type": "str"}, "type": {"key": "type", "type": "str"}, "etag": {"key": "etag", "type": "str"}, "provisioning_state": {"key": "properties.provisioningState", "type": "str"}, "private_endpoint": {"key": "properties.privateEndpoint", "type": "PrivateEndpoint"}, "group_ids": {"key": "properties.groupIds", "type": "[str]"}, "private_link_service_connection_state": { "key": "properties.privateLinkServiceConnectionState", "type": "PrivateLinkServiceConnectionState", }, } def __init__( self, *, private_link_service_connection_state: Optional["_models.PrivateLinkServiceConnectionState"] = None, **kwargs: Any ) -> None: """ :keyword private_link_service_connection_state: The private link service connection state of the private endpoint connection. :paramtype private_link_service_connection_state: ~azure.mgmt.batch.models.PrivateLinkServiceConnectionState """ super().__init__(**kwargs) self.provisioning_state = None self.private_endpoint = None self.group_ids = None self.private_link_service_connection_state = private_link_service_connection_state class PrivateLinkResource(ProxyResource): """Contains information about a private link resource. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: The ID of the resource. :vartype id: str :ivar name: The name of the resource. :vartype name: str :ivar type: The type of the resource. :vartype type: str :ivar etag: The ETag of the resource, used for concurrency statements. :vartype etag: str :ivar group_id: The group id is used to establish the private link connection. :vartype group_id: str :ivar required_members: The list of required members that are used to establish the private link connection. :vartype required_members: list[str] :ivar required_zone_names: The list of required zone names for the private DNS resource name. :vartype required_zone_names: list[str] """ _validation = { "id": {"readonly": True}, "name": {"readonly": True}, "type": {"readonly": True}, "etag": {"readonly": True}, "group_id": {"readonly": True}, "required_members": {"readonly": True}, "required_zone_names": {"readonly": True}, } _attribute_map = { "id": {"key": "id", "type": "str"}, "name": {"key": "name", "type": "str"}, "type": {"key": "type", "type": "str"}, "etag": {"key": "etag", "type": "str"}, "group_id": {"key": "properties.groupId", "type": "str"}, "required_members": {"key": "properties.requiredMembers", "type": "[str]"}, "required_zone_names": {"key": "properties.requiredZoneNames", "type": "[str]"}, } def __init__(self, **kwargs: Any) -> None: """ """ super().__init__(**kwargs) self.group_id = None self.required_members = None self.required_zone_names = None class PrivateLinkServiceConnectionState(_serialization.Model): """The private link service connection state of the private endpoint connection. Variables are only populated by the server, and will be ignored when sending a request. All required parameters must be populated in order to send to Azure. :ivar status: The status of the Batch private endpoint connection. Required. Known values are: "Approved", "Pending", "Rejected", and "Disconnected". :vartype status: str or ~azure.mgmt.batch.models.PrivateLinkServiceConnectionStatus :ivar description: Description of the private Connection state. :vartype description: str :ivar actions_required: Action required on the private connection state. :vartype actions_required: str """ _validation = { "status": {"required": True}, "actions_required": {"readonly": True}, } _attribute_map = { "status": {"key": "status", "type": "str"}, "description": {"key": "description", "type": "str"}, "actions_required": {"key": "actionsRequired", "type": "str"}, } def __init__( self, *, status: Union[str, "_models.PrivateLinkServiceConnectionStatus"], description: Optional[str] = None, **kwargs: Any ) -> None: """ :keyword status: The status of the Batch private endpoint connection. Required. Known values are: "Approved", "Pending", "Rejected", and "Disconnected". :paramtype status: str or ~azure.mgmt.batch.models.PrivateLinkServiceConnectionStatus :keyword description: Description of the private Connection state. :paramtype description: str """ super().__init__(**kwargs) self.status = status self.description = description self.actions_required = None class PublicIPAddressConfiguration(_serialization.Model): """The public IP Address configuration of the networking configuration of a Pool. :ivar provision: The default value is BatchManaged. Known values are: "BatchManaged", "UserManaged", and "NoPublicIPAddresses". :vartype provision: str or ~azure.mgmt.batch.models.IPAddressProvisioningType :ivar ip_address_ids: The number of IPs specified here limits the maximum size of the Pool - 100 dedicated nodes or 100 Spot/low-priority nodes can be allocated for each public IP. For example, a pool needing 250 dedicated VMs would need at least 3 public IPs specified. Each element of this collection is of the form: /subscriptions/{subscription}/resourceGroups/{group}/providers/Microsoft.Network/publicIPAddresses/{ip}. :vartype ip_address_ids: list[str] """ _attribute_map = { "provision": {"key": "provision", "type": "str"}, "ip_address_ids": {"key": "ipAddressIds", "type": "[str]"}, } def __init__( self, *, provision: Optional[Union[str, "_models.IPAddressProvisioningType"]] = None, ip_address_ids: Optional[List[str]] = None, **kwargs: Any ) -> None: """ :keyword provision: The default value is BatchManaged. Known values are: "BatchManaged", "UserManaged", and "NoPublicIPAddresses". :paramtype provision: str or ~azure.mgmt.batch.models.IPAddressProvisioningType :keyword ip_address_ids: The number of IPs specified here limits the maximum size of the Pool - 100 dedicated nodes or 100 Spot/low-priority nodes can be allocated for each public IP. For example, a pool needing 250 dedicated VMs would need at least 3 public IPs specified. Each element of this collection is of the form: /subscriptions/{subscription}/resourceGroups/{group}/providers/Microsoft.Network/publicIPAddresses/{ip}. :paramtype ip_address_ids: list[str] """ super().__init__(**kwargs) self.provision = provision self.ip_address_ids = ip_address_ids class ResizeError(_serialization.Model): """An error that occurred when resizing a pool. All required parameters must be populated in order to send to Azure. :ivar code: An identifier for the error. Codes are invariant and are intended to be consumed programmatically. Required. :vartype code: str :ivar message: A message describing the error, intended to be suitable for display in a user interface. Required. :vartype message: str :ivar details: Additional details about the error. :vartype details: list[~azure.mgmt.batch.models.ResizeError] """ _validation = { "code": {"required": True}, "message": {"required": True}, } _attribute_map = { "code": {"key": "code", "type": "str"}, "message": {"key": "message", "type": "str"}, "details": {"key": "details", "type": "[ResizeError]"}, } def __init__( self, *, code: str, message: str, details: Optional[List["_models.ResizeError"]] = None, **kwargs: Any ) -> None: """ :keyword code: An identifier for the error. Codes are invariant and are intended to be consumed programmatically. Required. :paramtype code: str :keyword message: A message describing the error, intended to be suitable for display in a user interface. Required. :paramtype message: str :keyword details: Additional details about the error. :paramtype details: list[~azure.mgmt.batch.models.ResizeError] """ super().__init__(**kwargs) self.code = code self.message = message self.details = details class ResizeOperationStatus(_serialization.Model): """Describes either the current operation (if the pool AllocationState is Resizing) or the previously completed operation (if the AllocationState is Steady). :ivar target_dedicated_nodes: The desired number of dedicated compute nodes in the pool. :vartype target_dedicated_nodes: int :ivar target_low_priority_nodes: The desired number of Spot/low-priority compute nodes in the pool. :vartype target_low_priority_nodes: int :ivar resize_timeout: The default value is 15 minutes. The minimum value is 5 minutes. If you specify a value less than 5 minutes, the Batch service returns an error; if you are calling the REST API directly, the HTTP status code is 400 (Bad Request). :vartype resize_timeout: ~datetime.timedelta :ivar node_deallocation_option: The default value is requeue. Known values are: "Requeue", "Terminate", "TaskCompletion", and "RetainedData". :vartype node_deallocation_option: str or ~azure.mgmt.batch.models.ComputeNodeDeallocationOption :ivar start_time: The time when this resize operation was started. :vartype start_time: ~datetime.datetime :ivar errors: This property is set only if an error occurred during the last pool resize, and only when the pool allocationState is Steady. :vartype errors: list[~azure.mgmt.batch.models.ResizeError] """ _attribute_map = { "target_dedicated_nodes": {"key": "targetDedicatedNodes", "type": "int"}, "target_low_priority_nodes": {"key": "targetLowPriorityNodes", "type": "int"}, "resize_timeout": {"key": "resizeTimeout", "type": "duration"}, "node_deallocation_option": {"key": "nodeDeallocationOption", "type": "str"}, "start_time": {"key": "startTime", "type": "iso-8601"}, "errors": {"key": "errors", "type": "[ResizeError]"}, } def __init__( self, *, target_dedicated_nodes: Optional[int] = None, target_low_priority_nodes: Optional[int] = None, resize_timeout: Optional[datetime.timedelta] = None, node_deallocation_option: Optional[Union[str, "_models.ComputeNodeDeallocationOption"]] = None, start_time: Optional[datetime.datetime] = None, errors: Optional[List["_models.ResizeError"]] = None, **kwargs: Any ) -> None: """ :keyword target_dedicated_nodes: The desired number of dedicated compute nodes in the pool. :paramtype target_dedicated_nodes: int :keyword target_low_priority_nodes: The desired number of Spot/low-priority compute nodes in the pool. :paramtype target_low_priority_nodes: int :keyword resize_timeout: The default value is 15 minutes. The minimum value is 5 minutes. If you specify a value less than 5 minutes, the Batch service returns an error; if you are calling the REST API directly, the HTTP status code is 400 (Bad Request). :paramtype resize_timeout: ~datetime.timedelta :keyword node_deallocation_option: The default value is requeue. Known values are: "Requeue", "Terminate", "TaskCompletion", and "RetainedData". :paramtype node_deallocation_option: str or ~azure.mgmt.batch.models.ComputeNodeDeallocationOption :keyword start_time: The time when this resize operation was started. :paramtype start_time: ~datetime.datetime :keyword errors: This property is set only if an error occurred during the last pool resize, and only when the pool allocationState is Steady. :paramtype errors: list[~azure.mgmt.batch.models.ResizeError] """ super().__init__(**kwargs) self.target_dedicated_nodes = target_dedicated_nodes self.target_low_priority_nodes = target_low_priority_nodes self.resize_timeout = resize_timeout self.node_deallocation_option = node_deallocation_option self.start_time = start_time self.errors = errors class ResourceFile(_serialization.Model): """A single file or multiple files to be downloaded to a compute node. :ivar auto_storage_container_name: The autoStorageContainerName, storageContainerUrl and httpUrl properties are mutually exclusive and one of them must be specified. :vartype auto_storage_container_name: str :ivar storage_container_url: The autoStorageContainerName, storageContainerUrl and httpUrl properties are mutually exclusive and one of them must be specified. This URL must be readable and listable from compute nodes. There are three ways to get such a URL for a container in Azure storage: include a Shared Access Signature (SAS) granting read and list permissions on the container, use a managed identity with read and list permissions, or set the ACL for the container to allow public access. :vartype storage_container_url: str :ivar http_url: The autoStorageContainerName, storageContainerUrl and httpUrl properties are mutually exclusive and one of them must be specified. If the URL points to Azure Blob Storage, it must be readable from compute nodes. There are three ways to get such a URL for a blob in Azure storage: include a Shared Access Signature (SAS) granting read permissions on the blob, use a managed identity with read permission, or set the ACL for the blob or its container to allow public access. :vartype http_url: str :ivar blob_prefix: The property is valid only when autoStorageContainerName or storageContainerUrl is used. This prefix can be a partial filename or a subdirectory. If a prefix is not specified, all the files in the container will be downloaded. :vartype blob_prefix: str :ivar file_path: If the httpUrl property is specified, the filePath is required and describes the path which the file will be downloaded to, including the filename. Otherwise, if the autoStorageContainerName or storageContainerUrl property is specified, filePath is optional and is the directory to download the files to. In the case where filePath is used as a directory, any directory structure already associated with the input data will be retained in full and appended to the specified filePath directory. The specified relative path cannot break out of the task's working directory (for example by using '..'). :vartype file_path: str :ivar file_mode: This property applies only to files being downloaded to Linux compute nodes. It will be ignored if it is specified for a resourceFile which will be downloaded to a Windows node. If this property is not specified for a Linux node, then a default value of 0770 is applied to the file. :vartype file_mode: str :ivar identity_reference: The reference to a user assigned identity associated with the Batch pool which a compute node will use. :vartype identity_reference: ~azure.mgmt.batch.models.ComputeNodeIdentityReference """ _attribute_map = { "auto_storage_container_name": {"key": "autoStorageContainerName", "type": "str"}, "storage_container_url": {"key": "storageContainerUrl", "type": "str"}, "http_url": {"key": "httpUrl", "type": "str"}, "blob_prefix": {"key": "blobPrefix", "type": "str"}, "file_path": {"key": "filePath", "type": "str"}, "file_mode": {"key": "fileMode", "type": "str"}, "identity_reference": {"key": "identityReference", "type": "ComputeNodeIdentityReference"}, } def __init__( self, *, auto_storage_container_name: Optional[str] = None, storage_container_url: Optional[str] = None, http_url: Optional[str] = None, blob_prefix: Optional[str] = None, file_path: Optional[str] = None, file_mode: Optional[str] = None, identity_reference: Optional["_models.ComputeNodeIdentityReference"] = None, **kwargs: Any ) -> None: """ :keyword auto_storage_container_name: The autoStorageContainerName, storageContainerUrl and httpUrl properties are mutually exclusive and one of them must be specified. :paramtype auto_storage_container_name: str :keyword storage_container_url: The autoStorageContainerName, storageContainerUrl and httpUrl properties are mutually exclusive and one of them must be specified. This URL must be readable and listable from compute nodes. There are three ways to get such a URL for a container in Azure storage: include a Shared Access Signature (SAS) granting read and list permissions on the container, use a managed identity with read and list permissions, or set the ACL for the container to allow public access. :paramtype storage_container_url: str :keyword http_url: The autoStorageContainerName, storageContainerUrl and httpUrl properties are mutually exclusive and one of them must be specified. If the URL points to Azure Blob Storage, it must be readable from compute nodes. There are three ways to get such a URL for a blob in Azure storage: include a Shared Access Signature (SAS) granting read permissions on the blob, use a managed identity with read permission, or set the ACL for the blob or its container to allow public access. :paramtype http_url: str :keyword blob_prefix: The property is valid only when autoStorageContainerName or storageContainerUrl is used. This prefix can be a partial filename or a subdirectory. If a prefix is not specified, all the files in the container will be downloaded. :paramtype blob_prefix: str :keyword file_path: If the httpUrl property is specified, the filePath is required and describes the path which the file will be downloaded to, including the filename. Otherwise, if the autoStorageContainerName or storageContainerUrl property is specified, filePath is optional and is the directory to download the files to. In the case where filePath is used as a directory, any directory structure already associated with the input data will be retained in full and appended to the specified filePath directory. The specified relative path cannot break out of the task's working directory (for example by using '..'). :paramtype file_path: str :keyword file_mode: This property applies only to files being downloaded to Linux compute nodes. It will be ignored if it is specified for a resourceFile which will be downloaded to a Windows node. If this property is not specified for a Linux node, then a default value of 0770 is applied to the file. :paramtype file_mode: str :keyword identity_reference: The reference to a user assigned identity associated with the Batch pool which a compute node will use. :paramtype identity_reference: ~azure.mgmt.batch.models.ComputeNodeIdentityReference """ super().__init__(**kwargs) self.auto_storage_container_name = auto_storage_container_name self.storage_container_url = storage_container_url self.http_url = http_url self.blob_prefix = blob_prefix self.file_path = file_path self.file_mode = file_mode self.identity_reference = identity_reference class ScaleSettings(_serialization.Model): """Defines the desired size of the pool. This can either be 'fixedScale' where the requested targetDedicatedNodes is specified, or 'autoScale' which defines a formula which is periodically reevaluated. If this property is not specified, the pool will have a fixed scale with 0 targetDedicatedNodes. :ivar fixed_scale: This property and autoScale are mutually exclusive and one of the properties must be specified. :vartype fixed_scale: ~azure.mgmt.batch.models.FixedScaleSettings :ivar auto_scale: This property and fixedScale are mutually exclusive and one of the properties must be specified. :vartype auto_scale: ~azure.mgmt.batch.models.AutoScaleSettings """ _attribute_map = { "fixed_scale": {"key": "fixedScale", "type": "FixedScaleSettings"}, "auto_scale": {"key": "autoScale", "type": "AutoScaleSettings"}, } def __init__( self, *, fixed_scale: Optional["_models.FixedScaleSettings"] = None, auto_scale: Optional["_models.AutoScaleSettings"] = None, **kwargs: Any ) -> None: """ :keyword fixed_scale: This property and autoScale are mutually exclusive and one of the properties must be specified. :paramtype fixed_scale: ~azure.mgmt.batch.models.FixedScaleSettings :keyword auto_scale: This property and fixedScale are mutually exclusive and one of the properties must be specified. :paramtype auto_scale: ~azure.mgmt.batch.models.AutoScaleSettings """ super().__init__(**kwargs) self.fixed_scale = fixed_scale self.auto_scale = auto_scale class SkuCapability(_serialization.Model): """A SKU capability, such as the number of cores. Variables are only populated by the server, and will be ignored when sending a request. :ivar name: The name of the feature. :vartype name: str :ivar value: The value of the feature. :vartype value: str """ _validation = { "name": {"readonly": True}, "value": {"readonly": True}, } _attribute_map = { "name": {"key": "name", "type": "str"}, "value": {"key": "value", "type": "str"}, } def __init__(self, **kwargs: Any) -> None: """ """ super().__init__(**kwargs) self.name = None self.value = None class StartTask(_serialization.Model): """In some cases the start task may be re-run even though the node was not rebooted. Due to this, start tasks should be idempotent and exit gracefully if the setup they're performing has already been done. Special care should be taken to avoid start tasks which create breakaway process or install/launch services from the start task working directory, as this will block Batch from being able to re-run the start task. :ivar command_line: The command line does not run under a shell, and therefore cannot take advantage of shell features such as environment variable expansion. If you want to take advantage of such features, you should invoke the shell in the command line, for example using "cmd /c MyCommand" in Windows or "/bin/sh -c MyCommand" in Linux. Required if any other properties of the startTask are specified. :vartype command_line: str :ivar resource_files: A list of files that the Batch service will download to the compute node before running the command line. :vartype resource_files: list[~azure.mgmt.batch.models.ResourceFile] :ivar environment_settings: A list of environment variable settings for the start task. :vartype environment_settings: list[~azure.mgmt.batch.models.EnvironmentSetting] :ivar user_identity: If omitted, the task runs as a non-administrative user unique to the task. :vartype user_identity: ~azure.mgmt.batch.models.UserIdentity :ivar max_task_retry_count: The Batch service retries a task if its exit code is nonzero. Note that this value specifically controls the number of retries. The Batch service will try the task once, and may then retry up to this limit. For example, if the maximum retry count is 3, Batch tries the task up to 4 times (one initial try and 3 retries). If the maximum retry count is 0, the Batch service does not retry the task. If the maximum retry count is -1, the Batch service retries the task without limit. :vartype max_task_retry_count: int :ivar wait_for_success: If true and the start task fails on a compute node, the Batch service retries the start task up to its maximum retry count (maxTaskRetryCount). If the task has still not completed successfully after all retries, then the Batch service marks the compute node unusable, and will not schedule tasks to it. This condition can be detected via the node state and scheduling error detail. If false, the Batch service will not wait for the start task to complete. In this case, other tasks can start executing on the compute node while the start task is still running; and even if the start task fails, new tasks will continue to be scheduled on the node. The default is true. :vartype wait_for_success: bool :ivar container_settings: When this is specified, all directories recursively below the AZ_BATCH_NODE_ROOT_DIR (the root of Azure Batch directories on the node) are mapped into the container, all task environment variables are mapped into the container, and the task command line is executed in the container. :vartype container_settings: ~azure.mgmt.batch.models.TaskContainerSettings """ _attribute_map = { "command_line": {"key": "commandLine", "type": "str"}, "resource_files": {"key": "resourceFiles", "type": "[ResourceFile]"}, "environment_settings": {"key": "environmentSettings", "type": "[EnvironmentSetting]"}, "user_identity": {"key": "userIdentity", "type": "UserIdentity"}, "max_task_retry_count": {"key": "maxTaskRetryCount", "type": "int"}, "wait_for_success": {"key": "waitForSuccess", "type": "bool"}, "container_settings": {"key": "containerSettings", "type": "TaskContainerSettings"}, } def __init__( self, *, command_line: Optional[str] = None, resource_files: Optional[List["_models.ResourceFile"]] = None, environment_settings: Optional[List["_models.EnvironmentSetting"]] = None, user_identity: Optional["_models.UserIdentity"] = None, max_task_retry_count: Optional[int] = None, wait_for_success: Optional[bool] = None, container_settings: Optional["_models.TaskContainerSettings"] = None, **kwargs: Any ) -> None: """ :keyword command_line: The command line does not run under a shell, and therefore cannot take advantage of shell features such as environment variable expansion. If you want to take advantage of such features, you should invoke the shell in the command line, for example using "cmd /c MyCommand" in Windows or "/bin/sh -c MyCommand" in Linux. Required if any other properties of the startTask are specified. :paramtype command_line: str :keyword resource_files: A list of files that the Batch service will download to the compute node before running the command line. :paramtype resource_files: list[~azure.mgmt.batch.models.ResourceFile] :keyword environment_settings: A list of environment variable settings for the start task. :paramtype environment_settings: list[~azure.mgmt.batch.models.EnvironmentSetting] :keyword user_identity: If omitted, the task runs as a non-administrative user unique to the task. :paramtype user_identity: ~azure.mgmt.batch.models.UserIdentity :keyword max_task_retry_count: The Batch service retries a task if its exit code is nonzero. Note that this value specifically controls the number of retries. The Batch service will try the task once, and may then retry up to this limit. For example, if the maximum retry count is 3, Batch tries the task up to 4 times (one initial try and 3 retries). If the maximum retry count is 0, the Batch service does not retry the task. If the maximum retry count is -1, the Batch service retries the task without limit. :paramtype max_task_retry_count: int :keyword wait_for_success: If true and the start task fails on a compute node, the Batch service retries the start task up to its maximum retry count (maxTaskRetryCount). If the task has still not completed successfully after all retries, then the Batch service marks the compute node unusable, and will not schedule tasks to it. This condition can be detected via the node state and scheduling error detail. If false, the Batch service will not wait for the start task to complete. In this case, other tasks can start executing on the compute node while the start task is still running; and even if the start task fails, new tasks will continue to be scheduled on the node. The default is true. :paramtype wait_for_success: bool :keyword container_settings: When this is specified, all directories recursively below the AZ_BATCH_NODE_ROOT_DIR (the root of Azure Batch directories on the node) are mapped into the container, all task environment variables are mapped into the container, and the task command line is executed in the container. :paramtype container_settings: ~azure.mgmt.batch.models.TaskContainerSettings """ super().__init__(**kwargs) self.command_line = command_line self.resource_files = resource_files self.environment_settings = environment_settings self.user_identity = user_identity self.max_task_retry_count = max_task_retry_count self.wait_for_success = wait_for_success self.container_settings = container_settings class SupportedSku(_serialization.Model): """Describes a Batch supported SKU. Variables are only populated by the server, and will be ignored when sending a request. :ivar name: The name of the SKU. :vartype name: str :ivar family_name: The family name of the SKU. :vartype family_name: str :ivar capabilities: A collection of capabilities which this SKU supports. :vartype capabilities: list[~azure.mgmt.batch.models.SkuCapability] """ _validation = { "name": {"readonly": True}, "family_name": {"readonly": True}, "capabilities": {"readonly": True}, } _attribute_map = { "name": {"key": "name", "type": "str"}, "family_name": {"key": "familyName", "type": "str"}, "capabilities": {"key": "capabilities", "type": "[SkuCapability]"}, } def __init__(self, **kwargs: Any) -> None: """ """ super().__init__(**kwargs) self.name = None self.family_name = None self.capabilities = None class SupportedSkusResult(_serialization.Model): """The Batch List supported SKUs operation response. Variables are only populated by the server, and will be ignored when sending a request. All required parameters must be populated in order to send to Azure. :ivar value: The list of SKUs available for the Batch service in the location. Required. :vartype value: list[~azure.mgmt.batch.models.SupportedSku] :ivar next_link: The URL to use for getting the next set of results. :vartype next_link: str """ _validation = { "value": {"required": True}, "next_link": {"readonly": True}, } _attribute_map = { "value": {"key": "value", "type": "[SupportedSku]"}, "next_link": {"key": "nextLink", "type": "str"}, } def __init__(self, *, value: List["_models.SupportedSku"], **kwargs: Any) -> None: """ :keyword value: The list of SKUs available for the Batch service in the location. Required. :paramtype value: list[~azure.mgmt.batch.models.SupportedSku] """ super().__init__(**kwargs) self.value = value self.next_link = None class TaskContainerSettings(_serialization.Model): """The container settings for a task. All required parameters must be populated in order to send to Azure. :ivar container_run_options: These additional options are supplied as arguments to the "docker create" command, in addition to those controlled by the Batch Service. :vartype container_run_options: str :ivar image_name: This is the full image reference, as would be specified to "docker pull". If no tag is provided as part of the image name, the tag ":latest" is used as a default. Required. :vartype image_name: str :ivar registry: This setting can be omitted if was already provided at pool creation. :vartype registry: ~azure.mgmt.batch.models.ContainerRegistry :ivar working_directory: A flag to indicate where the container task working directory is. The default is 'taskWorkingDirectory'. Known values are: "TaskWorkingDirectory" and "ContainerImageDefault". :vartype working_directory: str or ~azure.mgmt.batch.models.ContainerWorkingDirectory """ _validation = { "image_name": {"required": True}, } _attribute_map = { "container_run_options": {"key": "containerRunOptions", "type": "str"}, "image_name": {"key": "imageName", "type": "str"}, "registry": {"key": "registry", "type": "ContainerRegistry"}, "working_directory": {"key": "workingDirectory", "type": "str"}, } def __init__( self, *, image_name: str, container_run_options: Optional[str] = None, registry: Optional["_models.ContainerRegistry"] = None, working_directory: Optional[Union[str, "_models.ContainerWorkingDirectory"]] = None, **kwargs: Any ) -> None: """ :keyword container_run_options: These additional options are supplied as arguments to the "docker create" command, in addition to those controlled by the Batch Service. :paramtype container_run_options: str :keyword image_name: This is the full image reference, as would be specified to "docker pull". If no tag is provided as part of the image name, the tag ":latest" is used as a default. Required. :paramtype image_name: str :keyword registry: This setting can be omitted if was already provided at pool creation. :paramtype registry: ~azure.mgmt.batch.models.ContainerRegistry :keyword working_directory: A flag to indicate where the container task working directory is. The default is 'taskWorkingDirectory'. Known values are: "TaskWorkingDirectory" and "ContainerImageDefault". :paramtype working_directory: str or ~azure.mgmt.batch.models.ContainerWorkingDirectory """ super().__init__(**kwargs) self.container_run_options = container_run_options self.image_name = image_name self.registry = registry self.working_directory = working_directory class TaskSchedulingPolicy(_serialization.Model): """Specifies how tasks should be distributed across compute nodes. All required parameters must be populated in order to send to Azure. :ivar node_fill_type: How tasks should be distributed across compute nodes. Required. Known values are: "Spread" and "Pack". :vartype node_fill_type: str or ~azure.mgmt.batch.models.ComputeNodeFillType """ _validation = { "node_fill_type": {"required": True}, } _attribute_map = { "node_fill_type": {"key": "nodeFillType", "type": "str"}, } def __init__(self, *, node_fill_type: Union[str, "_models.ComputeNodeFillType"], **kwargs: Any) -> None: """ :keyword node_fill_type: How tasks should be distributed across compute nodes. Required. Known values are: "Spread" and "Pack". :paramtype node_fill_type: str or ~azure.mgmt.batch.models.ComputeNodeFillType """ super().__init__(**kwargs) self.node_fill_type = node_fill_type class UserAccount(_serialization.Model): """Properties used to create a user on an Azure Batch node. All required parameters must be populated in order to send to Azure. :ivar name: The name of the user account. Names can contain any Unicode characters up to a maximum length of 20. Required. :vartype name: str :ivar password: The password for the user account. Required. :vartype password: str :ivar elevation_level: nonAdmin - The auto user is a standard user without elevated access. admin - The auto user is a user with elevated access and operates with full Administrator permissions. The default value is nonAdmin. Known values are: "NonAdmin" and "Admin". :vartype elevation_level: str or ~azure.mgmt.batch.models.ElevationLevel :ivar linux_user_configuration: This property is ignored if specified on a Windows pool. If not specified, the user is created with the default options. :vartype linux_user_configuration: ~azure.mgmt.batch.models.LinuxUserConfiguration :ivar windows_user_configuration: This property can only be specified if the user is on a Windows pool. If not specified and on a Windows pool, the user is created with the default options. :vartype windows_user_configuration: ~azure.mgmt.batch.models.WindowsUserConfiguration """ _validation = { "name": {"required": True}, "password": {"required": True}, } _attribute_map = { "name": {"key": "name", "type": "str"}, "password": {"key": "password", "type": "str"}, "elevation_level": {"key": "elevationLevel", "type": "str"}, "linux_user_configuration": {"key": "linuxUserConfiguration", "type": "LinuxUserConfiguration"}, "windows_user_configuration": {"key": "windowsUserConfiguration", "type": "WindowsUserConfiguration"}, } def __init__( self, *, name: str, password: str, elevation_level: Optional[Union[str, "_models.ElevationLevel"]] = None, linux_user_configuration: Optional["_models.LinuxUserConfiguration"] = None, windows_user_configuration: Optional["_models.WindowsUserConfiguration"] = None, **kwargs: Any ) -> None: """ :keyword name: The name of the user account. Names can contain any Unicode characters up to a maximum length of 20. Required. :paramtype name: str :keyword password: The password for the user account. Required. :paramtype password: str :keyword elevation_level: nonAdmin - The auto user is a standard user without elevated access. admin - The auto user is a user with elevated access and operates with full Administrator permissions. The default value is nonAdmin. Known values are: "NonAdmin" and "Admin". :paramtype elevation_level: str or ~azure.mgmt.batch.models.ElevationLevel :keyword linux_user_configuration: This property is ignored if specified on a Windows pool. If not specified, the user is created with the default options. :paramtype linux_user_configuration: ~azure.mgmt.batch.models.LinuxUserConfiguration :keyword windows_user_configuration: This property can only be specified if the user is on a Windows pool. If not specified and on a Windows pool, the user is created with the default options. :paramtype windows_user_configuration: ~azure.mgmt.batch.models.WindowsUserConfiguration """ super().__init__(**kwargs) self.name = name self.password = password self.elevation_level = elevation_level self.linux_user_configuration = linux_user_configuration self.windows_user_configuration = windows_user_configuration class UserAssignedIdentities(_serialization.Model): """The list of associated user identities. Variables are only populated by the server, and will be ignored when sending a request. :ivar principal_id: The principal id of user assigned identity. :vartype principal_id: str :ivar client_id: The client id of user assigned identity. :vartype client_id: str """ _validation = { "principal_id": {"readonly": True}, "client_id": {"readonly": True}, } _attribute_map = { "principal_id": {"key": "principalId", "type": "str"}, "client_id": {"key": "clientId", "type": "str"}, } def __init__(self, **kwargs: Any) -> None: """ """ super().__init__(**kwargs) self.principal_id = None self.client_id = None class UserIdentity(_serialization.Model): """Specify either the userName or autoUser property, but not both. :ivar user_name: The userName and autoUser properties are mutually exclusive; you must specify one but not both. :vartype user_name: str :ivar auto_user: The userName and autoUser properties are mutually exclusive; you must specify one but not both. :vartype auto_user: ~azure.mgmt.batch.models.AutoUserSpecification """ _attribute_map = { "user_name": {"key": "userName", "type": "str"}, "auto_user": {"key": "autoUser", "type": "AutoUserSpecification"}, } def __init__( self, *, user_name: Optional[str] = None, auto_user: Optional["_models.AutoUserSpecification"] = None, **kwargs: Any ) -> None: """ :keyword user_name: The userName and autoUser properties are mutually exclusive; you must specify one but not both. :paramtype user_name: str :keyword auto_user: The userName and autoUser properties are mutually exclusive; you must specify one but not both. :paramtype auto_user: ~azure.mgmt.batch.models.AutoUserSpecification """ super().__init__(**kwargs) self.user_name = user_name self.auto_user = auto_user class VirtualMachineConfiguration(_serialization.Model): """The configuration for compute nodes in a pool based on the Azure Virtual Machines infrastructure. All required parameters must be populated in order to send to Azure. :ivar image_reference: A reference to an Azure Virtual Machines Marketplace image or the Azure Image resource of a custom Virtual Machine. To get the list of all imageReferences verified by Azure Batch, see the 'List supported node agent SKUs' operation. Required. :vartype image_reference: ~azure.mgmt.batch.models.ImageReference :ivar node_agent_sku_id: The Batch node agent is a program that runs on each node in the pool, and provides the command-and-control interface between the node and the Batch service. There are different implementations of the node agent, known as SKUs, for different operating systems. You must specify a node agent SKU which matches the selected image reference. To get the list of supported node agent SKUs along with their list of verified image references, see the 'List supported node agent SKUs' operation. Required. :vartype node_agent_sku_id: str :ivar windows_configuration: This property must not be specified if the imageReference specifies a Linux OS image. :vartype windows_configuration: ~azure.mgmt.batch.models.WindowsConfiguration :ivar data_disks: This property must be specified if the compute nodes in the pool need to have empty data disks attached to them. :vartype data_disks: list[~azure.mgmt.batch.models.DataDisk] :ivar license_type: This only applies to images that contain the Windows operating system, and should only be used when you hold valid on-premises licenses for the nodes which will be deployed. If omitted, no on-premises licensing discount is applied. Values are: Windows_Server - The on-premises license is for Windows Server. Windows_Client - The on-premises license is for Windows Client. :vartype license_type: str :ivar container_configuration: If specified, setup is performed on each node in the pool to allow tasks to run in containers. All regular tasks and job manager tasks run on this pool must specify the containerSettings property, and all other tasks may specify it. :vartype container_configuration: ~azure.mgmt.batch.models.ContainerConfiguration :ivar disk_encryption_configuration: If specified, encryption is performed on each node in the pool during node provisioning. :vartype disk_encryption_configuration: ~azure.mgmt.batch.models.DiskEncryptionConfiguration :ivar node_placement_configuration: This configuration will specify rules on how nodes in the pool will be physically allocated. :vartype node_placement_configuration: ~azure.mgmt.batch.models.NodePlacementConfiguration :ivar extensions: If specified, the extensions mentioned in this configuration will be installed on each node. :vartype extensions: list[~azure.mgmt.batch.models.VMExtension] :ivar os_disk: Contains configuration for ephemeral OSDisk settings. :vartype os_disk: ~azure.mgmt.batch.models.OSDisk """ _validation = { "image_reference": {"required": True}, "node_agent_sku_id": {"required": True}, } _attribute_map = { "image_reference": {"key": "imageReference", "type": "ImageReference"}, "node_agent_sku_id": {"key": "nodeAgentSkuId", "type": "str"}, "windows_configuration": {"key": "windowsConfiguration", "type": "WindowsConfiguration"}, "data_disks": {"key": "dataDisks", "type": "[DataDisk]"}, "license_type": {"key": "licenseType", "type": "str"}, "container_configuration": {"key": "containerConfiguration", "type": "ContainerConfiguration"}, "disk_encryption_configuration": {"key": "diskEncryptionConfiguration", "type": "DiskEncryptionConfiguration"}, "node_placement_configuration": {"key": "nodePlacementConfiguration", "type": "NodePlacementConfiguration"}, "extensions": {"key": "extensions", "type": "[VMExtension]"}, "os_disk": {"key": "osDisk", "type": "OSDisk"}, } def __init__( self, *, image_reference: "_models.ImageReference", node_agent_sku_id: str, windows_configuration: Optional["_models.WindowsConfiguration"] = None, data_disks: Optional[List["_models.DataDisk"]] = None, license_type: Optional[str] = None, container_configuration: Optional["_models.ContainerConfiguration"] = None, disk_encryption_configuration: Optional["_models.DiskEncryptionConfiguration"] = None, node_placement_configuration: Optional["_models.NodePlacementConfiguration"] = None, extensions: Optional[List["_models.VMExtension"]] = None, os_disk: Optional["_models.OSDisk"] = None, **kwargs: Any ) -> None: """ :keyword image_reference: A reference to an Azure Virtual Machines Marketplace image or the Azure Image resource of a custom Virtual Machine. To get the list of all imageReferences verified by Azure Batch, see the 'List supported node agent SKUs' operation. Required. :paramtype image_reference: ~azure.mgmt.batch.models.ImageReference :keyword node_agent_sku_id: The Batch node agent is a program that runs on each node in the pool, and provides the command-and-control interface between the node and the Batch service. There are different implementations of the node agent, known as SKUs, for different operating systems. You must specify a node agent SKU which matches the selected image reference. To get the list of supported node agent SKUs along with their list of verified image references, see the 'List supported node agent SKUs' operation. Required. :paramtype node_agent_sku_id: str :keyword windows_configuration: This property must not be specified if the imageReference specifies a Linux OS image. :paramtype windows_configuration: ~azure.mgmt.batch.models.WindowsConfiguration :keyword data_disks: This property must be specified if the compute nodes in the pool need to have empty data disks attached to them. :paramtype data_disks: list[~azure.mgmt.batch.models.DataDisk] :keyword license_type: This only applies to images that contain the Windows operating system, and should only be used when you hold valid on-premises licenses for the nodes which will be deployed. If omitted, no on-premises licensing discount is applied. Values are: Windows_Server - The on-premises license is for Windows Server. Windows_Client - The on-premises license is for Windows Client. :paramtype license_type: str :keyword container_configuration: If specified, setup is performed on each node in the pool to allow tasks to run in containers. All regular tasks and job manager tasks run on this pool must specify the containerSettings property, and all other tasks may specify it. :paramtype container_configuration: ~azure.mgmt.batch.models.ContainerConfiguration :keyword disk_encryption_configuration: If specified, encryption is performed on each node in the pool during node provisioning. :paramtype disk_encryption_configuration: ~azure.mgmt.batch.models.DiskEncryptionConfiguration :keyword node_placement_configuration: This configuration will specify rules on how nodes in the pool will be physically allocated. :paramtype node_placement_configuration: ~azure.mgmt.batch.models.NodePlacementConfiguration :keyword extensions: If specified, the extensions mentioned in this configuration will be installed on each node. :paramtype extensions: list[~azure.mgmt.batch.models.VMExtension] :keyword os_disk: Contains configuration for ephemeral OSDisk settings. :paramtype os_disk: ~azure.mgmt.batch.models.OSDisk """ super().__init__(**kwargs) self.image_reference = image_reference self.node_agent_sku_id = node_agent_sku_id self.windows_configuration = windows_configuration self.data_disks = data_disks self.license_type = license_type self.container_configuration = container_configuration self.disk_encryption_configuration = disk_encryption_configuration self.node_placement_configuration = node_placement_configuration self.extensions = extensions self.os_disk = os_disk class VirtualMachineFamilyCoreQuota(_serialization.Model): """A VM Family and its associated core quota for the Batch account. Variables are only populated by the server, and will be ignored when sending a request. :ivar name: The Virtual Machine family name. :vartype name: str :ivar core_quota: The core quota for the VM family for the Batch account. :vartype core_quota: int """ _validation = { "name": {"readonly": True}, "core_quota": {"readonly": True}, } _attribute_map = { "name": {"key": "name", "type": "str"}, "core_quota": {"key": "coreQuota", "type": "int"}, } def __init__(self, **kwargs: Any) -> None: """ """ super().__init__(**kwargs) self.name = None self.core_quota = None class VMExtension(_serialization.Model): """The configuration for virtual machine extensions. All required parameters must be populated in order to send to Azure. :ivar name: The name of the virtual machine extension. Required. :vartype name: str :ivar publisher: The name of the extension handler publisher. Required. :vartype publisher: str :ivar type: The type of the extensions. Required. :vartype type: str :ivar type_handler_version: The version of script handler. :vartype type_handler_version: str :ivar auto_upgrade_minor_version: Indicates whether the extension should use a newer minor version if one is available at deployment time. Once deployed, however, the extension will not upgrade minor versions unless redeployed, even with this property set to true. :vartype auto_upgrade_minor_version: bool :ivar enable_automatic_upgrade: Indicates whether the extension should be automatically upgraded by the platform if there is a newer version of the extension available. :vartype enable_automatic_upgrade: bool :ivar settings: JSON formatted public settings for the extension. :vartype settings: JSON :ivar protected_settings: The extension can contain either protectedSettings or protectedSettingsFromKeyVault or no protected settings at all. :vartype protected_settings: JSON :ivar provision_after_extensions: Collection of extension names after which this extension needs to be provisioned. :vartype provision_after_extensions: list[str] """ _validation = { "name": {"required": True}, "publisher": {"required": True}, "type": {"required": True}, } _attribute_map = { "name": {"key": "name", "type": "str"}, "publisher": {"key": "publisher", "type": "str"}, "type": {"key": "type", "type": "str"}, "type_handler_version": {"key": "typeHandlerVersion", "type": "str"}, "auto_upgrade_minor_version": {"key": "autoUpgradeMinorVersion", "type": "bool"}, "enable_automatic_upgrade": {"key": "enableAutomaticUpgrade", "type": "bool"}, "settings": {"key": "settings", "type": "object"}, "protected_settings": {"key": "protectedSettings", "type": "object"}, "provision_after_extensions": {"key": "provisionAfterExtensions", "type": "[str]"}, } def __init__( self, *, name: str, publisher: str, type: str, type_handler_version: Optional[str] = None, auto_upgrade_minor_version: Optional[bool] = None, enable_automatic_upgrade: Optional[bool] = None, settings: Optional[JSON] = None, protected_settings: Optional[JSON] = None, provision_after_extensions: Optional[List[str]] = None, **kwargs: Any ) -> None: """ :keyword name: The name of the virtual machine extension. Required. :paramtype name: str :keyword publisher: The name of the extension handler publisher. Required. :paramtype publisher: str :keyword type: The type of the extensions. Required. :paramtype type: str :keyword type_handler_version: The version of script handler. :paramtype type_handler_version: str :keyword auto_upgrade_minor_version: Indicates whether the extension should use a newer minor version if one is available at deployment time. Once deployed, however, the extension will not upgrade minor versions unless redeployed, even with this property set to true. :paramtype auto_upgrade_minor_version: bool :keyword enable_automatic_upgrade: Indicates whether the extension should be automatically upgraded by the platform if there is a newer version of the extension available. :paramtype enable_automatic_upgrade: bool :keyword settings: JSON formatted public settings for the extension. :paramtype settings: JSON :keyword protected_settings: The extension can contain either protectedSettings or protectedSettingsFromKeyVault or no protected settings at all. :paramtype protected_settings: JSON :keyword provision_after_extensions: Collection of extension names after which this extension needs to be provisioned. :paramtype provision_after_extensions: list[str] """ super().__init__(**kwargs) self.name = name self.publisher = publisher self.type = type self.type_handler_version = type_handler_version self.auto_upgrade_minor_version = auto_upgrade_minor_version self.enable_automatic_upgrade = enable_automatic_upgrade self.settings = settings self.protected_settings = protected_settings self.provision_after_extensions = provision_after_extensions class WindowsConfiguration(_serialization.Model): """Windows operating system settings to apply to the virtual machine. :ivar enable_automatic_updates: If omitted, the default value is true. :vartype enable_automatic_updates: bool """ _attribute_map = { "enable_automatic_updates": {"key": "enableAutomaticUpdates", "type": "bool"}, } def __init__(self, *, enable_automatic_updates: Optional[bool] = None, **kwargs: Any) -> None: """ :keyword enable_automatic_updates: If omitted, the default value is true. :paramtype enable_automatic_updates: bool """ super().__init__(**kwargs) self.enable_automatic_updates = enable_automatic_updates class WindowsUserConfiguration(_serialization.Model): """Properties used to create a user account on a Windows node. :ivar login_mode: Specifies login mode for the user. The default value for VirtualMachineConfiguration pools is interactive mode and for CloudServiceConfiguration pools is batch mode. Known values are: "Batch" and "Interactive". :vartype login_mode: str or ~azure.mgmt.batch.models.LoginMode """ _attribute_map = { "login_mode": {"key": "loginMode", "type": "str"}, } def __init__(self, *, login_mode: Optional[Union[str, "_models.LoginMode"]] = None, **kwargs: Any) -> None: """ :keyword login_mode: Specifies login mode for the user. The default value for VirtualMachineConfiguration pools is interactive mode and for CloudServiceConfiguration pools is batch mode. Known values are: "Batch" and "Interactive". :paramtype login_mode: str or ~azure.mgmt.batch.models.LoginMode """ super().__init__(**kwargs) self.login_mode = login_mode
0.695545
0.291586
from enum import Enum from azure.core import CaseInsensitiveEnumMeta class AccountKeyType(str, Enum, metaclass=CaseInsensitiveEnumMeta): """The type of account key to regenerate.""" PRIMARY = "Primary" """The primary account key.""" SECONDARY = "Secondary" """The secondary account key.""" class AllocationState(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Whether the pool is resizing.""" STEADY = "Steady" """The pool is not resizing. There are no changes to the number of nodes in the pool in progress. #: A pool enters this state when it is created and when no operations are being performed on the #: pool to change the number of nodes.""" RESIZING = "Resizing" """The pool is resizing; that is, compute nodes are being added to or removed from the pool.""" STOPPING = "Stopping" """The pool was resizing, but the user has requested that the resize be stopped, but the stop #: request has not yet been completed.""" class AuthenticationMode(str, Enum, metaclass=CaseInsensitiveEnumMeta): """The authentication mode for the Batch account.""" SHARED_KEY = "SharedKey" """The authentication mode using shared keys.""" AAD = "AAD" """The authentication mode using Azure Active Directory.""" TASK_AUTHENTICATION_TOKEN = "TaskAuthenticationToken" """The authentication mode using task authentication tokens.""" class AutoStorageAuthenticationMode(str, Enum, metaclass=CaseInsensitiveEnumMeta): """The authentication mode which the Batch service will use to manage the auto-storage account.""" STORAGE_KEYS = "StorageKeys" """The Batch service will authenticate requests to auto-storage using storage account keys.""" BATCH_ACCOUNT_MANAGED_IDENTITY = "BatchAccountManagedIdentity" """The Batch service will authenticate requests to auto-storage using the managed identity #: assigned to the Batch account.""" class AutoUserScope(str, Enum, metaclass=CaseInsensitiveEnumMeta): """The default value is Pool. If the pool is running Windows a value of Task should be specified if stricter isolation between tasks is required. For example, if the task mutates the registry in a way which could impact other tasks, or if certificates have been specified on the pool which should not be accessible by normal tasks but should be accessible by start tasks. """ TASK = "Task" """Specifies that the service should create a new user for the task.""" POOL = "Pool" """Specifies that the task runs as the common auto user account which is created on every node in #: a pool.""" class CachingType(str, Enum, metaclass=CaseInsensitiveEnumMeta): """The type of caching to enable for the disk.""" NONE = "None" """The caching mode for the disk is not enabled.""" READ_ONLY = "ReadOnly" """The caching mode for the disk is read only.""" READ_WRITE = "ReadWrite" """The caching mode for the disk is read and write.""" class CertificateFormat(str, Enum, metaclass=CaseInsensitiveEnumMeta): """The format of the certificate - either Pfx or Cer. If omitted, the default is Pfx.""" PFX = "Pfx" """The certificate is a PFX (PKCS#12) formatted certificate or certificate chain.""" CER = "Cer" """The certificate is a base64-encoded X.509 certificate.""" class CertificateProvisioningState(str, Enum, metaclass=CaseInsensitiveEnumMeta): """CertificateProvisioningState.""" SUCCEEDED = "Succeeded" """The certificate is available for use in pools.""" DELETING = "Deleting" """The user has requested that the certificate be deleted, but the delete operation has not yet #: completed. You may not reference the certificate when creating or updating pools.""" FAILED = "Failed" """The user requested that the certificate be deleted, but there are pools that still have #: references to the certificate, or it is still installed on one or more compute nodes. (The #: latter can occur if the certificate has been removed from the pool, but the node has not yet #: restarted. Nodes refresh their certificates only when they restart.) You may use the cancel #: certificate delete operation to cancel the delete, or the delete certificate operation to retry #: the delete.""" class CertificateStoreLocation(str, Enum, metaclass=CaseInsensitiveEnumMeta): """The default value is currentUser. This property is applicable only for pools configured with Windows nodes (that is, created with cloudServiceConfiguration, or with virtualMachineConfiguration using a Windows image reference). For Linux compute nodes, the certificates are stored in a directory inside the task working directory and an environment variable AZ_BATCH_CERTIFICATES_DIR is supplied to the task to query for this location. For certificates with visibility of 'remoteUser', a 'certs' directory is created in the user's home directory (e.g., /home/{user-name}/certs) and certificates are placed in that directory. """ CURRENT_USER = "CurrentUser" """Certificates should be installed to the CurrentUser certificate store.""" LOCAL_MACHINE = "LocalMachine" """Certificates should be installed to the LocalMachine certificate store.""" class CertificateVisibility(str, Enum, metaclass=CaseInsensitiveEnumMeta): """CertificateVisibility.""" START_TASK = "StartTask" """The certificate should be visible to the user account under which the start task is run. Note #: that if AutoUser Scope is Pool for both the StartTask and a Task, this certificate will be #: visible to the Task as well.""" TASK = "Task" """The certificate should be visible to the user accounts under which job tasks are run.""" REMOTE_USER = "RemoteUser" """The certificate should be visible to the user accounts under which users remotely access the #: node.""" class ComputeNodeDeallocationOption(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Determines what to do with a node and its running task(s) after it has been selected for deallocation. """ REQUEUE = "Requeue" """Terminate running task processes and requeue the tasks. The tasks will run again when a node is #: available. Remove nodes as soon as tasks have been terminated.""" TERMINATE = "Terminate" """Terminate running tasks. The tasks will be completed with failureInfo indicating that they were #: terminated, and will not run again. Remove nodes as soon as tasks have been terminated.""" TASK_COMPLETION = "TaskCompletion" """Allow currently running tasks to complete. Schedule no new tasks while waiting. Remove nodes #: when all tasks have completed.""" RETAINED_DATA = "RetainedData" """Allow currently running tasks to complete, then wait for all task data retention periods to #: expire. Schedule no new tasks while waiting. Remove nodes when all task retention periods have #: expired.""" class ComputeNodeFillType(str, Enum, metaclass=CaseInsensitiveEnumMeta): """How tasks should be distributed across compute nodes.""" SPREAD = "Spread" """Tasks should be assigned evenly across all nodes in the pool.""" PACK = "Pack" """As many tasks as possible (taskSlotsPerNode) should be assigned to each node in the pool before #: any tasks are assigned to the next node in the pool.""" class ContainerType(str, Enum, metaclass=CaseInsensitiveEnumMeta): """The container technology to be used.""" DOCKER_COMPATIBLE = "DockerCompatible" """A Docker compatible container technology will be used to launch the containers.""" CRI_COMPATIBLE = "CriCompatible" """A CRI based technology will be used to launch the containers.""" class ContainerWorkingDirectory(str, Enum, metaclass=CaseInsensitiveEnumMeta): """A flag to indicate where the container task working directory is. The default is 'taskWorkingDirectory'. """ TASK_WORKING_DIRECTORY = "TaskWorkingDirectory" """Use the standard Batch service task working directory, which will contain the Task resource #: files populated by Batch.""" CONTAINER_IMAGE_DEFAULT = "ContainerImageDefault" """Using container image defined working directory. Beware that this directory will not contain #: the resource files downloaded by Batch.""" class DiskEncryptionTarget(str, Enum, metaclass=CaseInsensitiveEnumMeta): """If omitted, no disks on the compute nodes in the pool will be encrypted.""" OS_DISK = "OsDisk" """The OS Disk on the compute node is encrypted.""" TEMPORARY_DISK = "TemporaryDisk" """The temporary disk on the compute node is encrypted. On Linux this encryption applies to other #: partitions (such as those on mounted data disks) when encryption occurs at boot time.""" class DynamicVNetAssignmentScope(str, Enum, metaclass=CaseInsensitiveEnumMeta): """The scope of dynamic vnet assignment.""" NONE = "none" """No dynamic VNet assignment is enabled.""" JOB = "job" """Dynamic VNet assignment is done per-job. If this value is set, the network configuration subnet #: ID must also be set. This feature requires approval before use, please contact support""" class ElevationLevel(str, Enum, metaclass=CaseInsensitiveEnumMeta): """The elevation level of the user.""" NON_ADMIN = "NonAdmin" """The user is a standard user without elevated access.""" ADMIN = "Admin" """The user is a user with elevated access and operates with full Administrator permissions.""" class EndpointAccessDefaultAction(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Default action for endpoint access. It is only applicable when publicNetworkAccess is enabled.""" ALLOW = "Allow" """Allow client access.""" DENY = "Deny" """Deny client access.""" class InboundEndpointProtocol(str, Enum, metaclass=CaseInsensitiveEnumMeta): """The protocol of the endpoint.""" TCP = "TCP" """Use TCP for the endpoint.""" UDP = "UDP" """Use UDP for the endpoint.""" class InterNodeCommunicationState(str, Enum, metaclass=CaseInsensitiveEnumMeta): """This imposes restrictions on which nodes can be assigned to the pool. Enabling this value can reduce the chance of the requested number of nodes to be allocated in the pool. If not specified, this value defaults to 'Disabled'. """ ENABLED = "Enabled" """Enable network communication between virtual machines.""" DISABLED = "Disabled" """Disable network communication between virtual machines.""" class IPAddressProvisioningType(str, Enum, metaclass=CaseInsensitiveEnumMeta): """The provisioning type for Public IP Addresses for the Batch Pool.""" BATCH_MANAGED = "BatchManaged" """A public IP will be created and managed by Batch. There may be multiple public IPs depending on #: the size of the Pool.""" USER_MANAGED = "UserManaged" """Public IPs are provided by the user and will be used to provision the Compute Nodes.""" NO_PUBLIC_IP_ADDRESSES = "NoPublicIPAddresses" """No public IP Address will be created for the Compute Nodes in the Pool.""" class KeySource(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Type of the key source.""" MICROSOFT_BATCH = "Microsoft.Batch" """Batch creates and manages the encryption keys used to protect the account data.""" MICROSOFT_KEY_VAULT = "Microsoft.KeyVault" """The encryption keys used to protect the account data are stored in an external key vault. If #: this is set then the Batch Account identity must be set to ``SystemAssigned`` and a valid Key #: Identifier must also be supplied under the keyVaultProperties.""" class LoginMode(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Specifies login mode for the user. The default value for VirtualMachineConfiguration pools is interactive mode and for CloudServiceConfiguration pools is batch mode. """ BATCH = "Batch" """The LOGON32_LOGON_BATCH Win32 login mode. The batch login mode is recommended for long running #: parallel processes.""" INTERACTIVE = "Interactive" """The LOGON32_LOGON_INTERACTIVE Win32 login mode. Some applications require having permissions #: associated with the interactive login mode. If this is the case for an application used in your #: task, then this option is recommended.""" class NameAvailabilityReason(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Gets the reason that a Batch account name could not be used. The Reason element is only returned if NameAvailable is false. """ INVALID = "Invalid" """The requested name is invalid.""" ALREADY_EXISTS = "AlreadyExists" """The requested name is already in use.""" class NetworkSecurityGroupRuleAccess(str, Enum, metaclass=CaseInsensitiveEnumMeta): """The action that should be taken for a specified IP address, subnet range or tag.""" ALLOW = "Allow" """Allow access.""" DENY = "Deny" """Deny access.""" class NodeCommunicationMode(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Determines how a pool communicates with the Batch service.""" DEFAULT = "Default" """The node communication mode is automatically set by the Batch service.""" CLASSIC = "Classic" """Nodes using the Classic communication mode require inbound TCP communication on ports 29876 and #: 29877 from the "BatchNodeManagement.{region}" service tag and outbound TCP communication on #: port 443 to the "Storage.region" and "BatchNodeManagement.{region}" service tags.""" SIMPLIFIED = "Simplified" """Nodes using the Simplified communication mode require outbound TCP communication on port 443 to #: the "BatchNodeManagement.{region}" service tag. No open inbound ports are required.""" class NodePlacementPolicyType(str, Enum, metaclass=CaseInsensitiveEnumMeta): """The default value is regional.""" REGIONAL = "Regional" """All nodes in the pool will be allocated in the same region.""" ZONAL = "Zonal" """Nodes in the pool will be spread across different zones with best effort balancing.""" class PackageState(str, Enum, metaclass=CaseInsensitiveEnumMeta): """The current state of the application package.""" PENDING = "Pending" """The application package has been created but has not yet been activated.""" ACTIVE = "Active" """The application package is ready for use.""" class PoolAllocationMode(str, Enum, metaclass=CaseInsensitiveEnumMeta): """The allocation mode for creating pools in the Batch account.""" BATCH_SERVICE = "BatchService" """Pools will be allocated in subscriptions owned by the Batch service.""" USER_SUBSCRIPTION = "UserSubscription" """Pools will be allocated in a subscription owned by the user.""" class PoolIdentityType(str, Enum, metaclass=CaseInsensitiveEnumMeta): """The type of identity used for the Batch Pool.""" USER_ASSIGNED = "UserAssigned" """Batch pool has user assigned identities with it.""" NONE = "None" """Batch pool has no identity associated with it. Setting ``None`` in update pool will remove #: existing identities.""" class PoolProvisioningState(str, Enum, metaclass=CaseInsensitiveEnumMeta): """The current state of the pool.""" SUCCEEDED = "Succeeded" """The pool is available to run tasks subject to the availability of compute nodes.""" DELETING = "Deleting" """The user has requested that the pool be deleted, but the delete operation has not yet #: completed.""" class PrivateEndpointConnectionProvisioningState(str, Enum, metaclass=CaseInsensitiveEnumMeta): """The provisioning state of the private endpoint connection.""" CREATING = "Creating" """The connection is creating.""" UPDATING = "Updating" """The user has requested that the connection status be updated, but the update operation has not #: yet completed. You may not reference the connection when connecting the Batch account.""" DELETING = "Deleting" """The connection is deleting.""" SUCCEEDED = "Succeeded" """The connection status is final and is ready for use if Status is Approved.""" FAILED = "Failed" """The user requested that the connection be updated and it failed. You may retry the update #: operation.""" CANCELLED = "Cancelled" """The user has cancelled the connection creation.""" class PrivateLinkServiceConnectionStatus(str, Enum, metaclass=CaseInsensitiveEnumMeta): """The status of the Batch private endpoint connection.""" APPROVED = "Approved" """The private endpoint connection is approved and can be used to access Batch account""" PENDING = "Pending" """The private endpoint connection is pending and cannot be used to access Batch account""" REJECTED = "Rejected" """The private endpoint connection is rejected and cannot be used to access Batch account""" DISCONNECTED = "Disconnected" """The private endpoint connection is disconnected and cannot be used to access Batch account""" class ProvisioningState(str, Enum, metaclass=CaseInsensitiveEnumMeta): """The provisioned state of the resource.""" INVALID = "Invalid" """The account is in an invalid state.""" CREATING = "Creating" """The account is being created.""" DELETING = "Deleting" """The account is being deleted.""" SUCCEEDED = "Succeeded" """The account has been created and is ready for use.""" FAILED = "Failed" """The last operation for the account is failed.""" CANCELLED = "Cancelled" """The last operation for the account is cancelled.""" class PublicNetworkAccessType(str, Enum, metaclass=CaseInsensitiveEnumMeta): """The network access type for operating on the resources in the Batch account.""" ENABLED = "Enabled" """Enables connectivity to Azure Batch through public DNS.""" DISABLED = "Disabled" """Disables public connectivity and enables private connectivity to Azure Batch Service through #: private endpoint resource.""" class ResourceIdentityType(str, Enum, metaclass=CaseInsensitiveEnumMeta): """The type of identity used for the Batch account.""" SYSTEM_ASSIGNED = "SystemAssigned" """Batch account has a system assigned identity with it.""" USER_ASSIGNED = "UserAssigned" """Batch account has user assigned identities with it.""" NONE = "None" """Batch account has no identity associated with it. Setting ``None`` in update account will #: remove existing identities.""" class StorageAccountType(str, Enum, metaclass=CaseInsensitiveEnumMeta): """The storage account type for use in creating data disks.""" STANDARD_LRS = "Standard_LRS" """The data disk should use standard locally redundant storage.""" PREMIUM_LRS = "Premium_LRS" """The data disk should use premium locally redundant storage."""
azure-mgmt-batch
/azure_mgmt_batch-17.1.0-py3-none-any.whl/azure/mgmt/batch/models/_batch_management_client_enums.py
_batch_management_client_enums.py
from enum import Enum from azure.core import CaseInsensitiveEnumMeta class AccountKeyType(str, Enum, metaclass=CaseInsensitiveEnumMeta): """The type of account key to regenerate.""" PRIMARY = "Primary" """The primary account key.""" SECONDARY = "Secondary" """The secondary account key.""" class AllocationState(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Whether the pool is resizing.""" STEADY = "Steady" """The pool is not resizing. There are no changes to the number of nodes in the pool in progress. #: A pool enters this state when it is created and when no operations are being performed on the #: pool to change the number of nodes.""" RESIZING = "Resizing" """The pool is resizing; that is, compute nodes are being added to or removed from the pool.""" STOPPING = "Stopping" """The pool was resizing, but the user has requested that the resize be stopped, but the stop #: request has not yet been completed.""" class AuthenticationMode(str, Enum, metaclass=CaseInsensitiveEnumMeta): """The authentication mode for the Batch account.""" SHARED_KEY = "SharedKey" """The authentication mode using shared keys.""" AAD = "AAD" """The authentication mode using Azure Active Directory.""" TASK_AUTHENTICATION_TOKEN = "TaskAuthenticationToken" """The authentication mode using task authentication tokens.""" class AutoStorageAuthenticationMode(str, Enum, metaclass=CaseInsensitiveEnumMeta): """The authentication mode which the Batch service will use to manage the auto-storage account.""" STORAGE_KEYS = "StorageKeys" """The Batch service will authenticate requests to auto-storage using storage account keys.""" BATCH_ACCOUNT_MANAGED_IDENTITY = "BatchAccountManagedIdentity" """The Batch service will authenticate requests to auto-storage using the managed identity #: assigned to the Batch account.""" class AutoUserScope(str, Enum, metaclass=CaseInsensitiveEnumMeta): """The default value is Pool. If the pool is running Windows a value of Task should be specified if stricter isolation between tasks is required. For example, if the task mutates the registry in a way which could impact other tasks, or if certificates have been specified on the pool which should not be accessible by normal tasks but should be accessible by start tasks. """ TASK = "Task" """Specifies that the service should create a new user for the task.""" POOL = "Pool" """Specifies that the task runs as the common auto user account which is created on every node in #: a pool.""" class CachingType(str, Enum, metaclass=CaseInsensitiveEnumMeta): """The type of caching to enable for the disk.""" NONE = "None" """The caching mode for the disk is not enabled.""" READ_ONLY = "ReadOnly" """The caching mode for the disk is read only.""" READ_WRITE = "ReadWrite" """The caching mode for the disk is read and write.""" class CertificateFormat(str, Enum, metaclass=CaseInsensitiveEnumMeta): """The format of the certificate - either Pfx or Cer. If omitted, the default is Pfx.""" PFX = "Pfx" """The certificate is a PFX (PKCS#12) formatted certificate or certificate chain.""" CER = "Cer" """The certificate is a base64-encoded X.509 certificate.""" class CertificateProvisioningState(str, Enum, metaclass=CaseInsensitiveEnumMeta): """CertificateProvisioningState.""" SUCCEEDED = "Succeeded" """The certificate is available for use in pools.""" DELETING = "Deleting" """The user has requested that the certificate be deleted, but the delete operation has not yet #: completed. You may not reference the certificate when creating or updating pools.""" FAILED = "Failed" """The user requested that the certificate be deleted, but there are pools that still have #: references to the certificate, or it is still installed on one or more compute nodes. (The #: latter can occur if the certificate has been removed from the pool, but the node has not yet #: restarted. Nodes refresh their certificates only when they restart.) You may use the cancel #: certificate delete operation to cancel the delete, or the delete certificate operation to retry #: the delete.""" class CertificateStoreLocation(str, Enum, metaclass=CaseInsensitiveEnumMeta): """The default value is currentUser. This property is applicable only for pools configured with Windows nodes (that is, created with cloudServiceConfiguration, or with virtualMachineConfiguration using a Windows image reference). For Linux compute nodes, the certificates are stored in a directory inside the task working directory and an environment variable AZ_BATCH_CERTIFICATES_DIR is supplied to the task to query for this location. For certificates with visibility of 'remoteUser', a 'certs' directory is created in the user's home directory (e.g., /home/{user-name}/certs) and certificates are placed in that directory. """ CURRENT_USER = "CurrentUser" """Certificates should be installed to the CurrentUser certificate store.""" LOCAL_MACHINE = "LocalMachine" """Certificates should be installed to the LocalMachine certificate store.""" class CertificateVisibility(str, Enum, metaclass=CaseInsensitiveEnumMeta): """CertificateVisibility.""" START_TASK = "StartTask" """The certificate should be visible to the user account under which the start task is run. Note #: that if AutoUser Scope is Pool for both the StartTask and a Task, this certificate will be #: visible to the Task as well.""" TASK = "Task" """The certificate should be visible to the user accounts under which job tasks are run.""" REMOTE_USER = "RemoteUser" """The certificate should be visible to the user accounts under which users remotely access the #: node.""" class ComputeNodeDeallocationOption(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Determines what to do with a node and its running task(s) after it has been selected for deallocation. """ REQUEUE = "Requeue" """Terminate running task processes and requeue the tasks. The tasks will run again when a node is #: available. Remove nodes as soon as tasks have been terminated.""" TERMINATE = "Terminate" """Terminate running tasks. The tasks will be completed with failureInfo indicating that they were #: terminated, and will not run again. Remove nodes as soon as tasks have been terminated.""" TASK_COMPLETION = "TaskCompletion" """Allow currently running tasks to complete. Schedule no new tasks while waiting. Remove nodes #: when all tasks have completed.""" RETAINED_DATA = "RetainedData" """Allow currently running tasks to complete, then wait for all task data retention periods to #: expire. Schedule no new tasks while waiting. Remove nodes when all task retention periods have #: expired.""" class ComputeNodeFillType(str, Enum, metaclass=CaseInsensitiveEnumMeta): """How tasks should be distributed across compute nodes.""" SPREAD = "Spread" """Tasks should be assigned evenly across all nodes in the pool.""" PACK = "Pack" """As many tasks as possible (taskSlotsPerNode) should be assigned to each node in the pool before #: any tasks are assigned to the next node in the pool.""" class ContainerType(str, Enum, metaclass=CaseInsensitiveEnumMeta): """The container technology to be used.""" DOCKER_COMPATIBLE = "DockerCompatible" """A Docker compatible container technology will be used to launch the containers.""" CRI_COMPATIBLE = "CriCompatible" """A CRI based technology will be used to launch the containers.""" class ContainerWorkingDirectory(str, Enum, metaclass=CaseInsensitiveEnumMeta): """A flag to indicate where the container task working directory is. The default is 'taskWorkingDirectory'. """ TASK_WORKING_DIRECTORY = "TaskWorkingDirectory" """Use the standard Batch service task working directory, which will contain the Task resource #: files populated by Batch.""" CONTAINER_IMAGE_DEFAULT = "ContainerImageDefault" """Using container image defined working directory. Beware that this directory will not contain #: the resource files downloaded by Batch.""" class DiskEncryptionTarget(str, Enum, metaclass=CaseInsensitiveEnumMeta): """If omitted, no disks on the compute nodes in the pool will be encrypted.""" OS_DISK = "OsDisk" """The OS Disk on the compute node is encrypted.""" TEMPORARY_DISK = "TemporaryDisk" """The temporary disk on the compute node is encrypted. On Linux this encryption applies to other #: partitions (such as those on mounted data disks) when encryption occurs at boot time.""" class DynamicVNetAssignmentScope(str, Enum, metaclass=CaseInsensitiveEnumMeta): """The scope of dynamic vnet assignment.""" NONE = "none" """No dynamic VNet assignment is enabled.""" JOB = "job" """Dynamic VNet assignment is done per-job. If this value is set, the network configuration subnet #: ID must also be set. This feature requires approval before use, please contact support""" class ElevationLevel(str, Enum, metaclass=CaseInsensitiveEnumMeta): """The elevation level of the user.""" NON_ADMIN = "NonAdmin" """The user is a standard user without elevated access.""" ADMIN = "Admin" """The user is a user with elevated access and operates with full Administrator permissions.""" class EndpointAccessDefaultAction(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Default action for endpoint access. It is only applicable when publicNetworkAccess is enabled.""" ALLOW = "Allow" """Allow client access.""" DENY = "Deny" """Deny client access.""" class InboundEndpointProtocol(str, Enum, metaclass=CaseInsensitiveEnumMeta): """The protocol of the endpoint.""" TCP = "TCP" """Use TCP for the endpoint.""" UDP = "UDP" """Use UDP for the endpoint.""" class InterNodeCommunicationState(str, Enum, metaclass=CaseInsensitiveEnumMeta): """This imposes restrictions on which nodes can be assigned to the pool. Enabling this value can reduce the chance of the requested number of nodes to be allocated in the pool. If not specified, this value defaults to 'Disabled'. """ ENABLED = "Enabled" """Enable network communication between virtual machines.""" DISABLED = "Disabled" """Disable network communication between virtual machines.""" class IPAddressProvisioningType(str, Enum, metaclass=CaseInsensitiveEnumMeta): """The provisioning type for Public IP Addresses for the Batch Pool.""" BATCH_MANAGED = "BatchManaged" """A public IP will be created and managed by Batch. There may be multiple public IPs depending on #: the size of the Pool.""" USER_MANAGED = "UserManaged" """Public IPs are provided by the user and will be used to provision the Compute Nodes.""" NO_PUBLIC_IP_ADDRESSES = "NoPublicIPAddresses" """No public IP Address will be created for the Compute Nodes in the Pool.""" class KeySource(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Type of the key source.""" MICROSOFT_BATCH = "Microsoft.Batch" """Batch creates and manages the encryption keys used to protect the account data.""" MICROSOFT_KEY_VAULT = "Microsoft.KeyVault" """The encryption keys used to protect the account data are stored in an external key vault. If #: this is set then the Batch Account identity must be set to ``SystemAssigned`` and a valid Key #: Identifier must also be supplied under the keyVaultProperties.""" class LoginMode(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Specifies login mode for the user. The default value for VirtualMachineConfiguration pools is interactive mode and for CloudServiceConfiguration pools is batch mode. """ BATCH = "Batch" """The LOGON32_LOGON_BATCH Win32 login mode. The batch login mode is recommended for long running #: parallel processes.""" INTERACTIVE = "Interactive" """The LOGON32_LOGON_INTERACTIVE Win32 login mode. Some applications require having permissions #: associated with the interactive login mode. If this is the case for an application used in your #: task, then this option is recommended.""" class NameAvailabilityReason(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Gets the reason that a Batch account name could not be used. The Reason element is only returned if NameAvailable is false. """ INVALID = "Invalid" """The requested name is invalid.""" ALREADY_EXISTS = "AlreadyExists" """The requested name is already in use.""" class NetworkSecurityGroupRuleAccess(str, Enum, metaclass=CaseInsensitiveEnumMeta): """The action that should be taken for a specified IP address, subnet range or tag.""" ALLOW = "Allow" """Allow access.""" DENY = "Deny" """Deny access.""" class NodeCommunicationMode(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Determines how a pool communicates with the Batch service.""" DEFAULT = "Default" """The node communication mode is automatically set by the Batch service.""" CLASSIC = "Classic" """Nodes using the Classic communication mode require inbound TCP communication on ports 29876 and #: 29877 from the "BatchNodeManagement.{region}" service tag and outbound TCP communication on #: port 443 to the "Storage.region" and "BatchNodeManagement.{region}" service tags.""" SIMPLIFIED = "Simplified" """Nodes using the Simplified communication mode require outbound TCP communication on port 443 to #: the "BatchNodeManagement.{region}" service tag. No open inbound ports are required.""" class NodePlacementPolicyType(str, Enum, metaclass=CaseInsensitiveEnumMeta): """The default value is regional.""" REGIONAL = "Regional" """All nodes in the pool will be allocated in the same region.""" ZONAL = "Zonal" """Nodes in the pool will be spread across different zones with best effort balancing.""" class PackageState(str, Enum, metaclass=CaseInsensitiveEnumMeta): """The current state of the application package.""" PENDING = "Pending" """The application package has been created but has not yet been activated.""" ACTIVE = "Active" """The application package is ready for use.""" class PoolAllocationMode(str, Enum, metaclass=CaseInsensitiveEnumMeta): """The allocation mode for creating pools in the Batch account.""" BATCH_SERVICE = "BatchService" """Pools will be allocated in subscriptions owned by the Batch service.""" USER_SUBSCRIPTION = "UserSubscription" """Pools will be allocated in a subscription owned by the user.""" class PoolIdentityType(str, Enum, metaclass=CaseInsensitiveEnumMeta): """The type of identity used for the Batch Pool.""" USER_ASSIGNED = "UserAssigned" """Batch pool has user assigned identities with it.""" NONE = "None" """Batch pool has no identity associated with it. Setting ``None`` in update pool will remove #: existing identities.""" class PoolProvisioningState(str, Enum, metaclass=CaseInsensitiveEnumMeta): """The current state of the pool.""" SUCCEEDED = "Succeeded" """The pool is available to run tasks subject to the availability of compute nodes.""" DELETING = "Deleting" """The user has requested that the pool be deleted, but the delete operation has not yet #: completed.""" class PrivateEndpointConnectionProvisioningState(str, Enum, metaclass=CaseInsensitiveEnumMeta): """The provisioning state of the private endpoint connection.""" CREATING = "Creating" """The connection is creating.""" UPDATING = "Updating" """The user has requested that the connection status be updated, but the update operation has not #: yet completed. You may not reference the connection when connecting the Batch account.""" DELETING = "Deleting" """The connection is deleting.""" SUCCEEDED = "Succeeded" """The connection status is final and is ready for use if Status is Approved.""" FAILED = "Failed" """The user requested that the connection be updated and it failed. You may retry the update #: operation.""" CANCELLED = "Cancelled" """The user has cancelled the connection creation.""" class PrivateLinkServiceConnectionStatus(str, Enum, metaclass=CaseInsensitiveEnumMeta): """The status of the Batch private endpoint connection.""" APPROVED = "Approved" """The private endpoint connection is approved and can be used to access Batch account""" PENDING = "Pending" """The private endpoint connection is pending and cannot be used to access Batch account""" REJECTED = "Rejected" """The private endpoint connection is rejected and cannot be used to access Batch account""" DISCONNECTED = "Disconnected" """The private endpoint connection is disconnected and cannot be used to access Batch account""" class ProvisioningState(str, Enum, metaclass=CaseInsensitiveEnumMeta): """The provisioned state of the resource.""" INVALID = "Invalid" """The account is in an invalid state.""" CREATING = "Creating" """The account is being created.""" DELETING = "Deleting" """The account is being deleted.""" SUCCEEDED = "Succeeded" """The account has been created and is ready for use.""" FAILED = "Failed" """The last operation for the account is failed.""" CANCELLED = "Cancelled" """The last operation for the account is cancelled.""" class PublicNetworkAccessType(str, Enum, metaclass=CaseInsensitiveEnumMeta): """The network access type for operating on the resources in the Batch account.""" ENABLED = "Enabled" """Enables connectivity to Azure Batch through public DNS.""" DISABLED = "Disabled" """Disables public connectivity and enables private connectivity to Azure Batch Service through #: private endpoint resource.""" class ResourceIdentityType(str, Enum, metaclass=CaseInsensitiveEnumMeta): """The type of identity used for the Batch account.""" SYSTEM_ASSIGNED = "SystemAssigned" """Batch account has a system assigned identity with it.""" USER_ASSIGNED = "UserAssigned" """Batch account has user assigned identities with it.""" NONE = "None" """Batch account has no identity associated with it. Setting ``None`` in update account will #: remove existing identities.""" class StorageAccountType(str, Enum, metaclass=CaseInsensitiveEnumMeta): """The storage account type for use in creating data disks.""" STANDARD_LRS = "Standard_LRS" """The data disk should use standard locally redundant storage.""" PREMIUM_LRS = "Premium_LRS" """The data disk should use premium locally redundant storage."""
0.894208
0.354321
from ._models_py3 import ActivateApplicationPackageParameters from ._models_py3 import Application from ._models_py3 import ApplicationPackage from ._models_py3 import ApplicationPackageReference from ._models_py3 import AutoScaleRun from ._models_py3 import AutoScaleRunError from ._models_py3 import AutoScaleSettings from ._models_py3 import AutoStorageBaseProperties from ._models_py3 import AutoStorageProperties from ._models_py3 import AutoUserSpecification from ._models_py3 import AzureBlobFileSystemConfiguration from ._models_py3 import AzureFileShareConfiguration from ._models_py3 import BatchAccount from ._models_py3 import BatchAccountCreateParameters from ._models_py3 import BatchAccountIdentity from ._models_py3 import BatchAccountKeys from ._models_py3 import BatchAccountListResult from ._models_py3 import BatchAccountRegenerateKeyParameters from ._models_py3 import BatchAccountUpdateParameters from ._models_py3 import BatchLocationQuota from ._models_py3 import BatchPoolIdentity from ._models_py3 import CIFSMountConfiguration from ._models_py3 import Certificate from ._models_py3 import CertificateBaseProperties from ._models_py3 import CertificateCreateOrUpdateParameters from ._models_py3 import CertificateCreateOrUpdateProperties from ._models_py3 import CertificateProperties from ._models_py3 import CertificateReference from ._models_py3 import CheckNameAvailabilityParameters from ._models_py3 import CheckNameAvailabilityResult from ._models_py3 import CloudErrorBody from ._models_py3 import CloudServiceConfiguration from ._models_py3 import ComputeNodeIdentityReference from ._models_py3 import ContainerConfiguration from ._models_py3 import ContainerRegistry from ._models_py3 import DataDisk from ._models_py3 import DeleteCertificateError from ._models_py3 import DeploymentConfiguration from ._models_py3 import DetectorListResult from ._models_py3 import DetectorResponse from ._models_py3 import DiffDiskSettings from ._models_py3 import DiskEncryptionConfiguration from ._models_py3 import EncryptionProperties from ._models_py3 import EndpointAccessProfile from ._models_py3 import EndpointDependency from ._models_py3 import EndpointDetail from ._models_py3 import EnvironmentSetting from ._models_py3 import FixedScaleSettings from ._models_py3 import IPRule from ._models_py3 import ImageReference from ._models_py3 import InboundNatPool from ._models_py3 import KeyVaultProperties from ._models_py3 import KeyVaultReference from ._models_py3 import LinuxUserConfiguration from ._models_py3 import ListApplicationPackagesResult from ._models_py3 import ListApplicationsResult from ._models_py3 import ListCertificatesResult from ._models_py3 import ListPoolsResult from ._models_py3 import ListPrivateEndpointConnectionsResult from ._models_py3 import ListPrivateLinkResourcesResult from ._models_py3 import MetadataItem from ._models_py3 import MountConfiguration from ._models_py3 import NFSMountConfiguration from ._models_py3 import NetworkConfiguration from ._models_py3 import NetworkProfile from ._models_py3 import NetworkSecurityGroupRule from ._models_py3 import NodePlacementConfiguration from ._models_py3 import OSDisk from ._models_py3 import Operation from ._models_py3 import OperationDisplay from ._models_py3 import OperationListResult from ._models_py3 import OutboundEnvironmentEndpoint from ._models_py3 import OutboundEnvironmentEndpointCollection from ._models_py3 import Pool from ._models_py3 import PoolEndpointConfiguration from ._models_py3 import PrivateEndpoint from ._models_py3 import PrivateEndpointConnection from ._models_py3 import PrivateLinkResource from ._models_py3 import PrivateLinkServiceConnectionState from ._models_py3 import ProxyResource from ._models_py3 import PublicIPAddressConfiguration from ._models_py3 import ResizeError from ._models_py3 import ResizeOperationStatus from ._models_py3 import Resource from ._models_py3 import ResourceFile from ._models_py3 import ScaleSettings from ._models_py3 import SkuCapability from ._models_py3 import StartTask from ._models_py3 import SupportedSku from ._models_py3 import SupportedSkusResult from ._models_py3 import TaskContainerSettings from ._models_py3 import TaskSchedulingPolicy from ._models_py3 import UserAccount from ._models_py3 import UserAssignedIdentities from ._models_py3 import UserIdentity from ._models_py3 import VMExtension from ._models_py3 import VirtualMachineConfiguration from ._models_py3 import VirtualMachineFamilyCoreQuota from ._models_py3 import WindowsConfiguration from ._models_py3 import WindowsUserConfiguration from ._batch_management_client_enums import AccountKeyType from ._batch_management_client_enums import AllocationState from ._batch_management_client_enums import AuthenticationMode from ._batch_management_client_enums import AutoStorageAuthenticationMode from ._batch_management_client_enums import AutoUserScope from ._batch_management_client_enums import CachingType from ._batch_management_client_enums import CertificateFormat from ._batch_management_client_enums import CertificateProvisioningState from ._batch_management_client_enums import CertificateStoreLocation from ._batch_management_client_enums import CertificateVisibility from ._batch_management_client_enums import ComputeNodeDeallocationOption from ._batch_management_client_enums import ComputeNodeFillType from ._batch_management_client_enums import ContainerType from ._batch_management_client_enums import ContainerWorkingDirectory from ._batch_management_client_enums import DiskEncryptionTarget from ._batch_management_client_enums import DynamicVNetAssignmentScope from ._batch_management_client_enums import ElevationLevel from ._batch_management_client_enums import EndpointAccessDefaultAction from ._batch_management_client_enums import IPAddressProvisioningType from ._batch_management_client_enums import InboundEndpointProtocol from ._batch_management_client_enums import InterNodeCommunicationState from ._batch_management_client_enums import KeySource from ._batch_management_client_enums import LoginMode from ._batch_management_client_enums import NameAvailabilityReason from ._batch_management_client_enums import NetworkSecurityGroupRuleAccess from ._batch_management_client_enums import NodeCommunicationMode from ._batch_management_client_enums import NodePlacementPolicyType from ._batch_management_client_enums import PackageState from ._batch_management_client_enums import PoolAllocationMode from ._batch_management_client_enums import PoolIdentityType from ._batch_management_client_enums import PoolProvisioningState from ._batch_management_client_enums import PrivateEndpointConnectionProvisioningState from ._batch_management_client_enums import PrivateLinkServiceConnectionStatus from ._batch_management_client_enums import ProvisioningState from ._batch_management_client_enums import PublicNetworkAccessType from ._batch_management_client_enums import ResourceIdentityType from ._batch_management_client_enums import StorageAccountType from ._patch import __all__ as _patch_all from ._patch import * # pylint: disable=unused-wildcard-import from ._patch import patch_sdk as _patch_sdk __all__ = [ "ActivateApplicationPackageParameters", "Application", "ApplicationPackage", "ApplicationPackageReference", "AutoScaleRun", "AutoScaleRunError", "AutoScaleSettings", "AutoStorageBaseProperties", "AutoStorageProperties", "AutoUserSpecification", "AzureBlobFileSystemConfiguration", "AzureFileShareConfiguration", "BatchAccount", "BatchAccountCreateParameters", "BatchAccountIdentity", "BatchAccountKeys", "BatchAccountListResult", "BatchAccountRegenerateKeyParameters", "BatchAccountUpdateParameters", "BatchLocationQuota", "BatchPoolIdentity", "CIFSMountConfiguration", "Certificate", "CertificateBaseProperties", "CertificateCreateOrUpdateParameters", "CertificateCreateOrUpdateProperties", "CertificateProperties", "CertificateReference", "CheckNameAvailabilityParameters", "CheckNameAvailabilityResult", "CloudErrorBody", "CloudServiceConfiguration", "ComputeNodeIdentityReference", "ContainerConfiguration", "ContainerRegistry", "DataDisk", "DeleteCertificateError", "DeploymentConfiguration", "DetectorListResult", "DetectorResponse", "DiffDiskSettings", "DiskEncryptionConfiguration", "EncryptionProperties", "EndpointAccessProfile", "EndpointDependency", "EndpointDetail", "EnvironmentSetting", "FixedScaleSettings", "IPRule", "ImageReference", "InboundNatPool", "KeyVaultProperties", "KeyVaultReference", "LinuxUserConfiguration", "ListApplicationPackagesResult", "ListApplicationsResult", "ListCertificatesResult", "ListPoolsResult", "ListPrivateEndpointConnectionsResult", "ListPrivateLinkResourcesResult", "MetadataItem", "MountConfiguration", "NFSMountConfiguration", "NetworkConfiguration", "NetworkProfile", "NetworkSecurityGroupRule", "NodePlacementConfiguration", "OSDisk", "Operation", "OperationDisplay", "OperationListResult", "OutboundEnvironmentEndpoint", "OutboundEnvironmentEndpointCollection", "Pool", "PoolEndpointConfiguration", "PrivateEndpoint", "PrivateEndpointConnection", "PrivateLinkResource", "PrivateLinkServiceConnectionState", "ProxyResource", "PublicIPAddressConfiguration", "ResizeError", "ResizeOperationStatus", "Resource", "ResourceFile", "ScaleSettings", "SkuCapability", "StartTask", "SupportedSku", "SupportedSkusResult", "TaskContainerSettings", "TaskSchedulingPolicy", "UserAccount", "UserAssignedIdentities", "UserIdentity", "VMExtension", "VirtualMachineConfiguration", "VirtualMachineFamilyCoreQuota", "WindowsConfiguration", "WindowsUserConfiguration", "AccountKeyType", "AllocationState", "AuthenticationMode", "AutoStorageAuthenticationMode", "AutoUserScope", "CachingType", "CertificateFormat", "CertificateProvisioningState", "CertificateStoreLocation", "CertificateVisibility", "ComputeNodeDeallocationOption", "ComputeNodeFillType", "ContainerType", "ContainerWorkingDirectory", "DiskEncryptionTarget", "DynamicVNetAssignmentScope", "ElevationLevel", "EndpointAccessDefaultAction", "IPAddressProvisioningType", "InboundEndpointProtocol", "InterNodeCommunicationState", "KeySource", "LoginMode", "NameAvailabilityReason", "NetworkSecurityGroupRuleAccess", "NodeCommunicationMode", "NodePlacementPolicyType", "PackageState", "PoolAllocationMode", "PoolIdentityType", "PoolProvisioningState", "PrivateEndpointConnectionProvisioningState", "PrivateLinkServiceConnectionStatus", "ProvisioningState", "PublicNetworkAccessType", "ResourceIdentityType", "StorageAccountType", ] __all__.extend([p for p in _patch_all if p not in __all__]) _patch_sdk()
azure-mgmt-batch
/azure_mgmt_batch-17.1.0-py3-none-any.whl/azure/mgmt/batch/models/__init__.py
__init__.py
from ._models_py3 import ActivateApplicationPackageParameters from ._models_py3 import Application from ._models_py3 import ApplicationPackage from ._models_py3 import ApplicationPackageReference from ._models_py3 import AutoScaleRun from ._models_py3 import AutoScaleRunError from ._models_py3 import AutoScaleSettings from ._models_py3 import AutoStorageBaseProperties from ._models_py3 import AutoStorageProperties from ._models_py3 import AutoUserSpecification from ._models_py3 import AzureBlobFileSystemConfiguration from ._models_py3 import AzureFileShareConfiguration from ._models_py3 import BatchAccount from ._models_py3 import BatchAccountCreateParameters from ._models_py3 import BatchAccountIdentity from ._models_py3 import BatchAccountKeys from ._models_py3 import BatchAccountListResult from ._models_py3 import BatchAccountRegenerateKeyParameters from ._models_py3 import BatchAccountUpdateParameters from ._models_py3 import BatchLocationQuota from ._models_py3 import BatchPoolIdentity from ._models_py3 import CIFSMountConfiguration from ._models_py3 import Certificate from ._models_py3 import CertificateBaseProperties from ._models_py3 import CertificateCreateOrUpdateParameters from ._models_py3 import CertificateCreateOrUpdateProperties from ._models_py3 import CertificateProperties from ._models_py3 import CertificateReference from ._models_py3 import CheckNameAvailabilityParameters from ._models_py3 import CheckNameAvailabilityResult from ._models_py3 import CloudErrorBody from ._models_py3 import CloudServiceConfiguration from ._models_py3 import ComputeNodeIdentityReference from ._models_py3 import ContainerConfiguration from ._models_py3 import ContainerRegistry from ._models_py3 import DataDisk from ._models_py3 import DeleteCertificateError from ._models_py3 import DeploymentConfiguration from ._models_py3 import DetectorListResult from ._models_py3 import DetectorResponse from ._models_py3 import DiffDiskSettings from ._models_py3 import DiskEncryptionConfiguration from ._models_py3 import EncryptionProperties from ._models_py3 import EndpointAccessProfile from ._models_py3 import EndpointDependency from ._models_py3 import EndpointDetail from ._models_py3 import EnvironmentSetting from ._models_py3 import FixedScaleSettings from ._models_py3 import IPRule from ._models_py3 import ImageReference from ._models_py3 import InboundNatPool from ._models_py3 import KeyVaultProperties from ._models_py3 import KeyVaultReference from ._models_py3 import LinuxUserConfiguration from ._models_py3 import ListApplicationPackagesResult from ._models_py3 import ListApplicationsResult from ._models_py3 import ListCertificatesResult from ._models_py3 import ListPoolsResult from ._models_py3 import ListPrivateEndpointConnectionsResult from ._models_py3 import ListPrivateLinkResourcesResult from ._models_py3 import MetadataItem from ._models_py3 import MountConfiguration from ._models_py3 import NFSMountConfiguration from ._models_py3 import NetworkConfiguration from ._models_py3 import NetworkProfile from ._models_py3 import NetworkSecurityGroupRule from ._models_py3 import NodePlacementConfiguration from ._models_py3 import OSDisk from ._models_py3 import Operation from ._models_py3 import OperationDisplay from ._models_py3 import OperationListResult from ._models_py3 import OutboundEnvironmentEndpoint from ._models_py3 import OutboundEnvironmentEndpointCollection from ._models_py3 import Pool from ._models_py3 import PoolEndpointConfiguration from ._models_py3 import PrivateEndpoint from ._models_py3 import PrivateEndpointConnection from ._models_py3 import PrivateLinkResource from ._models_py3 import PrivateLinkServiceConnectionState from ._models_py3 import ProxyResource from ._models_py3 import PublicIPAddressConfiguration from ._models_py3 import ResizeError from ._models_py3 import ResizeOperationStatus from ._models_py3 import Resource from ._models_py3 import ResourceFile from ._models_py3 import ScaleSettings from ._models_py3 import SkuCapability from ._models_py3 import StartTask from ._models_py3 import SupportedSku from ._models_py3 import SupportedSkusResult from ._models_py3 import TaskContainerSettings from ._models_py3 import TaskSchedulingPolicy from ._models_py3 import UserAccount from ._models_py3 import UserAssignedIdentities from ._models_py3 import UserIdentity from ._models_py3 import VMExtension from ._models_py3 import VirtualMachineConfiguration from ._models_py3 import VirtualMachineFamilyCoreQuota from ._models_py3 import WindowsConfiguration from ._models_py3 import WindowsUserConfiguration from ._batch_management_client_enums import AccountKeyType from ._batch_management_client_enums import AllocationState from ._batch_management_client_enums import AuthenticationMode from ._batch_management_client_enums import AutoStorageAuthenticationMode from ._batch_management_client_enums import AutoUserScope from ._batch_management_client_enums import CachingType from ._batch_management_client_enums import CertificateFormat from ._batch_management_client_enums import CertificateProvisioningState from ._batch_management_client_enums import CertificateStoreLocation from ._batch_management_client_enums import CertificateVisibility from ._batch_management_client_enums import ComputeNodeDeallocationOption from ._batch_management_client_enums import ComputeNodeFillType from ._batch_management_client_enums import ContainerType from ._batch_management_client_enums import ContainerWorkingDirectory from ._batch_management_client_enums import DiskEncryptionTarget from ._batch_management_client_enums import DynamicVNetAssignmentScope from ._batch_management_client_enums import ElevationLevel from ._batch_management_client_enums import EndpointAccessDefaultAction from ._batch_management_client_enums import IPAddressProvisioningType from ._batch_management_client_enums import InboundEndpointProtocol from ._batch_management_client_enums import InterNodeCommunicationState from ._batch_management_client_enums import KeySource from ._batch_management_client_enums import LoginMode from ._batch_management_client_enums import NameAvailabilityReason from ._batch_management_client_enums import NetworkSecurityGroupRuleAccess from ._batch_management_client_enums import NodeCommunicationMode from ._batch_management_client_enums import NodePlacementPolicyType from ._batch_management_client_enums import PackageState from ._batch_management_client_enums import PoolAllocationMode from ._batch_management_client_enums import PoolIdentityType from ._batch_management_client_enums import PoolProvisioningState from ._batch_management_client_enums import PrivateEndpointConnectionProvisioningState from ._batch_management_client_enums import PrivateLinkServiceConnectionStatus from ._batch_management_client_enums import ProvisioningState from ._batch_management_client_enums import PublicNetworkAccessType from ._batch_management_client_enums import ResourceIdentityType from ._batch_management_client_enums import StorageAccountType from ._patch import __all__ as _patch_all from ._patch import * # pylint: disable=unused-wildcard-import from ._patch import patch_sdk as _patch_sdk __all__ = [ "ActivateApplicationPackageParameters", "Application", "ApplicationPackage", "ApplicationPackageReference", "AutoScaleRun", "AutoScaleRunError", "AutoScaleSettings", "AutoStorageBaseProperties", "AutoStorageProperties", "AutoUserSpecification", "AzureBlobFileSystemConfiguration", "AzureFileShareConfiguration", "BatchAccount", "BatchAccountCreateParameters", "BatchAccountIdentity", "BatchAccountKeys", "BatchAccountListResult", "BatchAccountRegenerateKeyParameters", "BatchAccountUpdateParameters", "BatchLocationQuota", "BatchPoolIdentity", "CIFSMountConfiguration", "Certificate", "CertificateBaseProperties", "CertificateCreateOrUpdateParameters", "CertificateCreateOrUpdateProperties", "CertificateProperties", "CertificateReference", "CheckNameAvailabilityParameters", "CheckNameAvailabilityResult", "CloudErrorBody", "CloudServiceConfiguration", "ComputeNodeIdentityReference", "ContainerConfiguration", "ContainerRegistry", "DataDisk", "DeleteCertificateError", "DeploymentConfiguration", "DetectorListResult", "DetectorResponse", "DiffDiskSettings", "DiskEncryptionConfiguration", "EncryptionProperties", "EndpointAccessProfile", "EndpointDependency", "EndpointDetail", "EnvironmentSetting", "FixedScaleSettings", "IPRule", "ImageReference", "InboundNatPool", "KeyVaultProperties", "KeyVaultReference", "LinuxUserConfiguration", "ListApplicationPackagesResult", "ListApplicationsResult", "ListCertificatesResult", "ListPoolsResult", "ListPrivateEndpointConnectionsResult", "ListPrivateLinkResourcesResult", "MetadataItem", "MountConfiguration", "NFSMountConfiguration", "NetworkConfiguration", "NetworkProfile", "NetworkSecurityGroupRule", "NodePlacementConfiguration", "OSDisk", "Operation", "OperationDisplay", "OperationListResult", "OutboundEnvironmentEndpoint", "OutboundEnvironmentEndpointCollection", "Pool", "PoolEndpointConfiguration", "PrivateEndpoint", "PrivateEndpointConnection", "PrivateLinkResource", "PrivateLinkServiceConnectionState", "ProxyResource", "PublicIPAddressConfiguration", "ResizeError", "ResizeOperationStatus", "Resource", "ResourceFile", "ScaleSettings", "SkuCapability", "StartTask", "SupportedSku", "SupportedSkusResult", "TaskContainerSettings", "TaskSchedulingPolicy", "UserAccount", "UserAssignedIdentities", "UserIdentity", "VMExtension", "VirtualMachineConfiguration", "VirtualMachineFamilyCoreQuota", "WindowsConfiguration", "WindowsUserConfiguration", "AccountKeyType", "AllocationState", "AuthenticationMode", "AutoStorageAuthenticationMode", "AutoUserScope", "CachingType", "CertificateFormat", "CertificateProvisioningState", "CertificateStoreLocation", "CertificateVisibility", "ComputeNodeDeallocationOption", "ComputeNodeFillType", "ContainerType", "ContainerWorkingDirectory", "DiskEncryptionTarget", "DynamicVNetAssignmentScope", "ElevationLevel", "EndpointAccessDefaultAction", "IPAddressProvisioningType", "InboundEndpointProtocol", "InterNodeCommunicationState", "KeySource", "LoginMode", "NameAvailabilityReason", "NetworkSecurityGroupRuleAccess", "NodeCommunicationMode", "NodePlacementPolicyType", "PackageState", "PoolAllocationMode", "PoolIdentityType", "PoolProvisioningState", "PrivateEndpointConnectionProvisioningState", "PrivateLinkServiceConnectionStatus", "ProvisioningState", "PublicNetworkAccessType", "ResourceIdentityType", "StorageAccountType", ] __all__.extend([p for p in _patch_all if p not in __all__]) _patch_sdk()
0.571169
0.068944
# Microsoft Azure SDK for Python This is the Microsoft Azure Batchai Management Client Library. This package has been tested with Python 2.7, 3.5, 3.6, 3.7 and 3.8. For a more complete view of Azure libraries, see the [azure sdk python release](https://aka.ms/azsdk/python/all). # Usage To learn how to use this package, see the [quickstart guide](https://aka.ms/azsdk/python/mgmt) For docs and references, see [Python SDK References](https://docs.microsoft.com/python/api/overview/azure/) Code samples for this package can be found at [Batchai Management](https://docs.microsoft.com/samples/browse/?languages=python&term=Getting%20started%20-%20Managing&terms=Getting%20started%20-%20Managing) on docs.microsoft.com. Additional code samples for different Azure services are available at [Samples Repo](https://aka.ms/azsdk/python/mgmt/samples) # Provide Feedback If you encounter any bugs or have suggestions, please file an issue in the [Issues](https://github.com/Azure/azure-sdk-for-python/issues) section of the project. ![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-python%2Fazure-mgmt-batchai%2FREADME.png)
azure-mgmt-batchai
/azure-mgmt-batchai-7.0.0b1.zip/azure-mgmt-batchai-7.0.0b1/README.md
README.md
# Microsoft Azure SDK for Python This is the Microsoft Azure Batchai Management Client Library. This package has been tested with Python 2.7, 3.5, 3.6, 3.7 and 3.8. For a more complete view of Azure libraries, see the [azure sdk python release](https://aka.ms/azsdk/python/all). # Usage To learn how to use this package, see the [quickstart guide](https://aka.ms/azsdk/python/mgmt) For docs and references, see [Python SDK References](https://docs.microsoft.com/python/api/overview/azure/) Code samples for this package can be found at [Batchai Management](https://docs.microsoft.com/samples/browse/?languages=python&term=Getting%20started%20-%20Managing&terms=Getting%20started%20-%20Managing) on docs.microsoft.com. Additional code samples for different Azure services are available at [Samples Repo](https://aka.ms/azsdk/python/mgmt/samples) # Provide Feedback If you encounter any bugs or have suggestions, please file an issue in the [Issues](https://github.com/Azure/azure-sdk-for-python/issues) section of the project. ![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-python%2Fazure-mgmt-batchai%2FREADME.png)
0.741487
0.623563
# Release History ## 7.0.0b1 (2021-06-02) This is beta preview version. For detailed changelog please refer to equivalent stable version 2.0.0(https://pypi.org/project/azure-mgmt-batchai/2.0.0/) This version uses a next-generation code generator that introduces important breaking changes, but also important new features (like unified authentication and async programming). **General breaking changes** - Credential system has been completly revamped: - `azure.common.credentials` or `msrestazure.azure_active_directory` instances are no longer supported, use the `azure-identity` classes instead: https://pypi.org/project/azure-identity/ - `credentials` parameter has been renamed `credential` - The `config` attribute no longer exists on a client, configuration should be passed as kwarg. Example: `MyClient(credential, subscription_id, enable_logging=True)`. For a complete set of supported options, see the [parameters accept in init documentation of azure-core](https://github.com/Azure/azure-sdk-for-python/blob/master/sdk/core/azure-core/CLIENT_LIBRARY_DEVELOPER.md#available-policies) - You can't import a `version` module anymore, use `__version__` instead - Operations that used to return a `msrest.polling.LROPoller` now returns a `azure.core.polling.LROPoller` and are prefixed with `begin_`. - Exceptions tree have been simplified and most exceptions are now `azure.core.exceptions.HttpResponseError` (`CloudError` has been removed). - Most of the operation kwarg have changed. Some of the most noticeable: - `raw` has been removed. Equivalent feature can be found using `cls`, a callback that will give access to internal HTTP response for advanced user - For a complete set of supported options, see the [parameters accept in Request documentation of azure-core](https://github.com/Azure/azure-sdk-for-python/blob/master/sdk/core/azure-core/CLIENT_LIBRARY_DEVELOPER.md#available-policies) **General new features** - Type annotations support using `typing`. SDKs are mypy ready. - This client has now stable and official support for async. Check the `aio` namespace of your package to find the async client. - This client now support natively tracing library like OpenCensus or OpenTelemetry. See this [tracing quickstart](https://github.com/Azure/azure-sdk-for-python/tree/master/sdk/core/azure-core-tracing-opentelemetry) for an overview. ## 2.0.0 (2018-06-07) **Breaking changes** This version uses 2018-05-01 BatchAI API specification which introduced the following braking changes: - Clusters, FileServers must be created under a workspace; - Jobs must be created under an experiment; - Clusters, FileServers and Jobs do not accept location during creation and belong to the same location as the parent workspace; - Clusters, FileServers and Jobs do not support tags; - BatchAIManagementClient.usage renamed to BatchAIManagementClient.usages; - Job priority changed a type from int to an enum; - File.is_directory is replaced with File.file_type; - Job.priority and JobCreateParameters.priority is replaced with scheduling_priority; - Removed unsupported MountSettings.file_server_type attribute; - OutputDirectory.type unsupported attribute removed; - OutputDirectory.create_new attributes removed, BatchAI will always create output directories if they not exist; - SetupTask.run_elevated attribute removed, the setup task is always executed under root. **Features** - Added support to workspaces to group Clusters, FileServers and Experiments and remove limit on number of allocated resources; - Added support for experiment to group jobs and remove limit on number of jobs; - Added support for configuring /dev/shm for jobs which use docker containers; - Added first class support for generic MPI jobs; - Added first class support for Horovod jobs. ## 1.0.1 (2018-04-16) **Bugfixes** - Fix some invalid models in Python 3 - Compatibility of the sdist with wheel 0.31.0 ## 1.0.0 (2018-03-19) **General Breaking changes** This version uses a next-generation code generator that *might* introduce breaking changes. - Model signatures now use only keyword-argument syntax. All positional arguments must be re-written as keyword-arguments. To keep auto-completion in most cases, models are now generated for Python 2 and Python 3. Python 3 uses the "*" syntax for keyword-only arguments. - Enum types now use the "str" mixin (class AzureEnum(str, Enum)) to improve the behavior when unrecognized enum values are encountered. While this is not a breaking change, the distinctions are important, and are documented here: https://docs.python.org/3/library/enum.html#others At a glance: - "is" should not be used at all. - "format" will return the string value, where "%s" string formatting will return `NameOfEnum.stringvalue`. Format syntax should be prefered. - New Long Running Operation: - Return type changes from `msrestazure.azure_operation.AzureOperationPoller` to `msrest.polling.LROPoller`. External API is the same. - Return type is now **always** a `msrest.polling.LROPoller`, regardless of the optional parameters used. - The behavior has changed when using `raw=True`. Instead of returning the initial call result as `ClientRawResponse`, without polling, now this returns an LROPoller. After polling, the final resource will be returned as a `ClientRawResponse`. - New `polling` parameter. The default behavior is `Polling=True` which will poll using ARM algorithm. When `Polling=False`, the response of the initial call will be returned without polling. - `polling` parameter accepts instances of subclasses of `msrest.polling.PollingMethod`. - `add_done_callback` will no longer raise if called after polling is finished, but will instead execute the callback right away. **Features** - added support for job level mounting - added support for environment variables with secret values - added support for performance counters reporting in Azure Application Insights - added support for custom images - added support for pyTorch deep learning framework - added API for usage and limits reporting - added API for listing job files in subdirectories - now user can choose caching type during NFS creation - get cluster now reports a path segment generated for storing start task output logs - get job now reports a path segment generated for job's output directories - renamed EnvironmentSetting to EnvironmentVariable ## 0.2.0 (2017-10-05) * credentials_info property got renamed to credentials. * removed unused class FileServerStatus and Code enum * renamed enums for CachingType and VmPriority * removed 'statuses' attribute on FileServer ## 0.1.0 (2017-10-03) * Initial Release
azure-mgmt-batchai
/azure-mgmt-batchai-7.0.0b1.zip/azure-mgmt-batchai-7.0.0b1/CHANGELOG.md
CHANGELOG.md
# Release History ## 7.0.0b1 (2021-06-02) This is beta preview version. For detailed changelog please refer to equivalent stable version 2.0.0(https://pypi.org/project/azure-mgmt-batchai/2.0.0/) This version uses a next-generation code generator that introduces important breaking changes, but also important new features (like unified authentication and async programming). **General breaking changes** - Credential system has been completly revamped: - `azure.common.credentials` or `msrestazure.azure_active_directory` instances are no longer supported, use the `azure-identity` classes instead: https://pypi.org/project/azure-identity/ - `credentials` parameter has been renamed `credential` - The `config` attribute no longer exists on a client, configuration should be passed as kwarg. Example: `MyClient(credential, subscription_id, enable_logging=True)`. For a complete set of supported options, see the [parameters accept in init documentation of azure-core](https://github.com/Azure/azure-sdk-for-python/blob/master/sdk/core/azure-core/CLIENT_LIBRARY_DEVELOPER.md#available-policies) - You can't import a `version` module anymore, use `__version__` instead - Operations that used to return a `msrest.polling.LROPoller` now returns a `azure.core.polling.LROPoller` and are prefixed with `begin_`. - Exceptions tree have been simplified and most exceptions are now `azure.core.exceptions.HttpResponseError` (`CloudError` has been removed). - Most of the operation kwarg have changed. Some of the most noticeable: - `raw` has been removed. Equivalent feature can be found using `cls`, a callback that will give access to internal HTTP response for advanced user - For a complete set of supported options, see the [parameters accept in Request documentation of azure-core](https://github.com/Azure/azure-sdk-for-python/blob/master/sdk/core/azure-core/CLIENT_LIBRARY_DEVELOPER.md#available-policies) **General new features** - Type annotations support using `typing`. SDKs are mypy ready. - This client has now stable and official support for async. Check the `aio` namespace of your package to find the async client. - This client now support natively tracing library like OpenCensus or OpenTelemetry. See this [tracing quickstart](https://github.com/Azure/azure-sdk-for-python/tree/master/sdk/core/azure-core-tracing-opentelemetry) for an overview. ## 2.0.0 (2018-06-07) **Breaking changes** This version uses 2018-05-01 BatchAI API specification which introduced the following braking changes: - Clusters, FileServers must be created under a workspace; - Jobs must be created under an experiment; - Clusters, FileServers and Jobs do not accept location during creation and belong to the same location as the parent workspace; - Clusters, FileServers and Jobs do not support tags; - BatchAIManagementClient.usage renamed to BatchAIManagementClient.usages; - Job priority changed a type from int to an enum; - File.is_directory is replaced with File.file_type; - Job.priority and JobCreateParameters.priority is replaced with scheduling_priority; - Removed unsupported MountSettings.file_server_type attribute; - OutputDirectory.type unsupported attribute removed; - OutputDirectory.create_new attributes removed, BatchAI will always create output directories if they not exist; - SetupTask.run_elevated attribute removed, the setup task is always executed under root. **Features** - Added support to workspaces to group Clusters, FileServers and Experiments and remove limit on number of allocated resources; - Added support for experiment to group jobs and remove limit on number of jobs; - Added support for configuring /dev/shm for jobs which use docker containers; - Added first class support for generic MPI jobs; - Added first class support for Horovod jobs. ## 1.0.1 (2018-04-16) **Bugfixes** - Fix some invalid models in Python 3 - Compatibility of the sdist with wheel 0.31.0 ## 1.0.0 (2018-03-19) **General Breaking changes** This version uses a next-generation code generator that *might* introduce breaking changes. - Model signatures now use only keyword-argument syntax. All positional arguments must be re-written as keyword-arguments. To keep auto-completion in most cases, models are now generated for Python 2 and Python 3. Python 3 uses the "*" syntax for keyword-only arguments. - Enum types now use the "str" mixin (class AzureEnum(str, Enum)) to improve the behavior when unrecognized enum values are encountered. While this is not a breaking change, the distinctions are important, and are documented here: https://docs.python.org/3/library/enum.html#others At a glance: - "is" should not be used at all. - "format" will return the string value, where "%s" string formatting will return `NameOfEnum.stringvalue`. Format syntax should be prefered. - New Long Running Operation: - Return type changes from `msrestazure.azure_operation.AzureOperationPoller` to `msrest.polling.LROPoller`. External API is the same. - Return type is now **always** a `msrest.polling.LROPoller`, regardless of the optional parameters used. - The behavior has changed when using `raw=True`. Instead of returning the initial call result as `ClientRawResponse`, without polling, now this returns an LROPoller. After polling, the final resource will be returned as a `ClientRawResponse`. - New `polling` parameter. The default behavior is `Polling=True` which will poll using ARM algorithm. When `Polling=False`, the response of the initial call will be returned without polling. - `polling` parameter accepts instances of subclasses of `msrest.polling.PollingMethod`. - `add_done_callback` will no longer raise if called after polling is finished, but will instead execute the callback right away. **Features** - added support for job level mounting - added support for environment variables with secret values - added support for performance counters reporting in Azure Application Insights - added support for custom images - added support for pyTorch deep learning framework - added API for usage and limits reporting - added API for listing job files in subdirectories - now user can choose caching type during NFS creation - get cluster now reports a path segment generated for storing start task output logs - get job now reports a path segment generated for job's output directories - renamed EnvironmentSetting to EnvironmentVariable ## 0.2.0 (2017-10-05) * credentials_info property got renamed to credentials. * removed unused class FileServerStatus and Code enum * renamed enums for CachingType and VmPriority * removed 'statuses' attribute on FileServer ## 0.1.0 (2017-10-03) * Initial Release
0.821223
0.446434
from typing import TYPE_CHECKING from azure.core.configuration import Configuration from azure.core.pipeline import policies from azure.mgmt.core.policies import ARMHttpLoggingPolicy from ._version import VERSION if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from typing import Any from azure.core.credentials import TokenCredential class BatchAIConfiguration(Configuration): """Configuration for BatchAI. Note that all parameters used to create this instance are saved as instance attributes. :param credential: Credential needed for the client to connect to Azure. :type credential: ~azure.core.credentials.TokenCredential :param subscription_id: The subscriptionID for the Azure user. :type subscription_id: str """ def __init__( self, credential, # type: "TokenCredential" subscription_id, # type: str **kwargs # type: Any ): # type: (...) -> None if credential is None: raise ValueError("Parameter 'credential' must not be None.") if subscription_id is None: raise ValueError("Parameter 'subscription_id' must not be None.") super(BatchAIConfiguration, self).__init__(**kwargs) self.credential = credential self.subscription_id = subscription_id self.api_version = "2018-05-01" self.credential_scopes = kwargs.pop('credential_scopes', ['https://management.azure.com/.default']) kwargs.setdefault('sdk_moniker', 'mgmt-batchai/{}'.format(VERSION)) self._configure(**kwargs) def _configure( self, **kwargs # type: Any ): # type: (...) -> None self.user_agent_policy = kwargs.get('user_agent_policy') or policies.UserAgentPolicy(**kwargs) self.headers_policy = kwargs.get('headers_policy') or policies.HeadersPolicy(**kwargs) self.proxy_policy = kwargs.get('proxy_policy') or policies.ProxyPolicy(**kwargs) self.logging_policy = kwargs.get('logging_policy') or policies.NetworkTraceLoggingPolicy(**kwargs) self.http_logging_policy = kwargs.get('http_logging_policy') or ARMHttpLoggingPolicy(**kwargs) self.retry_policy = kwargs.get('retry_policy') or policies.RetryPolicy(**kwargs) self.custom_hook_policy = kwargs.get('custom_hook_policy') or policies.CustomHookPolicy(**kwargs) self.redirect_policy = kwargs.get('redirect_policy') or policies.RedirectPolicy(**kwargs) self.authentication_policy = kwargs.get('authentication_policy') if self.credential and not self.authentication_policy: self.authentication_policy = policies.BearerTokenCredentialPolicy(self.credential, *self.credential_scopes, **kwargs)
azure-mgmt-batchai
/azure-mgmt-batchai-7.0.0b1.zip/azure-mgmt-batchai-7.0.0b1/azure/mgmt/batchai/_configuration.py
_configuration.py
from typing import TYPE_CHECKING from azure.core.configuration import Configuration from azure.core.pipeline import policies from azure.mgmt.core.policies import ARMHttpLoggingPolicy from ._version import VERSION if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from typing import Any from azure.core.credentials import TokenCredential class BatchAIConfiguration(Configuration): """Configuration for BatchAI. Note that all parameters used to create this instance are saved as instance attributes. :param credential: Credential needed for the client to connect to Azure. :type credential: ~azure.core.credentials.TokenCredential :param subscription_id: The subscriptionID for the Azure user. :type subscription_id: str """ def __init__( self, credential, # type: "TokenCredential" subscription_id, # type: str **kwargs # type: Any ): # type: (...) -> None if credential is None: raise ValueError("Parameter 'credential' must not be None.") if subscription_id is None: raise ValueError("Parameter 'subscription_id' must not be None.") super(BatchAIConfiguration, self).__init__(**kwargs) self.credential = credential self.subscription_id = subscription_id self.api_version = "2018-05-01" self.credential_scopes = kwargs.pop('credential_scopes', ['https://management.azure.com/.default']) kwargs.setdefault('sdk_moniker', 'mgmt-batchai/{}'.format(VERSION)) self._configure(**kwargs) def _configure( self, **kwargs # type: Any ): # type: (...) -> None self.user_agent_policy = kwargs.get('user_agent_policy') or policies.UserAgentPolicy(**kwargs) self.headers_policy = kwargs.get('headers_policy') or policies.HeadersPolicy(**kwargs) self.proxy_policy = kwargs.get('proxy_policy') or policies.ProxyPolicy(**kwargs) self.logging_policy = kwargs.get('logging_policy') or policies.NetworkTraceLoggingPolicy(**kwargs) self.http_logging_policy = kwargs.get('http_logging_policy') or ARMHttpLoggingPolicy(**kwargs) self.retry_policy = kwargs.get('retry_policy') or policies.RetryPolicy(**kwargs) self.custom_hook_policy = kwargs.get('custom_hook_policy') or policies.CustomHookPolicy(**kwargs) self.redirect_policy = kwargs.get('redirect_policy') or policies.RedirectPolicy(**kwargs) self.authentication_policy = kwargs.get('authentication_policy') if self.credential and not self.authentication_policy: self.authentication_policy = policies.BearerTokenCredentialPolicy(self.credential, *self.credential_scopes, **kwargs)
0.797517
0.087213
from typing import TYPE_CHECKING from azure.mgmt.core import ARMPipelineClient from msrest import Deserializer, Serializer if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from typing import Any, Optional from azure.core.credentials import TokenCredential from azure.core.pipeline.transport import HttpRequest, HttpResponse from ._configuration import BatchAIConfiguration from .operations import Operations from .operations import UsagesOperations from .operations import WorkspacesOperations from .operations import ExperimentsOperations from .operations import JobsOperations from .operations import FileServersOperations from .operations import ClustersOperations from . import models class BatchAI(object): """The Azure BatchAI Management API. :ivar operations: Operations operations :vartype operations: batch_ai.operations.Operations :ivar usages: UsagesOperations operations :vartype usages: batch_ai.operations.UsagesOperations :ivar workspaces: WorkspacesOperations operations :vartype workspaces: batch_ai.operations.WorkspacesOperations :ivar experiments: ExperimentsOperations operations :vartype experiments: batch_ai.operations.ExperimentsOperations :ivar jobs: JobsOperations operations :vartype jobs: batch_ai.operations.JobsOperations :ivar file_servers: FileServersOperations operations :vartype file_servers: batch_ai.operations.FileServersOperations :ivar clusters: ClustersOperations operations :vartype clusters: batch_ai.operations.ClustersOperations :param credential: Credential needed for the client to connect to Azure. :type credential: ~azure.core.credentials.TokenCredential :param subscription_id: The subscriptionID for the Azure user. :type subscription_id: str :param str base_url: Service URL :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. """ def __init__( self, credential, # type: "TokenCredential" subscription_id, # type: str base_url=None, # type: Optional[str] **kwargs # type: Any ): # type: (...) -> None if not base_url: base_url = 'https://management.azure.com' self._config = BatchAIConfiguration(credential, subscription_id, **kwargs) self._client = ARMPipelineClient(base_url=base_url, config=self._config, **kwargs) client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} self._serialize = Serializer(client_models) self._serialize.client_side_validation = False self._deserialize = Deserializer(client_models) self.operations = Operations( self._client, self._config, self._serialize, self._deserialize) self.usages = UsagesOperations( self._client, self._config, self._serialize, self._deserialize) self.workspaces = WorkspacesOperations( self._client, self._config, self._serialize, self._deserialize) self.experiments = ExperimentsOperations( self._client, self._config, self._serialize, self._deserialize) self.jobs = JobsOperations( self._client, self._config, self._serialize, self._deserialize) self.file_servers = FileServersOperations( self._client, self._config, self._serialize, self._deserialize) self.clusters = ClustersOperations( self._client, self._config, self._serialize, self._deserialize) def _send_request(self, http_request, **kwargs): # type: (HttpRequest, Any) -> HttpResponse """Runs the network request through the client's chained policies. :param http_request: The network request you want to make. Required. :type http_request: ~azure.core.pipeline.transport.HttpRequest :keyword bool stream: Whether the response payload will be streamed. Defaults to True. :return: The response of your network call. Does not do error handling on your response. :rtype: ~azure.core.pipeline.transport.HttpResponse """ path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } http_request.url = self._client.format_url(http_request.url, **path_format_arguments) stream = kwargs.pop("stream", True) pipeline_response = self._client._pipeline.run(http_request, stream=stream, **kwargs) return pipeline_response.http_response def close(self): # type: () -> None self._client.close() def __enter__(self): # type: () -> BatchAI self._client.__enter__() return self def __exit__(self, *exc_details): # type: (Any) -> None self._client.__exit__(*exc_details)
azure-mgmt-batchai
/azure-mgmt-batchai-7.0.0b1.zip/azure-mgmt-batchai-7.0.0b1/azure/mgmt/batchai/_batch_ai.py
_batch_ai.py
from typing import TYPE_CHECKING from azure.mgmt.core import ARMPipelineClient from msrest import Deserializer, Serializer if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from typing import Any, Optional from azure.core.credentials import TokenCredential from azure.core.pipeline.transport import HttpRequest, HttpResponse from ._configuration import BatchAIConfiguration from .operations import Operations from .operations import UsagesOperations from .operations import WorkspacesOperations from .operations import ExperimentsOperations from .operations import JobsOperations from .operations import FileServersOperations from .operations import ClustersOperations from . import models class BatchAI(object): """The Azure BatchAI Management API. :ivar operations: Operations operations :vartype operations: batch_ai.operations.Operations :ivar usages: UsagesOperations operations :vartype usages: batch_ai.operations.UsagesOperations :ivar workspaces: WorkspacesOperations operations :vartype workspaces: batch_ai.operations.WorkspacesOperations :ivar experiments: ExperimentsOperations operations :vartype experiments: batch_ai.operations.ExperimentsOperations :ivar jobs: JobsOperations operations :vartype jobs: batch_ai.operations.JobsOperations :ivar file_servers: FileServersOperations operations :vartype file_servers: batch_ai.operations.FileServersOperations :ivar clusters: ClustersOperations operations :vartype clusters: batch_ai.operations.ClustersOperations :param credential: Credential needed for the client to connect to Azure. :type credential: ~azure.core.credentials.TokenCredential :param subscription_id: The subscriptionID for the Azure user. :type subscription_id: str :param str base_url: Service URL :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. """ def __init__( self, credential, # type: "TokenCredential" subscription_id, # type: str base_url=None, # type: Optional[str] **kwargs # type: Any ): # type: (...) -> None if not base_url: base_url = 'https://management.azure.com' self._config = BatchAIConfiguration(credential, subscription_id, **kwargs) self._client = ARMPipelineClient(base_url=base_url, config=self._config, **kwargs) client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} self._serialize = Serializer(client_models) self._serialize.client_side_validation = False self._deserialize = Deserializer(client_models) self.operations = Operations( self._client, self._config, self._serialize, self._deserialize) self.usages = UsagesOperations( self._client, self._config, self._serialize, self._deserialize) self.workspaces = WorkspacesOperations( self._client, self._config, self._serialize, self._deserialize) self.experiments = ExperimentsOperations( self._client, self._config, self._serialize, self._deserialize) self.jobs = JobsOperations( self._client, self._config, self._serialize, self._deserialize) self.file_servers = FileServersOperations( self._client, self._config, self._serialize, self._deserialize) self.clusters = ClustersOperations( self._client, self._config, self._serialize, self._deserialize) def _send_request(self, http_request, **kwargs): # type: (HttpRequest, Any) -> HttpResponse """Runs the network request through the client's chained policies. :param http_request: The network request you want to make. Required. :type http_request: ~azure.core.pipeline.transport.HttpRequest :keyword bool stream: Whether the response payload will be streamed. Defaults to True. :return: The response of your network call. Does not do error handling on your response. :rtype: ~azure.core.pipeline.transport.HttpResponse """ path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } http_request.url = self._client.format_url(http_request.url, **path_format_arguments) stream = kwargs.pop("stream", True) pipeline_response = self._client._pipeline.run(http_request, stream=stream, **kwargs) return pipeline_response.http_response def close(self): # type: () -> None self._client.close() def __enter__(self): # type: () -> BatchAI self._client.__enter__() return self def __exit__(self, *exc_details): # type: (Any) -> None self._client.__exit__(*exc_details)
0.858155
0.097605
from typing import TYPE_CHECKING import warnings from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpRequest, HttpResponse from azure.core.polling import LROPoller, NoPolling, PollingMethod from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.arm_polling import ARMPolling from .. import models as _models if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar, Union T = TypeVar('T') ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] class ExperimentsOperations(object): """ExperimentsOperations operations. You should not instantiate this class directly. Instead, you should create a Client instance that instantiates it for you and attaches it as an attribute. :ivar models: Alias to model classes used in this operation group. :type models: ~batch_ai.models :param client: Client for service requests. :param config: Configuration of service client. :param serializer: An object model serializer. :param deserializer: An object model deserializer. """ models = _models def __init__(self, client, config, serializer, deserializer): self._client = client self._serialize = serializer self._deserialize = deserializer self._config = config def list_by_workspace( self, resource_group_name, # type: str workspace_name, # type: str experiments_list_by_workspace_options=None, # type: Optional["_models.ExperimentsListByWorkspaceOptions"] **kwargs # type: Any ): # type: (...) -> Iterable["_models.ExperimentListResult"] """Gets a list of Experiments within the specified Workspace. :param resource_group_name: Name of the resource group to which the resource belongs. :type resource_group_name: str :param workspace_name: The name of the workspace. Workspace names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type workspace_name: str :param experiments_list_by_workspace_options: Parameter group. :type experiments_list_by_workspace_options: ~batch_ai.models.ExperimentsListByWorkspaceOptions :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ExperimentListResult or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~batch_ai.models.ExperimentListResult] :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.ExperimentListResult"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) _max_results = None if experiments_list_by_workspace_options is not None: _max_results = experiments_list_by_workspace_options.max_results api_version = "2018-05-01" accept = "application/json" def prepare_request(next_link=None): # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') if not next_link: # Construct URL url = self.list_by_workspace.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', pattern=r'^[-\w\._]+$'), 'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), '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 = {} # type: Dict[str, Any] if _max_results is not None: query_parameters['maxresults'] = self._serialize.query("max_results", _max_results, 'int', maximum=1000, minimum=1) query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') request = self._client.get(url, query_parameters, header_parameters) else: url = next_link query_parameters = {} # type: Dict[str, Any] request = self._client.get(url, query_parameters, header_parameters) return request def extract_data(pipeline_response): deserialized = self._deserialize('ExperimentListResult', pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return ItemPaged( get_next, extract_data ) list_by_workspace.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces/{workspaceName}/experiments'} # type: ignore def _create_initial( self, resource_group_name, # type: str workspace_name, # type: str experiment_name, # type: str **kwargs # type: Any ): # type: (...) -> Optional["_models.Experiment"] cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.Experiment"]] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2018-05-01" accept = "application/json" # Construct URL url = self._create_initial.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', pattern=r'^[-\w\._]+$'), 'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'experimentName': self._serialize.url("experiment_name", experiment_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), '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 = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') request = self._client.put(url, query_parameters, header_parameters) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = None if response.status_code == 200: deserialized = self._deserialize('Experiment', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized _create_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces/{workspaceName}/experiments/{experimentName}'} # type: ignore def begin_create( self, resource_group_name, # type: str workspace_name, # type: str experiment_name, # type: str **kwargs # type: Any ): # type: (...) -> LROPoller["_models.Experiment"] """Creates an Experiment. :param resource_group_name: Name of the resource group to which the resource belongs. :type resource_group_name: str :param workspace_name: The name of the workspace. Workspace names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type workspace_name: str :param experiment_name: The name of the experiment. Experiment names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type experiment_name: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.PollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of LROPoller that returns either Experiment or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~batch_ai.models.Experiment] :raises ~azure.core.exceptions.HttpResponseError: """ polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] cls = kwargs.pop('cls', None) # type: ClsType["_models.Experiment"] lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval ) cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] if cont_token is None: raw_result = self._create_initial( resource_group_name=resource_group_name, workspace_name=workspace_name, experiment_name=experiment_name, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map', None) kwargs.pop('content_type', None) def get_long_running_output(pipeline_response): deserialized = self._deserialize('Experiment', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', pattern=r'^[-\w\._]+$'), 'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'experimentName': self._serialize.url("experiment_name", experiment_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } if polling is True: polling_method = ARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) elif polling is False: polling_method = NoPolling() else: polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output ) else: return LROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_create.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces/{workspaceName}/experiments/{experimentName}'} # type: ignore def _delete_initial( self, resource_group_name, # type: str workspace_name, # type: str experiment_name, # type: str **kwargs # type: Any ): # type: (...) -> None cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2018-05-01" accept = "application/json" # Construct URL url = self._delete_initial.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', pattern=r'^[-\w\._]+$'), 'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'experimentName': self._serialize.url("experiment_name", experiment_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), '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 = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') request = self._client.delete(url, query_parameters, header_parameters) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) _delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces/{workspaceName}/experiments/{experimentName}'} # type: ignore def begin_delete( self, resource_group_name, # type: str workspace_name, # type: str experiment_name, # type: str **kwargs # type: Any ): # type: (...) -> LROPoller[None] """Deletes an Experiment. :param resource_group_name: Name of the resource group to which the resource belongs. :type resource_group_name: str :param workspace_name: The name of the workspace. Workspace names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type workspace_name: str :param experiment_name: The name of the experiment. Experiment names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type experiment_name: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.PollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of LROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[None] :raises ~azure.core.exceptions.HttpResponseError: """ polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] cls = kwargs.pop('cls', None) # type: ClsType[None] lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval ) cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] if cont_token is None: raw_result = self._delete_initial( resource_group_name=resource_group_name, workspace_name=workspace_name, experiment_name=experiment_name, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map', None) kwargs.pop('content_type', None) def get_long_running_output(pipeline_response): if cls: return cls(pipeline_response, None, {}) path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', pattern=r'^[-\w\._]+$'), 'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'experimentName': self._serialize.url("experiment_name", experiment_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } if polling is True: polling_method = ARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) elif polling is False: polling_method = NoPolling() else: polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output ) else: return LROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces/{workspaceName}/experiments/{experimentName}'} # type: ignore def get( self, resource_group_name, # type: str workspace_name, # type: str experiment_name, # type: str **kwargs # type: Any ): # type: (...) -> "_models.Experiment" """Gets information about an Experiment. :param resource_group_name: Name of the resource group to which the resource belongs. :type resource_group_name: str :param workspace_name: The name of the workspace. Workspace names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type workspace_name: str :param experiment_name: The name of the experiment. Experiment names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type experiment_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Experiment, or the result of cls(response) :rtype: ~batch_ai.models.Experiment :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.Experiment"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2018-05-01" accept = "application/json" # Construct URL url = self.get.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', pattern=r'^[-\w\._]+$'), 'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'experimentName': self._serialize.url("experiment_name", experiment_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), '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 = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') request = self._client.get(url, query_parameters, header_parameters) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize('Experiment', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces/{workspaceName}/experiments/{experimentName}'} # type: ignore
azure-mgmt-batchai
/azure-mgmt-batchai-7.0.0b1.zip/azure-mgmt-batchai-7.0.0b1/azure/mgmt/batchai/operations/_experiments_operations.py
_experiments_operations.py
from typing import TYPE_CHECKING import warnings from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpRequest, HttpResponse from azure.core.polling import LROPoller, NoPolling, PollingMethod from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.arm_polling import ARMPolling from .. import models as _models if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar, Union T = TypeVar('T') ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] class ExperimentsOperations(object): """ExperimentsOperations operations. You should not instantiate this class directly. Instead, you should create a Client instance that instantiates it for you and attaches it as an attribute. :ivar models: Alias to model classes used in this operation group. :type models: ~batch_ai.models :param client: Client for service requests. :param config: Configuration of service client. :param serializer: An object model serializer. :param deserializer: An object model deserializer. """ models = _models def __init__(self, client, config, serializer, deserializer): self._client = client self._serialize = serializer self._deserialize = deserializer self._config = config def list_by_workspace( self, resource_group_name, # type: str workspace_name, # type: str experiments_list_by_workspace_options=None, # type: Optional["_models.ExperimentsListByWorkspaceOptions"] **kwargs # type: Any ): # type: (...) -> Iterable["_models.ExperimentListResult"] """Gets a list of Experiments within the specified Workspace. :param resource_group_name: Name of the resource group to which the resource belongs. :type resource_group_name: str :param workspace_name: The name of the workspace. Workspace names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type workspace_name: str :param experiments_list_by_workspace_options: Parameter group. :type experiments_list_by_workspace_options: ~batch_ai.models.ExperimentsListByWorkspaceOptions :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ExperimentListResult or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~batch_ai.models.ExperimentListResult] :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.ExperimentListResult"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) _max_results = None if experiments_list_by_workspace_options is not None: _max_results = experiments_list_by_workspace_options.max_results api_version = "2018-05-01" accept = "application/json" def prepare_request(next_link=None): # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') if not next_link: # Construct URL url = self.list_by_workspace.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', pattern=r'^[-\w\._]+$'), 'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), '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 = {} # type: Dict[str, Any] if _max_results is not None: query_parameters['maxresults'] = self._serialize.query("max_results", _max_results, 'int', maximum=1000, minimum=1) query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') request = self._client.get(url, query_parameters, header_parameters) else: url = next_link query_parameters = {} # type: Dict[str, Any] request = self._client.get(url, query_parameters, header_parameters) return request def extract_data(pipeline_response): deserialized = self._deserialize('ExperimentListResult', pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return ItemPaged( get_next, extract_data ) list_by_workspace.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces/{workspaceName}/experiments'} # type: ignore def _create_initial( self, resource_group_name, # type: str workspace_name, # type: str experiment_name, # type: str **kwargs # type: Any ): # type: (...) -> Optional["_models.Experiment"] cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.Experiment"]] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2018-05-01" accept = "application/json" # Construct URL url = self._create_initial.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', pattern=r'^[-\w\._]+$'), 'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'experimentName': self._serialize.url("experiment_name", experiment_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), '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 = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') request = self._client.put(url, query_parameters, header_parameters) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = None if response.status_code == 200: deserialized = self._deserialize('Experiment', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized _create_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces/{workspaceName}/experiments/{experimentName}'} # type: ignore def begin_create( self, resource_group_name, # type: str workspace_name, # type: str experiment_name, # type: str **kwargs # type: Any ): # type: (...) -> LROPoller["_models.Experiment"] """Creates an Experiment. :param resource_group_name: Name of the resource group to which the resource belongs. :type resource_group_name: str :param workspace_name: The name of the workspace. Workspace names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type workspace_name: str :param experiment_name: The name of the experiment. Experiment names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type experiment_name: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.PollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of LROPoller that returns either Experiment or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~batch_ai.models.Experiment] :raises ~azure.core.exceptions.HttpResponseError: """ polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] cls = kwargs.pop('cls', None) # type: ClsType["_models.Experiment"] lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval ) cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] if cont_token is None: raw_result = self._create_initial( resource_group_name=resource_group_name, workspace_name=workspace_name, experiment_name=experiment_name, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map', None) kwargs.pop('content_type', None) def get_long_running_output(pipeline_response): deserialized = self._deserialize('Experiment', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', pattern=r'^[-\w\._]+$'), 'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'experimentName': self._serialize.url("experiment_name", experiment_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } if polling is True: polling_method = ARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) elif polling is False: polling_method = NoPolling() else: polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output ) else: return LROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_create.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces/{workspaceName}/experiments/{experimentName}'} # type: ignore def _delete_initial( self, resource_group_name, # type: str workspace_name, # type: str experiment_name, # type: str **kwargs # type: Any ): # type: (...) -> None cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2018-05-01" accept = "application/json" # Construct URL url = self._delete_initial.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', pattern=r'^[-\w\._]+$'), 'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'experimentName': self._serialize.url("experiment_name", experiment_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), '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 = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') request = self._client.delete(url, query_parameters, header_parameters) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) _delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces/{workspaceName}/experiments/{experimentName}'} # type: ignore def begin_delete( self, resource_group_name, # type: str workspace_name, # type: str experiment_name, # type: str **kwargs # type: Any ): # type: (...) -> LROPoller[None] """Deletes an Experiment. :param resource_group_name: Name of the resource group to which the resource belongs. :type resource_group_name: str :param workspace_name: The name of the workspace. Workspace names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type workspace_name: str :param experiment_name: The name of the experiment. Experiment names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type experiment_name: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.PollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of LROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[None] :raises ~azure.core.exceptions.HttpResponseError: """ polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] cls = kwargs.pop('cls', None) # type: ClsType[None] lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval ) cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] if cont_token is None: raw_result = self._delete_initial( resource_group_name=resource_group_name, workspace_name=workspace_name, experiment_name=experiment_name, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map', None) kwargs.pop('content_type', None) def get_long_running_output(pipeline_response): if cls: return cls(pipeline_response, None, {}) path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', pattern=r'^[-\w\._]+$'), 'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'experimentName': self._serialize.url("experiment_name", experiment_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } if polling is True: polling_method = ARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) elif polling is False: polling_method = NoPolling() else: polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output ) else: return LROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces/{workspaceName}/experiments/{experimentName}'} # type: ignore def get( self, resource_group_name, # type: str workspace_name, # type: str experiment_name, # type: str **kwargs # type: Any ): # type: (...) -> "_models.Experiment" """Gets information about an Experiment. :param resource_group_name: Name of the resource group to which the resource belongs. :type resource_group_name: str :param workspace_name: The name of the workspace. Workspace names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type workspace_name: str :param experiment_name: The name of the experiment. Experiment names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type experiment_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Experiment, or the result of cls(response) :rtype: ~batch_ai.models.Experiment :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.Experiment"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2018-05-01" accept = "application/json" # Construct URL url = self.get.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', pattern=r'^[-\w\._]+$'), 'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'experimentName': self._serialize.url("experiment_name", experiment_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), '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 = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') request = self._client.get(url, query_parameters, header_parameters) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize('Experiment', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces/{workspaceName}/experiments/{experimentName}'} # type: ignore
0.841826
0.09886
from typing import TYPE_CHECKING import warnings from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpRequest, HttpResponse from azure.core.polling import LROPoller, NoPolling, PollingMethod from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.arm_polling import ARMPolling from .. import models as _models if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar, Union T = TypeVar('T') ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] class JobsOperations(object): """JobsOperations operations. You should not instantiate this class directly. Instead, you should create a Client instance that instantiates it for you and attaches it as an attribute. :ivar models: Alias to model classes used in this operation group. :type models: ~batch_ai.models :param client: Client for service requests. :param config: Configuration of service client. :param serializer: An object model serializer. :param deserializer: An object model deserializer. """ models = _models def __init__(self, client, config, serializer, deserializer): self._client = client self._serialize = serializer self._deserialize = deserializer self._config = config def list_by_experiment( self, resource_group_name, # type: str workspace_name, # type: str experiment_name, # type: str jobs_list_by_experiment_options=None, # type: Optional["_models.JobsListByExperimentOptions"] **kwargs # type: Any ): # type: (...) -> Iterable["_models.JobListResult"] """Gets a list of Jobs within the specified Experiment. :param resource_group_name: Name of the resource group to which the resource belongs. :type resource_group_name: str :param workspace_name: The name of the workspace. Workspace names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type workspace_name: str :param experiment_name: The name of the experiment. Experiment names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type experiment_name: str :param jobs_list_by_experiment_options: Parameter group. :type jobs_list_by_experiment_options: ~batch_ai.models.JobsListByExperimentOptions :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either JobListResult or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~batch_ai.models.JobListResult] :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.JobListResult"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) _max_results = None if jobs_list_by_experiment_options is not None: _max_results = jobs_list_by_experiment_options.max_results api_version = "2018-05-01" accept = "application/json" def prepare_request(next_link=None): # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') if not next_link: # Construct URL url = self.list_by_experiment.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', pattern=r'^[-\w\._]+$'), 'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'experimentName': self._serialize.url("experiment_name", experiment_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), '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 = {} # type: Dict[str, Any] if _max_results is not None: query_parameters['maxresults'] = self._serialize.query("max_results", _max_results, 'int', maximum=1000, minimum=1) query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') request = self._client.get(url, query_parameters, header_parameters) else: url = next_link query_parameters = {} # type: Dict[str, Any] request = self._client.get(url, query_parameters, header_parameters) return request def extract_data(pipeline_response): deserialized = self._deserialize('JobListResult', pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return ItemPaged( get_next, extract_data ) list_by_experiment.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces/{workspaceName}/experiments/{experimentName}/jobs'} # type: ignore def _create_initial( self, resource_group_name, # type: str workspace_name, # type: str experiment_name, # type: str job_name, # type: str parameters, # type: "_models.JobCreateParameters" **kwargs # type: Any ): # type: (...) -> Optional["_models.Job"] cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.Job"]] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2018-05-01" content_type = kwargs.pop("content_type", "application/json") accept = "application/json" # Construct URL url = self._create_initial.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', pattern=r'^[-\w\._]+$'), 'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'experimentName': self._serialize.url("experiment_name", experiment_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'jobName': self._serialize.url("job_name", job_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), '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 = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') body_content_kwargs = {} # type: Dict[str, Any] body_content = self._serialize.body(parameters, 'JobCreateParameters') body_content_kwargs['content'] = body_content request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = None if response.status_code == 200: deserialized = self._deserialize('Job', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized _create_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces/{workspaceName}/experiments/{experimentName}/jobs/{jobName}'} # type: ignore def begin_create( self, resource_group_name, # type: str workspace_name, # type: str experiment_name, # type: str job_name, # type: str parameters, # type: "_models.JobCreateParameters" **kwargs # type: Any ): # type: (...) -> LROPoller["_models.Job"] """Creates a Job in the given Experiment. :param resource_group_name: Name of the resource group to which the resource belongs. :type resource_group_name: str :param workspace_name: The name of the workspace. Workspace names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type workspace_name: str :param experiment_name: The name of the experiment. Experiment names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type experiment_name: str :param job_name: The name of the job within the specified resource group. Job names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type job_name: str :param parameters: The parameters to provide for job creation. :type parameters: ~batch_ai.models.JobCreateParameters :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.PollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of LROPoller that returns either Job or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~batch_ai.models.Job] :raises ~azure.core.exceptions.HttpResponseError: """ polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] cls = kwargs.pop('cls', None) # type: ClsType["_models.Job"] lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval ) cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] if cont_token is None: raw_result = self._create_initial( resource_group_name=resource_group_name, workspace_name=workspace_name, experiment_name=experiment_name, job_name=job_name, parameters=parameters, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map', None) kwargs.pop('content_type', None) def get_long_running_output(pipeline_response): deserialized = self._deserialize('Job', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', pattern=r'^[-\w\._]+$'), 'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'experimentName': self._serialize.url("experiment_name", experiment_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'jobName': self._serialize.url("job_name", job_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } if polling is True: polling_method = ARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) elif polling is False: polling_method = NoPolling() else: polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output ) else: return LROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_create.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces/{workspaceName}/experiments/{experimentName}/jobs/{jobName}'} # type: ignore def _delete_initial( self, resource_group_name, # type: str workspace_name, # type: str experiment_name, # type: str job_name, # type: str **kwargs # type: Any ): # type: (...) -> None cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2018-05-01" accept = "application/json" # Construct URL url = self._delete_initial.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', pattern=r'^[-\w\._]+$'), 'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'experimentName': self._serialize.url("experiment_name", experiment_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'jobName': self._serialize.url("job_name", job_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), '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 = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') request = self._client.delete(url, query_parameters, header_parameters) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) _delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces/{workspaceName}/experiments/{experimentName}/jobs/{jobName}'} # type: ignore def begin_delete( self, resource_group_name, # type: str workspace_name, # type: str experiment_name, # type: str job_name, # type: str **kwargs # type: Any ): # type: (...) -> LROPoller[None] """Deletes a Job. :param resource_group_name: Name of the resource group to which the resource belongs. :type resource_group_name: str :param workspace_name: The name of the workspace. Workspace names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type workspace_name: str :param experiment_name: The name of the experiment. Experiment names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type experiment_name: str :param job_name: The name of the job within the specified resource group. Job names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type job_name: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.PollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of LROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[None] :raises ~azure.core.exceptions.HttpResponseError: """ polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] cls = kwargs.pop('cls', None) # type: ClsType[None] lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval ) cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] if cont_token is None: raw_result = self._delete_initial( resource_group_name=resource_group_name, workspace_name=workspace_name, experiment_name=experiment_name, job_name=job_name, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map', None) kwargs.pop('content_type', None) def get_long_running_output(pipeline_response): if cls: return cls(pipeline_response, None, {}) path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', pattern=r'^[-\w\._]+$'), 'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'experimentName': self._serialize.url("experiment_name", experiment_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'jobName': self._serialize.url("job_name", job_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } if polling is True: polling_method = ARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) elif polling is False: polling_method = NoPolling() else: polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output ) else: return LROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces/{workspaceName}/experiments/{experimentName}/jobs/{jobName}'} # type: ignore def get( self, resource_group_name, # type: str workspace_name, # type: str experiment_name, # type: str job_name, # type: str **kwargs # type: Any ): # type: (...) -> "_models.Job" """Gets information about a Job. :param resource_group_name: Name of the resource group to which the resource belongs. :type resource_group_name: str :param workspace_name: The name of the workspace. Workspace names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type workspace_name: str :param experiment_name: The name of the experiment. Experiment names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type experiment_name: str :param job_name: The name of the job within the specified resource group. Job names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type job_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Job, or the result of cls(response) :rtype: ~batch_ai.models.Job :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.Job"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2018-05-01" accept = "application/json" # Construct URL url = self.get.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', pattern=r'^[-\w\._]+$'), 'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'experimentName': self._serialize.url("experiment_name", experiment_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'jobName': self._serialize.url("job_name", job_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), '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 = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') request = self._client.get(url, query_parameters, header_parameters) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize('Job', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces/{workspaceName}/experiments/{experimentName}/jobs/{jobName}'} # type: ignore def list_output_files( self, resource_group_name, # type: str workspace_name, # type: str experiment_name, # type: str job_name, # type: str jobs_list_output_files_options, # type: "_models.JobsListOutputFilesOptions" **kwargs # type: Any ): # type: (...) -> Iterable["_models.FileListResult"] """List all directories and files inside the given directory of the Job's output directory (if the output directory is on Azure File Share or Azure Storage Container). :param resource_group_name: Name of the resource group to which the resource belongs. :type resource_group_name: str :param workspace_name: The name of the workspace. Workspace names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type workspace_name: str :param experiment_name: The name of the experiment. Experiment names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type experiment_name: str :param job_name: The name of the job within the specified resource group. Job names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type job_name: str :param jobs_list_output_files_options: Parameter group. :type jobs_list_output_files_options: ~batch_ai.models.JobsListOutputFilesOptions :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either FileListResult or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~batch_ai.models.FileListResult] :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.FileListResult"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) _outputdirectoryid = None _directory = None _linkexpiryinminutes = None _max_results = None if jobs_list_output_files_options is not None: _outputdirectoryid = jobs_list_output_files_options.outputdirectoryid _directory = jobs_list_output_files_options.directory _linkexpiryinminutes = jobs_list_output_files_options.linkexpiryinminutes _max_results = jobs_list_output_files_options.max_results api_version = "2018-05-01" accept = "application/json" def prepare_request(next_link=None): # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') if not next_link: # Construct URL url = self.list_output_files.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', pattern=r'^[-\w\._]+$'), 'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'experimentName': self._serialize.url("experiment_name", experiment_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'jobName': self._serialize.url("job_name", job_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), '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 = {} # type: Dict[str, Any] query_parameters['outputdirectoryid'] = self._serialize.query("outputdirectoryid", _outputdirectoryid, 'str') if _directory is not None: query_parameters['directory'] = self._serialize.query("directory", _directory, 'str') if _linkexpiryinminutes is not None: query_parameters['linkexpiryinminutes'] = self._serialize.query("linkexpiryinminutes", _linkexpiryinminutes, 'int', maximum=600, minimum=5) if _max_results is not None: query_parameters['maxresults'] = self._serialize.query("max_results", _max_results, 'int', maximum=1000, minimum=1) query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') request = self._client.post(url, query_parameters, header_parameters) else: url = next_link query_parameters = {} # type: Dict[str, Any] request = self._client.get(url, query_parameters, header_parameters) return request def extract_data(pipeline_response): deserialized = self._deserialize('FileListResult', pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return ItemPaged( get_next, extract_data ) list_output_files.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces/{workspaceName}/experiments/{experimentName}/jobs/{jobName}/listOutputFiles'} # type: ignore def list_remote_login_information( self, resource_group_name, # type: str workspace_name, # type: str experiment_name, # type: str job_name, # type: str **kwargs # type: Any ): # type: (...) -> Iterable["_models.RemoteLoginInformationListResult"] """Gets a list of currently existing nodes which were used for the Job execution. The returned information contains the node ID, its public IP and SSH port. :param resource_group_name: Name of the resource group to which the resource belongs. :type resource_group_name: str :param workspace_name: The name of the workspace. Workspace names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type workspace_name: str :param experiment_name: The name of the experiment. Experiment names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type experiment_name: str :param job_name: The name of the job within the specified resource group. Job names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type job_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either RemoteLoginInformationListResult or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~batch_ai.models.RemoteLoginInformationListResult] :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.RemoteLoginInformationListResult"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2018-05-01" accept = "application/json" def prepare_request(next_link=None): # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') if not next_link: # Construct URL url = self.list_remote_login_information.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', pattern=r'^[-\w\._]+$'), 'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'experimentName': self._serialize.url("experiment_name", experiment_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'jobName': self._serialize.url("job_name", job_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), '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 = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') request = self._client.post(url, query_parameters, header_parameters) else: url = next_link query_parameters = {} # type: Dict[str, Any] request = self._client.get(url, query_parameters, header_parameters) return request def extract_data(pipeline_response): deserialized = self._deserialize('RemoteLoginInformationListResult', pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return ItemPaged( get_next, extract_data ) list_remote_login_information.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces/{workspaceName}/experiments/{experimentName}/jobs/{jobName}/listRemoteLoginInformation'} # type: ignore def _terminate_initial( self, resource_group_name, # type: str workspace_name, # type: str experiment_name, # type: str job_name, # type: str **kwargs # type: Any ): # type: (...) -> None cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2018-05-01" accept = "application/json" # Construct URL url = self._terminate_initial.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', pattern=r'^[-\w\._]+$'), 'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'experimentName': self._serialize.url("experiment_name", experiment_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'jobName': self._serialize.url("job_name", job_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), '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 = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') request = self._client.post(url, query_parameters, header_parameters) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) _terminate_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces/{workspaceName}/experiments/{experimentName}/jobs/{jobName}/terminate'} # type: ignore def begin_terminate( self, resource_group_name, # type: str workspace_name, # type: str experiment_name, # type: str job_name, # type: str **kwargs # type: Any ): # type: (...) -> LROPoller[None] """Terminates a job. :param resource_group_name: Name of the resource group to which the resource belongs. :type resource_group_name: str :param workspace_name: The name of the workspace. Workspace names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type workspace_name: str :param experiment_name: The name of the experiment. Experiment names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type experiment_name: str :param job_name: The name of the job within the specified resource group. Job names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type job_name: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.PollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of LROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[None] :raises ~azure.core.exceptions.HttpResponseError: """ polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] cls = kwargs.pop('cls', None) # type: ClsType[None] lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval ) cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] if cont_token is None: raw_result = self._terminate_initial( resource_group_name=resource_group_name, workspace_name=workspace_name, experiment_name=experiment_name, job_name=job_name, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map', None) kwargs.pop('content_type', None) def get_long_running_output(pipeline_response): if cls: return cls(pipeline_response, None, {}) path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', pattern=r'^[-\w\._]+$'), 'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'experimentName': self._serialize.url("experiment_name", experiment_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'jobName': self._serialize.url("job_name", job_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } if polling is True: polling_method = ARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) elif polling is False: polling_method = NoPolling() else: polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output ) else: return LROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_terminate.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces/{workspaceName}/experiments/{experimentName}/jobs/{jobName}/terminate'} # type: ignore
azure-mgmt-batchai
/azure-mgmt-batchai-7.0.0b1.zip/azure-mgmt-batchai-7.0.0b1/azure/mgmt/batchai/operations/_jobs_operations.py
_jobs_operations.py
from typing import TYPE_CHECKING import warnings from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpRequest, HttpResponse from azure.core.polling import LROPoller, NoPolling, PollingMethod from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.arm_polling import ARMPolling from .. import models as _models if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar, Union T = TypeVar('T') ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] class JobsOperations(object): """JobsOperations operations. You should not instantiate this class directly. Instead, you should create a Client instance that instantiates it for you and attaches it as an attribute. :ivar models: Alias to model classes used in this operation group. :type models: ~batch_ai.models :param client: Client for service requests. :param config: Configuration of service client. :param serializer: An object model serializer. :param deserializer: An object model deserializer. """ models = _models def __init__(self, client, config, serializer, deserializer): self._client = client self._serialize = serializer self._deserialize = deserializer self._config = config def list_by_experiment( self, resource_group_name, # type: str workspace_name, # type: str experiment_name, # type: str jobs_list_by_experiment_options=None, # type: Optional["_models.JobsListByExperimentOptions"] **kwargs # type: Any ): # type: (...) -> Iterable["_models.JobListResult"] """Gets a list of Jobs within the specified Experiment. :param resource_group_name: Name of the resource group to which the resource belongs. :type resource_group_name: str :param workspace_name: The name of the workspace. Workspace names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type workspace_name: str :param experiment_name: The name of the experiment. Experiment names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type experiment_name: str :param jobs_list_by_experiment_options: Parameter group. :type jobs_list_by_experiment_options: ~batch_ai.models.JobsListByExperimentOptions :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either JobListResult or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~batch_ai.models.JobListResult] :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.JobListResult"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) _max_results = None if jobs_list_by_experiment_options is not None: _max_results = jobs_list_by_experiment_options.max_results api_version = "2018-05-01" accept = "application/json" def prepare_request(next_link=None): # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') if not next_link: # Construct URL url = self.list_by_experiment.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', pattern=r'^[-\w\._]+$'), 'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'experimentName': self._serialize.url("experiment_name", experiment_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), '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 = {} # type: Dict[str, Any] if _max_results is not None: query_parameters['maxresults'] = self._serialize.query("max_results", _max_results, 'int', maximum=1000, minimum=1) query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') request = self._client.get(url, query_parameters, header_parameters) else: url = next_link query_parameters = {} # type: Dict[str, Any] request = self._client.get(url, query_parameters, header_parameters) return request def extract_data(pipeline_response): deserialized = self._deserialize('JobListResult', pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return ItemPaged( get_next, extract_data ) list_by_experiment.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces/{workspaceName}/experiments/{experimentName}/jobs'} # type: ignore def _create_initial( self, resource_group_name, # type: str workspace_name, # type: str experiment_name, # type: str job_name, # type: str parameters, # type: "_models.JobCreateParameters" **kwargs # type: Any ): # type: (...) -> Optional["_models.Job"] cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.Job"]] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2018-05-01" content_type = kwargs.pop("content_type", "application/json") accept = "application/json" # Construct URL url = self._create_initial.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', pattern=r'^[-\w\._]+$'), 'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'experimentName': self._serialize.url("experiment_name", experiment_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'jobName': self._serialize.url("job_name", job_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), '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 = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') body_content_kwargs = {} # type: Dict[str, Any] body_content = self._serialize.body(parameters, 'JobCreateParameters') body_content_kwargs['content'] = body_content request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = None if response.status_code == 200: deserialized = self._deserialize('Job', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized _create_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces/{workspaceName}/experiments/{experimentName}/jobs/{jobName}'} # type: ignore def begin_create( self, resource_group_name, # type: str workspace_name, # type: str experiment_name, # type: str job_name, # type: str parameters, # type: "_models.JobCreateParameters" **kwargs # type: Any ): # type: (...) -> LROPoller["_models.Job"] """Creates a Job in the given Experiment. :param resource_group_name: Name of the resource group to which the resource belongs. :type resource_group_name: str :param workspace_name: The name of the workspace. Workspace names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type workspace_name: str :param experiment_name: The name of the experiment. Experiment names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type experiment_name: str :param job_name: The name of the job within the specified resource group. Job names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type job_name: str :param parameters: The parameters to provide for job creation. :type parameters: ~batch_ai.models.JobCreateParameters :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.PollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of LROPoller that returns either Job or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~batch_ai.models.Job] :raises ~azure.core.exceptions.HttpResponseError: """ polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] cls = kwargs.pop('cls', None) # type: ClsType["_models.Job"] lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval ) cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] if cont_token is None: raw_result = self._create_initial( resource_group_name=resource_group_name, workspace_name=workspace_name, experiment_name=experiment_name, job_name=job_name, parameters=parameters, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map', None) kwargs.pop('content_type', None) def get_long_running_output(pipeline_response): deserialized = self._deserialize('Job', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', pattern=r'^[-\w\._]+$'), 'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'experimentName': self._serialize.url("experiment_name", experiment_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'jobName': self._serialize.url("job_name", job_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } if polling is True: polling_method = ARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) elif polling is False: polling_method = NoPolling() else: polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output ) else: return LROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_create.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces/{workspaceName}/experiments/{experimentName}/jobs/{jobName}'} # type: ignore def _delete_initial( self, resource_group_name, # type: str workspace_name, # type: str experiment_name, # type: str job_name, # type: str **kwargs # type: Any ): # type: (...) -> None cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2018-05-01" accept = "application/json" # Construct URL url = self._delete_initial.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', pattern=r'^[-\w\._]+$'), 'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'experimentName': self._serialize.url("experiment_name", experiment_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'jobName': self._serialize.url("job_name", job_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), '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 = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') request = self._client.delete(url, query_parameters, header_parameters) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) _delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces/{workspaceName}/experiments/{experimentName}/jobs/{jobName}'} # type: ignore def begin_delete( self, resource_group_name, # type: str workspace_name, # type: str experiment_name, # type: str job_name, # type: str **kwargs # type: Any ): # type: (...) -> LROPoller[None] """Deletes a Job. :param resource_group_name: Name of the resource group to which the resource belongs. :type resource_group_name: str :param workspace_name: The name of the workspace. Workspace names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type workspace_name: str :param experiment_name: The name of the experiment. Experiment names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type experiment_name: str :param job_name: The name of the job within the specified resource group. Job names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type job_name: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.PollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of LROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[None] :raises ~azure.core.exceptions.HttpResponseError: """ polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] cls = kwargs.pop('cls', None) # type: ClsType[None] lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval ) cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] if cont_token is None: raw_result = self._delete_initial( resource_group_name=resource_group_name, workspace_name=workspace_name, experiment_name=experiment_name, job_name=job_name, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map', None) kwargs.pop('content_type', None) def get_long_running_output(pipeline_response): if cls: return cls(pipeline_response, None, {}) path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', pattern=r'^[-\w\._]+$'), 'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'experimentName': self._serialize.url("experiment_name", experiment_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'jobName': self._serialize.url("job_name", job_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } if polling is True: polling_method = ARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) elif polling is False: polling_method = NoPolling() else: polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output ) else: return LROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces/{workspaceName}/experiments/{experimentName}/jobs/{jobName}'} # type: ignore def get( self, resource_group_name, # type: str workspace_name, # type: str experiment_name, # type: str job_name, # type: str **kwargs # type: Any ): # type: (...) -> "_models.Job" """Gets information about a Job. :param resource_group_name: Name of the resource group to which the resource belongs. :type resource_group_name: str :param workspace_name: The name of the workspace. Workspace names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type workspace_name: str :param experiment_name: The name of the experiment. Experiment names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type experiment_name: str :param job_name: The name of the job within the specified resource group. Job names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type job_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Job, or the result of cls(response) :rtype: ~batch_ai.models.Job :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.Job"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2018-05-01" accept = "application/json" # Construct URL url = self.get.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', pattern=r'^[-\w\._]+$'), 'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'experimentName': self._serialize.url("experiment_name", experiment_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'jobName': self._serialize.url("job_name", job_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), '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 = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') request = self._client.get(url, query_parameters, header_parameters) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize('Job', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces/{workspaceName}/experiments/{experimentName}/jobs/{jobName}'} # type: ignore def list_output_files( self, resource_group_name, # type: str workspace_name, # type: str experiment_name, # type: str job_name, # type: str jobs_list_output_files_options, # type: "_models.JobsListOutputFilesOptions" **kwargs # type: Any ): # type: (...) -> Iterable["_models.FileListResult"] """List all directories and files inside the given directory of the Job's output directory (if the output directory is on Azure File Share or Azure Storage Container). :param resource_group_name: Name of the resource group to which the resource belongs. :type resource_group_name: str :param workspace_name: The name of the workspace. Workspace names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type workspace_name: str :param experiment_name: The name of the experiment. Experiment names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type experiment_name: str :param job_name: The name of the job within the specified resource group. Job names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type job_name: str :param jobs_list_output_files_options: Parameter group. :type jobs_list_output_files_options: ~batch_ai.models.JobsListOutputFilesOptions :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either FileListResult or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~batch_ai.models.FileListResult] :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.FileListResult"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) _outputdirectoryid = None _directory = None _linkexpiryinminutes = None _max_results = None if jobs_list_output_files_options is not None: _outputdirectoryid = jobs_list_output_files_options.outputdirectoryid _directory = jobs_list_output_files_options.directory _linkexpiryinminutes = jobs_list_output_files_options.linkexpiryinminutes _max_results = jobs_list_output_files_options.max_results api_version = "2018-05-01" accept = "application/json" def prepare_request(next_link=None): # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') if not next_link: # Construct URL url = self.list_output_files.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', pattern=r'^[-\w\._]+$'), 'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'experimentName': self._serialize.url("experiment_name", experiment_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'jobName': self._serialize.url("job_name", job_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), '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 = {} # type: Dict[str, Any] query_parameters['outputdirectoryid'] = self._serialize.query("outputdirectoryid", _outputdirectoryid, 'str') if _directory is not None: query_parameters['directory'] = self._serialize.query("directory", _directory, 'str') if _linkexpiryinminutes is not None: query_parameters['linkexpiryinminutes'] = self._serialize.query("linkexpiryinminutes", _linkexpiryinminutes, 'int', maximum=600, minimum=5) if _max_results is not None: query_parameters['maxresults'] = self._serialize.query("max_results", _max_results, 'int', maximum=1000, minimum=1) query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') request = self._client.post(url, query_parameters, header_parameters) else: url = next_link query_parameters = {} # type: Dict[str, Any] request = self._client.get(url, query_parameters, header_parameters) return request def extract_data(pipeline_response): deserialized = self._deserialize('FileListResult', pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return ItemPaged( get_next, extract_data ) list_output_files.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces/{workspaceName}/experiments/{experimentName}/jobs/{jobName}/listOutputFiles'} # type: ignore def list_remote_login_information( self, resource_group_name, # type: str workspace_name, # type: str experiment_name, # type: str job_name, # type: str **kwargs # type: Any ): # type: (...) -> Iterable["_models.RemoteLoginInformationListResult"] """Gets a list of currently existing nodes which were used for the Job execution. The returned information contains the node ID, its public IP and SSH port. :param resource_group_name: Name of the resource group to which the resource belongs. :type resource_group_name: str :param workspace_name: The name of the workspace. Workspace names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type workspace_name: str :param experiment_name: The name of the experiment. Experiment names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type experiment_name: str :param job_name: The name of the job within the specified resource group. Job names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type job_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either RemoteLoginInformationListResult or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~batch_ai.models.RemoteLoginInformationListResult] :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.RemoteLoginInformationListResult"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2018-05-01" accept = "application/json" def prepare_request(next_link=None): # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') if not next_link: # Construct URL url = self.list_remote_login_information.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', pattern=r'^[-\w\._]+$'), 'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'experimentName': self._serialize.url("experiment_name", experiment_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'jobName': self._serialize.url("job_name", job_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), '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 = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') request = self._client.post(url, query_parameters, header_parameters) else: url = next_link query_parameters = {} # type: Dict[str, Any] request = self._client.get(url, query_parameters, header_parameters) return request def extract_data(pipeline_response): deserialized = self._deserialize('RemoteLoginInformationListResult', pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return ItemPaged( get_next, extract_data ) list_remote_login_information.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces/{workspaceName}/experiments/{experimentName}/jobs/{jobName}/listRemoteLoginInformation'} # type: ignore def _terminate_initial( self, resource_group_name, # type: str workspace_name, # type: str experiment_name, # type: str job_name, # type: str **kwargs # type: Any ): # type: (...) -> None cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2018-05-01" accept = "application/json" # Construct URL url = self._terminate_initial.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', pattern=r'^[-\w\._]+$'), 'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'experimentName': self._serialize.url("experiment_name", experiment_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'jobName': self._serialize.url("job_name", job_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), '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 = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') request = self._client.post(url, query_parameters, header_parameters) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) _terminate_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces/{workspaceName}/experiments/{experimentName}/jobs/{jobName}/terminate'} # type: ignore def begin_terminate( self, resource_group_name, # type: str workspace_name, # type: str experiment_name, # type: str job_name, # type: str **kwargs # type: Any ): # type: (...) -> LROPoller[None] """Terminates a job. :param resource_group_name: Name of the resource group to which the resource belongs. :type resource_group_name: str :param workspace_name: The name of the workspace. Workspace names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type workspace_name: str :param experiment_name: The name of the experiment. Experiment names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type experiment_name: str :param job_name: The name of the job within the specified resource group. Job names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type job_name: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.PollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of LROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[None] :raises ~azure.core.exceptions.HttpResponseError: """ polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] cls = kwargs.pop('cls', None) # type: ClsType[None] lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval ) cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] if cont_token is None: raw_result = self._terminate_initial( resource_group_name=resource_group_name, workspace_name=workspace_name, experiment_name=experiment_name, job_name=job_name, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map', None) kwargs.pop('content_type', None) def get_long_running_output(pipeline_response): if cls: return cls(pipeline_response, None, {}) path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', pattern=r'^[-\w\._]+$'), 'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'experimentName': self._serialize.url("experiment_name", experiment_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'jobName': self._serialize.url("job_name", job_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } if polling is True: polling_method = ARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) elif polling is False: polling_method = NoPolling() else: polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output ) else: return LROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_terminate.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces/{workspaceName}/experiments/{experimentName}/jobs/{jobName}/terminate'} # type: ignore
0.83752
0.091788
from typing import TYPE_CHECKING import warnings from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpRequest, HttpResponse from azure.core.polling import LROPoller, NoPolling, PollingMethod from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.arm_polling import ARMPolling from .. import models as _models if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar, Union T = TypeVar('T') ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] class WorkspacesOperations(object): """WorkspacesOperations operations. You should not instantiate this class directly. Instead, you should create a Client instance that instantiates it for you and attaches it as an attribute. :ivar models: Alias to model classes used in this operation group. :type models: ~batch_ai.models :param client: Client for service requests. :param config: Configuration of service client. :param serializer: An object model serializer. :param deserializer: An object model deserializer. """ models = _models def __init__(self, client, config, serializer, deserializer): self._client = client self._serialize = serializer self._deserialize = deserializer self._config = config def list( self, workspaces_list_options=None, # type: Optional["_models.WorkspacesListOptions"] **kwargs # type: Any ): # type: (...) -> Iterable["_models.WorkspaceListResult"] """Gets a list of Workspaces associated with the given subscription. :param workspaces_list_options: Parameter group. :type workspaces_list_options: ~batch_ai.models.WorkspacesListOptions :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either WorkspaceListResult or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~batch_ai.models.WorkspaceListResult] :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.WorkspaceListResult"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) _max_results = None if workspaces_list_options is not None: _max_results = workspaces_list_options.max_results api_version = "2018-05-01" accept = "application/json" def prepare_request(next_link=None): # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') if not next_link: # Construct URL url = self.list.metadata['url'] # type: ignore 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 = {} # type: Dict[str, Any] if _max_results is not None: query_parameters['maxresults'] = self._serialize.query("max_results", _max_results, 'int', maximum=1000, minimum=1) query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') request = self._client.get(url, query_parameters, header_parameters) else: url = next_link query_parameters = {} # type: Dict[str, Any] request = self._client.get(url, query_parameters, header_parameters) return request def extract_data(pipeline_response): deserialized = self._deserialize('WorkspaceListResult', pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return ItemPaged( get_next, extract_data ) list.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.BatchAI/workspaces'} # type: ignore def list_by_resource_group( self, resource_group_name, # type: str workspaces_list_by_resource_group_options=None, # type: Optional["_models.WorkspacesListByResourceGroupOptions"] **kwargs # type: Any ): # type: (...) -> Iterable["_models.WorkspaceListResult"] """Gets a list of Workspaces within the specified resource group. :param resource_group_name: Name of the resource group to which the resource belongs. :type resource_group_name: str :param workspaces_list_by_resource_group_options: Parameter group. :type workspaces_list_by_resource_group_options: ~batch_ai.models.WorkspacesListByResourceGroupOptions :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either WorkspaceListResult or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~batch_ai.models.WorkspaceListResult] :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.WorkspaceListResult"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) _max_results = None if workspaces_list_by_resource_group_options is not None: _max_results = workspaces_list_by_resource_group_options.max_results api_version = "2018-05-01" accept = "application/json" def prepare_request(next_link=None): # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') if not next_link: # Construct URL url = self.list_by_resource_group.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', pattern=r'^[-\w\._]+$'), '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 = {} # type: Dict[str, Any] if _max_results is not None: query_parameters['maxresults'] = self._serialize.query("max_results", _max_results, 'int', maximum=1000, minimum=1) query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') request = self._client.get(url, query_parameters, header_parameters) else: url = next_link query_parameters = {} # type: Dict[str, Any] request = self._client.get(url, query_parameters, header_parameters) return request def extract_data(pipeline_response): deserialized = self._deserialize('WorkspaceListResult', pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return ItemPaged( get_next, extract_data ) list_by_resource_group.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces'} # type: ignore def _create_initial( self, resource_group_name, # type: str workspace_name, # type: str parameters, # type: "_models.WorkspaceCreateParameters" **kwargs # type: Any ): # type: (...) -> Optional["_models.Workspace"] cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.Workspace"]] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2018-05-01" content_type = kwargs.pop("content_type", "application/json") accept = "application/json" # Construct URL url = self._create_initial.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', pattern=r'^[-\w\._]+$'), 'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), '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 = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') body_content_kwargs = {} # type: Dict[str, Any] body_content = self._serialize.body(parameters, 'WorkspaceCreateParameters') body_content_kwargs['content'] = body_content request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = None if response.status_code == 200: deserialized = self._deserialize('Workspace', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized _create_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces/{workspaceName}'} # type: ignore def begin_create( self, resource_group_name, # type: str workspace_name, # type: str parameters, # type: "_models.WorkspaceCreateParameters" **kwargs # type: Any ): # type: (...) -> LROPoller["_models.Workspace"] """Creates a Workspace. :param resource_group_name: Name of the resource group to which the resource belongs. :type resource_group_name: str :param workspace_name: The name of the workspace. Workspace names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type workspace_name: str :param parameters: Workspace creation parameters. :type parameters: ~batch_ai.models.WorkspaceCreateParameters :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.PollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of LROPoller that returns either Workspace or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~batch_ai.models.Workspace] :raises ~azure.core.exceptions.HttpResponseError: """ polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] cls = kwargs.pop('cls', None) # type: ClsType["_models.Workspace"] lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval ) cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] if cont_token is None: raw_result = self._create_initial( resource_group_name=resource_group_name, workspace_name=workspace_name, parameters=parameters, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map', None) kwargs.pop('content_type', None) def get_long_running_output(pipeline_response): deserialized = self._deserialize('Workspace', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', pattern=r'^[-\w\._]+$'), 'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } if polling is True: polling_method = ARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) elif polling is False: polling_method = NoPolling() else: polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output ) else: return LROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_create.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces/{workspaceName}'} # type: ignore def update( self, resource_group_name, # type: str workspace_name, # type: str parameters, # type: "_models.WorkspaceUpdateParameters" **kwargs # type: Any ): # type: (...) -> "_models.Workspace" """Updates properties of a Workspace. :param resource_group_name: Name of the resource group to which the resource belongs. :type resource_group_name: str :param workspace_name: The name of the workspace. Workspace names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type workspace_name: str :param parameters: Additional parameters for workspace update. :type parameters: ~batch_ai.models.WorkspaceUpdateParameters :keyword callable cls: A custom type or function that will be passed the direct response :return: Workspace, or the result of cls(response) :rtype: ~batch_ai.models.Workspace :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.Workspace"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2018-05-01" content_type = kwargs.pop("content_type", "application/json") accept = "application/json" # Construct URL url = self.update.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', pattern=r'^[-\w\._]+$'), 'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), '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 = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') body_content_kwargs = {} # type: Dict[str, Any] body_content = self._serialize.body(parameters, 'WorkspaceUpdateParameters') body_content_kwargs['content'] = body_content request = self._client.patch(url, query_parameters, header_parameters, **body_content_kwargs) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize('Workspace', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces/{workspaceName}'} # type: ignore def _delete_initial( self, resource_group_name, # type: str workspace_name, # type: str **kwargs # type: Any ): # type: (...) -> None cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2018-05-01" accept = "application/json" # Construct URL url = self._delete_initial.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', pattern=r'^[-\w\._]+$'), 'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), '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 = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') request = self._client.delete(url, query_parameters, header_parameters) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) _delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces/{workspaceName}'} # type: ignore def begin_delete( self, resource_group_name, # type: str workspace_name, # type: str **kwargs # type: Any ): # type: (...) -> LROPoller[None] """Deletes a Workspace. :param resource_group_name: Name of the resource group to which the resource belongs. :type resource_group_name: str :param workspace_name: The name of the workspace. Workspace names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type workspace_name: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.PollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of LROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[None] :raises ~azure.core.exceptions.HttpResponseError: """ polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] cls = kwargs.pop('cls', None) # type: ClsType[None] lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval ) cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] if cont_token is None: raw_result = self._delete_initial( resource_group_name=resource_group_name, workspace_name=workspace_name, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map', None) kwargs.pop('content_type', None) def get_long_running_output(pipeline_response): if cls: return cls(pipeline_response, None, {}) path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', pattern=r'^[-\w\._]+$'), 'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } if polling is True: polling_method = ARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) elif polling is False: polling_method = NoPolling() else: polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output ) else: return LROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces/{workspaceName}'} # type: ignore def get( self, resource_group_name, # type: str workspace_name, # type: str **kwargs # type: Any ): # type: (...) -> "_models.Workspace" """Gets information about a Workspace. :param resource_group_name: Name of the resource group to which the resource belongs. :type resource_group_name: str :param workspace_name: The name of the workspace. Workspace names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type workspace_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Workspace, or the result of cls(response) :rtype: ~batch_ai.models.Workspace :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.Workspace"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2018-05-01" accept = "application/json" # Construct URL url = self.get.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', pattern=r'^[-\w\._]+$'), 'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), '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 = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') request = self._client.get(url, query_parameters, header_parameters) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize('Workspace', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces/{workspaceName}'} # type: ignore
azure-mgmt-batchai
/azure-mgmt-batchai-7.0.0b1.zip/azure-mgmt-batchai-7.0.0b1/azure/mgmt/batchai/operations/_workspaces_operations.py
_workspaces_operations.py
from typing import TYPE_CHECKING import warnings from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpRequest, HttpResponse from azure.core.polling import LROPoller, NoPolling, PollingMethod from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.arm_polling import ARMPolling from .. import models as _models if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar, Union T = TypeVar('T') ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] class WorkspacesOperations(object): """WorkspacesOperations operations. You should not instantiate this class directly. Instead, you should create a Client instance that instantiates it for you and attaches it as an attribute. :ivar models: Alias to model classes used in this operation group. :type models: ~batch_ai.models :param client: Client for service requests. :param config: Configuration of service client. :param serializer: An object model serializer. :param deserializer: An object model deserializer. """ models = _models def __init__(self, client, config, serializer, deserializer): self._client = client self._serialize = serializer self._deserialize = deserializer self._config = config def list( self, workspaces_list_options=None, # type: Optional["_models.WorkspacesListOptions"] **kwargs # type: Any ): # type: (...) -> Iterable["_models.WorkspaceListResult"] """Gets a list of Workspaces associated with the given subscription. :param workspaces_list_options: Parameter group. :type workspaces_list_options: ~batch_ai.models.WorkspacesListOptions :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either WorkspaceListResult or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~batch_ai.models.WorkspaceListResult] :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.WorkspaceListResult"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) _max_results = None if workspaces_list_options is not None: _max_results = workspaces_list_options.max_results api_version = "2018-05-01" accept = "application/json" def prepare_request(next_link=None): # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') if not next_link: # Construct URL url = self.list.metadata['url'] # type: ignore 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 = {} # type: Dict[str, Any] if _max_results is not None: query_parameters['maxresults'] = self._serialize.query("max_results", _max_results, 'int', maximum=1000, minimum=1) query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') request = self._client.get(url, query_parameters, header_parameters) else: url = next_link query_parameters = {} # type: Dict[str, Any] request = self._client.get(url, query_parameters, header_parameters) return request def extract_data(pipeline_response): deserialized = self._deserialize('WorkspaceListResult', pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return ItemPaged( get_next, extract_data ) list.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.BatchAI/workspaces'} # type: ignore def list_by_resource_group( self, resource_group_name, # type: str workspaces_list_by_resource_group_options=None, # type: Optional["_models.WorkspacesListByResourceGroupOptions"] **kwargs # type: Any ): # type: (...) -> Iterable["_models.WorkspaceListResult"] """Gets a list of Workspaces within the specified resource group. :param resource_group_name: Name of the resource group to which the resource belongs. :type resource_group_name: str :param workspaces_list_by_resource_group_options: Parameter group. :type workspaces_list_by_resource_group_options: ~batch_ai.models.WorkspacesListByResourceGroupOptions :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either WorkspaceListResult or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~batch_ai.models.WorkspaceListResult] :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.WorkspaceListResult"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) _max_results = None if workspaces_list_by_resource_group_options is not None: _max_results = workspaces_list_by_resource_group_options.max_results api_version = "2018-05-01" accept = "application/json" def prepare_request(next_link=None): # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') if not next_link: # Construct URL url = self.list_by_resource_group.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', pattern=r'^[-\w\._]+$'), '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 = {} # type: Dict[str, Any] if _max_results is not None: query_parameters['maxresults'] = self._serialize.query("max_results", _max_results, 'int', maximum=1000, minimum=1) query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') request = self._client.get(url, query_parameters, header_parameters) else: url = next_link query_parameters = {} # type: Dict[str, Any] request = self._client.get(url, query_parameters, header_parameters) return request def extract_data(pipeline_response): deserialized = self._deserialize('WorkspaceListResult', pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return ItemPaged( get_next, extract_data ) list_by_resource_group.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces'} # type: ignore def _create_initial( self, resource_group_name, # type: str workspace_name, # type: str parameters, # type: "_models.WorkspaceCreateParameters" **kwargs # type: Any ): # type: (...) -> Optional["_models.Workspace"] cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.Workspace"]] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2018-05-01" content_type = kwargs.pop("content_type", "application/json") accept = "application/json" # Construct URL url = self._create_initial.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', pattern=r'^[-\w\._]+$'), 'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), '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 = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') body_content_kwargs = {} # type: Dict[str, Any] body_content = self._serialize.body(parameters, 'WorkspaceCreateParameters') body_content_kwargs['content'] = body_content request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = None if response.status_code == 200: deserialized = self._deserialize('Workspace', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized _create_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces/{workspaceName}'} # type: ignore def begin_create( self, resource_group_name, # type: str workspace_name, # type: str parameters, # type: "_models.WorkspaceCreateParameters" **kwargs # type: Any ): # type: (...) -> LROPoller["_models.Workspace"] """Creates a Workspace. :param resource_group_name: Name of the resource group to which the resource belongs. :type resource_group_name: str :param workspace_name: The name of the workspace. Workspace names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type workspace_name: str :param parameters: Workspace creation parameters. :type parameters: ~batch_ai.models.WorkspaceCreateParameters :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.PollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of LROPoller that returns either Workspace or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~batch_ai.models.Workspace] :raises ~azure.core.exceptions.HttpResponseError: """ polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] cls = kwargs.pop('cls', None) # type: ClsType["_models.Workspace"] lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval ) cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] if cont_token is None: raw_result = self._create_initial( resource_group_name=resource_group_name, workspace_name=workspace_name, parameters=parameters, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map', None) kwargs.pop('content_type', None) def get_long_running_output(pipeline_response): deserialized = self._deserialize('Workspace', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', pattern=r'^[-\w\._]+$'), 'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } if polling is True: polling_method = ARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) elif polling is False: polling_method = NoPolling() else: polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output ) else: return LROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_create.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces/{workspaceName}'} # type: ignore def update( self, resource_group_name, # type: str workspace_name, # type: str parameters, # type: "_models.WorkspaceUpdateParameters" **kwargs # type: Any ): # type: (...) -> "_models.Workspace" """Updates properties of a Workspace. :param resource_group_name: Name of the resource group to which the resource belongs. :type resource_group_name: str :param workspace_name: The name of the workspace. Workspace names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type workspace_name: str :param parameters: Additional parameters for workspace update. :type parameters: ~batch_ai.models.WorkspaceUpdateParameters :keyword callable cls: A custom type or function that will be passed the direct response :return: Workspace, or the result of cls(response) :rtype: ~batch_ai.models.Workspace :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.Workspace"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2018-05-01" content_type = kwargs.pop("content_type", "application/json") accept = "application/json" # Construct URL url = self.update.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', pattern=r'^[-\w\._]+$'), 'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), '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 = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') body_content_kwargs = {} # type: Dict[str, Any] body_content = self._serialize.body(parameters, 'WorkspaceUpdateParameters') body_content_kwargs['content'] = body_content request = self._client.patch(url, query_parameters, header_parameters, **body_content_kwargs) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize('Workspace', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces/{workspaceName}'} # type: ignore def _delete_initial( self, resource_group_name, # type: str workspace_name, # type: str **kwargs # type: Any ): # type: (...) -> None cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2018-05-01" accept = "application/json" # Construct URL url = self._delete_initial.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', pattern=r'^[-\w\._]+$'), 'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), '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 = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') request = self._client.delete(url, query_parameters, header_parameters) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) _delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces/{workspaceName}'} # type: ignore def begin_delete( self, resource_group_name, # type: str workspace_name, # type: str **kwargs # type: Any ): # type: (...) -> LROPoller[None] """Deletes a Workspace. :param resource_group_name: Name of the resource group to which the resource belongs. :type resource_group_name: str :param workspace_name: The name of the workspace. Workspace names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type workspace_name: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.PollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of LROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[None] :raises ~azure.core.exceptions.HttpResponseError: """ polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] cls = kwargs.pop('cls', None) # type: ClsType[None] lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval ) cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] if cont_token is None: raw_result = self._delete_initial( resource_group_name=resource_group_name, workspace_name=workspace_name, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map', None) kwargs.pop('content_type', None) def get_long_running_output(pipeline_response): if cls: return cls(pipeline_response, None, {}) path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', pattern=r'^[-\w\._]+$'), 'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } if polling is True: polling_method = ARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) elif polling is False: polling_method = NoPolling() else: polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output ) else: return LROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces/{workspaceName}'} # type: ignore def get( self, resource_group_name, # type: str workspace_name, # type: str **kwargs # type: Any ): # type: (...) -> "_models.Workspace" """Gets information about a Workspace. :param resource_group_name: Name of the resource group to which the resource belongs. :type resource_group_name: str :param workspace_name: The name of the workspace. Workspace names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type workspace_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Workspace, or the result of cls(response) :rtype: ~batch_ai.models.Workspace :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.Workspace"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2018-05-01" accept = "application/json" # Construct URL url = self.get.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', pattern=r'^[-\w\._]+$'), 'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), '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 = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') request = self._client.get(url, query_parameters, header_parameters) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize('Workspace', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces/{workspaceName}'} # type: ignore
0.863392
0.084304
from typing import TYPE_CHECKING import warnings from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpRequest, HttpResponse from azure.core.polling import LROPoller, NoPolling, PollingMethod from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.arm_polling import ARMPolling from .. import models as _models if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar, Union T = TypeVar('T') ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] class ClustersOperations(object): """ClustersOperations operations. You should not instantiate this class directly. Instead, you should create a Client instance that instantiates it for you and attaches it as an attribute. :ivar models: Alias to model classes used in this operation group. :type models: ~batch_ai.models :param client: Client for service requests. :param config: Configuration of service client. :param serializer: An object model serializer. :param deserializer: An object model deserializer. """ models = _models def __init__(self, client, config, serializer, deserializer): self._client = client self._serialize = serializer self._deserialize = deserializer self._config = config def _create_initial( self, resource_group_name, # type: str workspace_name, # type: str cluster_name, # type: str parameters, # type: "_models.ClusterCreateParameters" **kwargs # type: Any ): # type: (...) -> Optional["_models.Cluster"] cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.Cluster"]] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2018-05-01" content_type = kwargs.pop("content_type", "application/json") accept = "application/json" # Construct URL url = self._create_initial.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', pattern=r'^[-\w\._]+$'), 'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), '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 = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') body_content_kwargs = {} # type: Dict[str, Any] body_content = self._serialize.body(parameters, 'ClusterCreateParameters') body_content_kwargs['content'] = body_content request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = None if response.status_code == 200: deserialized = self._deserialize('Cluster', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized _create_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces/{workspaceName}/clusters/{clusterName}'} # type: ignore def begin_create( self, resource_group_name, # type: str workspace_name, # type: str cluster_name, # type: str parameters, # type: "_models.ClusterCreateParameters" **kwargs # type: Any ): # type: (...) -> LROPoller["_models.Cluster"] """Creates a Cluster in the given Workspace. :param resource_group_name: Name of the resource group to which the resource belongs. :type resource_group_name: str :param workspace_name: The name of the workspace. Workspace names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type workspace_name: str :param cluster_name: The name of the cluster within the specified resource group. Cluster names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type cluster_name: str :param parameters: The parameters to provide for the Cluster creation. :type parameters: ~batch_ai.models.ClusterCreateParameters :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.PollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of LROPoller that returns either Cluster or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~batch_ai.models.Cluster] :raises ~azure.core.exceptions.HttpResponseError: """ polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] cls = kwargs.pop('cls', None) # type: ClsType["_models.Cluster"] lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval ) cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] if cont_token is None: raw_result = self._create_initial( resource_group_name=resource_group_name, workspace_name=workspace_name, cluster_name=cluster_name, parameters=parameters, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map', None) kwargs.pop('content_type', None) def get_long_running_output(pipeline_response): deserialized = self._deserialize('Cluster', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', pattern=r'^[-\w\._]+$'), 'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } if polling is True: polling_method = ARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) elif polling is False: polling_method = NoPolling() else: polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output ) else: return LROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_create.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces/{workspaceName}/clusters/{clusterName}'} # type: ignore def update( self, resource_group_name, # type: str workspace_name, # type: str cluster_name, # type: str parameters, # type: "_models.ClusterUpdateParameters" **kwargs # type: Any ): # type: (...) -> "_models.Cluster" """Updates properties of a Cluster. :param resource_group_name: Name of the resource group to which the resource belongs. :type resource_group_name: str :param workspace_name: The name of the workspace. Workspace names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type workspace_name: str :param cluster_name: The name of the cluster within the specified resource group. Cluster names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type cluster_name: str :param parameters: Additional parameters for cluster update. :type parameters: ~batch_ai.models.ClusterUpdateParameters :keyword callable cls: A custom type or function that will be passed the direct response :return: Cluster, or the result of cls(response) :rtype: ~batch_ai.models.Cluster :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.Cluster"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2018-05-01" content_type = kwargs.pop("content_type", "application/json") accept = "application/json" # Construct URL url = self.update.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', pattern=r'^[-\w\._]+$'), 'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), '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 = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') body_content_kwargs = {} # type: Dict[str, Any] body_content = self._serialize.body(parameters, 'ClusterUpdateParameters') body_content_kwargs['content'] = body_content request = self._client.patch(url, query_parameters, header_parameters, **body_content_kwargs) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize('Cluster', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces/{workspaceName}/clusters/{clusterName}'} # type: ignore def _delete_initial( self, resource_group_name, # type: str workspace_name, # type: str cluster_name, # type: str **kwargs # type: Any ): # type: (...) -> None cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2018-05-01" accept = "application/json" # Construct URL url = self._delete_initial.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', pattern=r'^[-\w\._]+$'), 'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), '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 = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') request = self._client.delete(url, query_parameters, header_parameters) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) _delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces/{workspaceName}/clusters/{clusterName}'} # type: ignore def begin_delete( self, resource_group_name, # type: str workspace_name, # type: str cluster_name, # type: str **kwargs # type: Any ): # type: (...) -> LROPoller[None] """Deletes a Cluster. :param resource_group_name: Name of the resource group to which the resource belongs. :type resource_group_name: str :param workspace_name: The name of the workspace. Workspace names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type workspace_name: str :param cluster_name: The name of the cluster within the specified resource group. Cluster names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type cluster_name: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.PollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of LROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[None] :raises ~azure.core.exceptions.HttpResponseError: """ polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] cls = kwargs.pop('cls', None) # type: ClsType[None] lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval ) cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] if cont_token is None: raw_result = self._delete_initial( resource_group_name=resource_group_name, workspace_name=workspace_name, cluster_name=cluster_name, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map', None) kwargs.pop('content_type', None) def get_long_running_output(pipeline_response): if cls: return cls(pipeline_response, None, {}) path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', pattern=r'^[-\w\._]+$'), 'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } if polling is True: polling_method = ARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) elif polling is False: polling_method = NoPolling() else: polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output ) else: return LROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces/{workspaceName}/clusters/{clusterName}'} # type: ignore def get( self, resource_group_name, # type: str workspace_name, # type: str cluster_name, # type: str **kwargs # type: Any ): # type: (...) -> "_models.Cluster" """Gets information about a Cluster. :param resource_group_name: Name of the resource group to which the resource belongs. :type resource_group_name: str :param workspace_name: The name of the workspace. Workspace names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type workspace_name: str :param cluster_name: The name of the cluster within the specified resource group. Cluster names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type cluster_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Cluster, or the result of cls(response) :rtype: ~batch_ai.models.Cluster :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.Cluster"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2018-05-01" accept = "application/json" # Construct URL url = self.get.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', pattern=r'^[-\w\._]+$'), 'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), '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 = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') request = self._client.get(url, query_parameters, header_parameters) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize('Cluster', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces/{workspaceName}/clusters/{clusterName}'} # type: ignore def list_remote_login_information( self, resource_group_name, # type: str workspace_name, # type: str cluster_name, # type: str **kwargs # type: Any ): # type: (...) -> Iterable["_models.RemoteLoginInformationListResult"] """Get the IP address, port of all the compute nodes in the Cluster. :param resource_group_name: Name of the resource group to which the resource belongs. :type resource_group_name: str :param workspace_name: The name of the workspace. Workspace names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type workspace_name: str :param cluster_name: The name of the cluster within the specified resource group. Cluster names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type cluster_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either RemoteLoginInformationListResult or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~batch_ai.models.RemoteLoginInformationListResult] :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.RemoteLoginInformationListResult"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2018-05-01" accept = "application/json" def prepare_request(next_link=None): # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') if not next_link: # Construct URL url = self.list_remote_login_information.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', pattern=r'^[-\w\._]+$'), 'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), '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 = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') request = self._client.post(url, query_parameters, header_parameters) else: url = next_link query_parameters = {} # type: Dict[str, Any] request = self._client.get(url, query_parameters, header_parameters) return request def extract_data(pipeline_response): deserialized = self._deserialize('RemoteLoginInformationListResult', pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return ItemPaged( get_next, extract_data ) list_remote_login_information.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces/{workspaceName}/clusters/{clusterName}/listRemoteLoginInformation'} # type: ignore def list_by_workspace( self, resource_group_name, # type: str workspace_name, # type: str clusters_list_by_workspace_options=None, # type: Optional["_models.ClustersListByWorkspaceOptions"] **kwargs # type: Any ): # type: (...) -> Iterable["_models.ClusterListResult"] """Gets information about Clusters associated with the given Workspace. :param resource_group_name: Name of the resource group to which the resource belongs. :type resource_group_name: str :param workspace_name: The name of the workspace. Workspace names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type workspace_name: str :param clusters_list_by_workspace_options: Parameter group. :type clusters_list_by_workspace_options: ~batch_ai.models.ClustersListByWorkspaceOptions :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ClusterListResult or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~batch_ai.models.ClusterListResult] :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.ClusterListResult"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) _max_results = None if clusters_list_by_workspace_options is not None: _max_results = clusters_list_by_workspace_options.max_results api_version = "2018-05-01" accept = "application/json" def prepare_request(next_link=None): # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') if not next_link: # Construct URL url = self.list_by_workspace.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', pattern=r'^[-\w\._]+$'), 'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), '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 = {} # type: Dict[str, Any] if _max_results is not None: query_parameters['maxresults'] = self._serialize.query("max_results", _max_results, 'int', maximum=1000, minimum=1) query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') request = self._client.get(url, query_parameters, header_parameters) else: url = next_link query_parameters = {} # type: Dict[str, Any] request = self._client.get(url, query_parameters, header_parameters) return request def extract_data(pipeline_response): deserialized = self._deserialize('ClusterListResult', pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return ItemPaged( get_next, extract_data ) list_by_workspace.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces/{workspaceName}/clusters'} # type: ignore
azure-mgmt-batchai
/azure-mgmt-batchai-7.0.0b1.zip/azure-mgmt-batchai-7.0.0b1/azure/mgmt/batchai/operations/_clusters_operations.py
_clusters_operations.py
from typing import TYPE_CHECKING import warnings from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpRequest, HttpResponse from azure.core.polling import LROPoller, NoPolling, PollingMethod from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.arm_polling import ARMPolling from .. import models as _models if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar, Union T = TypeVar('T') ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] class ClustersOperations(object): """ClustersOperations operations. You should not instantiate this class directly. Instead, you should create a Client instance that instantiates it for you and attaches it as an attribute. :ivar models: Alias to model classes used in this operation group. :type models: ~batch_ai.models :param client: Client for service requests. :param config: Configuration of service client. :param serializer: An object model serializer. :param deserializer: An object model deserializer. """ models = _models def __init__(self, client, config, serializer, deserializer): self._client = client self._serialize = serializer self._deserialize = deserializer self._config = config def _create_initial( self, resource_group_name, # type: str workspace_name, # type: str cluster_name, # type: str parameters, # type: "_models.ClusterCreateParameters" **kwargs # type: Any ): # type: (...) -> Optional["_models.Cluster"] cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.Cluster"]] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2018-05-01" content_type = kwargs.pop("content_type", "application/json") accept = "application/json" # Construct URL url = self._create_initial.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', pattern=r'^[-\w\._]+$'), 'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), '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 = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') body_content_kwargs = {} # type: Dict[str, Any] body_content = self._serialize.body(parameters, 'ClusterCreateParameters') body_content_kwargs['content'] = body_content request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = None if response.status_code == 200: deserialized = self._deserialize('Cluster', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized _create_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces/{workspaceName}/clusters/{clusterName}'} # type: ignore def begin_create( self, resource_group_name, # type: str workspace_name, # type: str cluster_name, # type: str parameters, # type: "_models.ClusterCreateParameters" **kwargs # type: Any ): # type: (...) -> LROPoller["_models.Cluster"] """Creates a Cluster in the given Workspace. :param resource_group_name: Name of the resource group to which the resource belongs. :type resource_group_name: str :param workspace_name: The name of the workspace. Workspace names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type workspace_name: str :param cluster_name: The name of the cluster within the specified resource group. Cluster names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type cluster_name: str :param parameters: The parameters to provide for the Cluster creation. :type parameters: ~batch_ai.models.ClusterCreateParameters :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.PollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of LROPoller that returns either Cluster or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~batch_ai.models.Cluster] :raises ~azure.core.exceptions.HttpResponseError: """ polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] cls = kwargs.pop('cls', None) # type: ClsType["_models.Cluster"] lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval ) cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] if cont_token is None: raw_result = self._create_initial( resource_group_name=resource_group_name, workspace_name=workspace_name, cluster_name=cluster_name, parameters=parameters, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map', None) kwargs.pop('content_type', None) def get_long_running_output(pipeline_response): deserialized = self._deserialize('Cluster', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', pattern=r'^[-\w\._]+$'), 'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } if polling is True: polling_method = ARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) elif polling is False: polling_method = NoPolling() else: polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output ) else: return LROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_create.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces/{workspaceName}/clusters/{clusterName}'} # type: ignore def update( self, resource_group_name, # type: str workspace_name, # type: str cluster_name, # type: str parameters, # type: "_models.ClusterUpdateParameters" **kwargs # type: Any ): # type: (...) -> "_models.Cluster" """Updates properties of a Cluster. :param resource_group_name: Name of the resource group to which the resource belongs. :type resource_group_name: str :param workspace_name: The name of the workspace. Workspace names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type workspace_name: str :param cluster_name: The name of the cluster within the specified resource group. Cluster names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type cluster_name: str :param parameters: Additional parameters for cluster update. :type parameters: ~batch_ai.models.ClusterUpdateParameters :keyword callable cls: A custom type or function that will be passed the direct response :return: Cluster, or the result of cls(response) :rtype: ~batch_ai.models.Cluster :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.Cluster"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2018-05-01" content_type = kwargs.pop("content_type", "application/json") accept = "application/json" # Construct URL url = self.update.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', pattern=r'^[-\w\._]+$'), 'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), '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 = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') body_content_kwargs = {} # type: Dict[str, Any] body_content = self._serialize.body(parameters, 'ClusterUpdateParameters') body_content_kwargs['content'] = body_content request = self._client.patch(url, query_parameters, header_parameters, **body_content_kwargs) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize('Cluster', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces/{workspaceName}/clusters/{clusterName}'} # type: ignore def _delete_initial( self, resource_group_name, # type: str workspace_name, # type: str cluster_name, # type: str **kwargs # type: Any ): # type: (...) -> None cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2018-05-01" accept = "application/json" # Construct URL url = self._delete_initial.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', pattern=r'^[-\w\._]+$'), 'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), '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 = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') request = self._client.delete(url, query_parameters, header_parameters) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) _delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces/{workspaceName}/clusters/{clusterName}'} # type: ignore def begin_delete( self, resource_group_name, # type: str workspace_name, # type: str cluster_name, # type: str **kwargs # type: Any ): # type: (...) -> LROPoller[None] """Deletes a Cluster. :param resource_group_name: Name of the resource group to which the resource belongs. :type resource_group_name: str :param workspace_name: The name of the workspace. Workspace names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type workspace_name: str :param cluster_name: The name of the cluster within the specified resource group. Cluster names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type cluster_name: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.PollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of LROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[None] :raises ~azure.core.exceptions.HttpResponseError: """ polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] cls = kwargs.pop('cls', None) # type: ClsType[None] lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval ) cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] if cont_token is None: raw_result = self._delete_initial( resource_group_name=resource_group_name, workspace_name=workspace_name, cluster_name=cluster_name, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map', None) kwargs.pop('content_type', None) def get_long_running_output(pipeline_response): if cls: return cls(pipeline_response, None, {}) path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', pattern=r'^[-\w\._]+$'), 'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } if polling is True: polling_method = ARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) elif polling is False: polling_method = NoPolling() else: polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output ) else: return LROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces/{workspaceName}/clusters/{clusterName}'} # type: ignore def get( self, resource_group_name, # type: str workspace_name, # type: str cluster_name, # type: str **kwargs # type: Any ): # type: (...) -> "_models.Cluster" """Gets information about a Cluster. :param resource_group_name: Name of the resource group to which the resource belongs. :type resource_group_name: str :param workspace_name: The name of the workspace. Workspace names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type workspace_name: str :param cluster_name: The name of the cluster within the specified resource group. Cluster names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type cluster_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Cluster, or the result of cls(response) :rtype: ~batch_ai.models.Cluster :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.Cluster"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2018-05-01" accept = "application/json" # Construct URL url = self.get.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', pattern=r'^[-\w\._]+$'), 'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), '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 = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') request = self._client.get(url, query_parameters, header_parameters) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize('Cluster', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces/{workspaceName}/clusters/{clusterName}'} # type: ignore def list_remote_login_information( self, resource_group_name, # type: str workspace_name, # type: str cluster_name, # type: str **kwargs # type: Any ): # type: (...) -> Iterable["_models.RemoteLoginInformationListResult"] """Get the IP address, port of all the compute nodes in the Cluster. :param resource_group_name: Name of the resource group to which the resource belongs. :type resource_group_name: str :param workspace_name: The name of the workspace. Workspace names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type workspace_name: str :param cluster_name: The name of the cluster within the specified resource group. Cluster names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type cluster_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either RemoteLoginInformationListResult or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~batch_ai.models.RemoteLoginInformationListResult] :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.RemoteLoginInformationListResult"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2018-05-01" accept = "application/json" def prepare_request(next_link=None): # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') if not next_link: # Construct URL url = self.list_remote_login_information.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', pattern=r'^[-\w\._]+$'), 'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), '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 = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') request = self._client.post(url, query_parameters, header_parameters) else: url = next_link query_parameters = {} # type: Dict[str, Any] request = self._client.get(url, query_parameters, header_parameters) return request def extract_data(pipeline_response): deserialized = self._deserialize('RemoteLoginInformationListResult', pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return ItemPaged( get_next, extract_data ) list_remote_login_information.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces/{workspaceName}/clusters/{clusterName}/listRemoteLoginInformation'} # type: ignore def list_by_workspace( self, resource_group_name, # type: str workspace_name, # type: str clusters_list_by_workspace_options=None, # type: Optional["_models.ClustersListByWorkspaceOptions"] **kwargs # type: Any ): # type: (...) -> Iterable["_models.ClusterListResult"] """Gets information about Clusters associated with the given Workspace. :param resource_group_name: Name of the resource group to which the resource belongs. :type resource_group_name: str :param workspace_name: The name of the workspace. Workspace names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type workspace_name: str :param clusters_list_by_workspace_options: Parameter group. :type clusters_list_by_workspace_options: ~batch_ai.models.ClustersListByWorkspaceOptions :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ClusterListResult or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~batch_ai.models.ClusterListResult] :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.ClusterListResult"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) _max_results = None if clusters_list_by_workspace_options is not None: _max_results = clusters_list_by_workspace_options.max_results api_version = "2018-05-01" accept = "application/json" def prepare_request(next_link=None): # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') if not next_link: # Construct URL url = self.list_by_workspace.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', pattern=r'^[-\w\._]+$'), 'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), '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 = {} # type: Dict[str, Any] if _max_results is not None: query_parameters['maxresults'] = self._serialize.query("max_results", _max_results, 'int', maximum=1000, minimum=1) query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') request = self._client.get(url, query_parameters, header_parameters) else: url = next_link query_parameters = {} # type: Dict[str, Any] request = self._client.get(url, query_parameters, header_parameters) return request def extract_data(pipeline_response): deserialized = self._deserialize('ClusterListResult', pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return ItemPaged( get_next, extract_data ) list_by_workspace.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces/{workspaceName}/clusters'} # type: ignore
0.860765
0.113432
from typing import TYPE_CHECKING import warnings from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpRequest, HttpResponse from azure.core.polling import LROPoller, NoPolling, PollingMethod from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.arm_polling import ARMPolling from .. import models as _models if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar, Union T = TypeVar('T') ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] class FileServersOperations(object): """FileServersOperations operations. You should not instantiate this class directly. Instead, you should create a Client instance that instantiates it for you and attaches it as an attribute. :ivar models: Alias to model classes used in this operation group. :type models: ~batch_ai.models :param client: Client for service requests. :param config: Configuration of service client. :param serializer: An object model serializer. :param deserializer: An object model deserializer. """ models = _models def __init__(self, client, config, serializer, deserializer): self._client = client self._serialize = serializer self._deserialize = deserializer self._config = config def _create_initial( self, resource_group_name, # type: str workspace_name, # type: str file_server_name, # type: str parameters, # type: "_models.FileServerCreateParameters" **kwargs # type: Any ): # type: (...) -> Optional["_models.FileServer"] cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.FileServer"]] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2018-05-01" content_type = kwargs.pop("content_type", "application/json") accept = "application/json" # Construct URL url = self._create_initial.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', pattern=r'^[-\w\._]+$'), 'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'fileServerName': self._serialize.url("file_server_name", file_server_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), '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 = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') body_content_kwargs = {} # type: Dict[str, Any] body_content = self._serialize.body(parameters, 'FileServerCreateParameters') body_content_kwargs['content'] = body_content request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = None if response.status_code == 200: deserialized = self._deserialize('FileServer', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized _create_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces/{workspaceName}/fileServers/{fileServerName}'} # type: ignore def begin_create( self, resource_group_name, # type: str workspace_name, # type: str file_server_name, # type: str parameters, # type: "_models.FileServerCreateParameters" **kwargs # type: Any ): # type: (...) -> LROPoller["_models.FileServer"] """Creates a File Server in the given workspace. :param resource_group_name: Name of the resource group to which the resource belongs. :type resource_group_name: str :param workspace_name: The name of the workspace. Workspace names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type workspace_name: str :param file_server_name: The name of the file server within the specified resource group. File server names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type file_server_name: str :param parameters: The parameters to provide for File Server creation. :type parameters: ~batch_ai.models.FileServerCreateParameters :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.PollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of LROPoller that returns either FileServer or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~batch_ai.models.FileServer] :raises ~azure.core.exceptions.HttpResponseError: """ polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] cls = kwargs.pop('cls', None) # type: ClsType["_models.FileServer"] lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval ) cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] if cont_token is None: raw_result = self._create_initial( resource_group_name=resource_group_name, workspace_name=workspace_name, file_server_name=file_server_name, parameters=parameters, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map', None) kwargs.pop('content_type', None) def get_long_running_output(pipeline_response): deserialized = self._deserialize('FileServer', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', pattern=r'^[-\w\._]+$'), 'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'fileServerName': self._serialize.url("file_server_name", file_server_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } if polling is True: polling_method = ARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) elif polling is False: polling_method = NoPolling() else: polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output ) else: return LROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_create.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces/{workspaceName}/fileServers/{fileServerName}'} # type: ignore def list_by_workspace( self, resource_group_name, # type: str workspace_name, # type: str file_servers_list_by_workspace_options=None, # type: Optional["_models.FileServersListByWorkspaceOptions"] **kwargs # type: Any ): # type: (...) -> Iterable["_models.FileServerListResult"] """Gets a list of File Servers associated with the specified workspace. :param resource_group_name: Name of the resource group to which the resource belongs. :type resource_group_name: str :param workspace_name: The name of the workspace. Workspace names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type workspace_name: str :param file_servers_list_by_workspace_options: Parameter group. :type file_servers_list_by_workspace_options: ~batch_ai.models.FileServersListByWorkspaceOptions :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either FileServerListResult or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~batch_ai.models.FileServerListResult] :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.FileServerListResult"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) _max_results = None if file_servers_list_by_workspace_options is not None: _max_results = file_servers_list_by_workspace_options.max_results api_version = "2018-05-01" accept = "application/json" def prepare_request(next_link=None): # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') if not next_link: # Construct URL url = self.list_by_workspace.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', pattern=r'^[-\w\._]+$'), 'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), '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 = {} # type: Dict[str, Any] if _max_results is not None: query_parameters['maxresults'] = self._serialize.query("max_results", _max_results, 'int', maximum=1000, minimum=1) query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') request = self._client.get(url, query_parameters, header_parameters) else: url = next_link query_parameters = {} # type: Dict[str, Any] request = self._client.get(url, query_parameters, header_parameters) return request def extract_data(pipeline_response): deserialized = self._deserialize('FileServerListResult', pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return ItemPaged( get_next, extract_data ) list_by_workspace.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces/{workspaceName}/fileServers'} # type: ignore
azure-mgmt-batchai
/azure-mgmt-batchai-7.0.0b1.zip/azure-mgmt-batchai-7.0.0b1/azure/mgmt/batchai/operations/_file_servers_operations.py
_file_servers_operations.py
from typing import TYPE_CHECKING import warnings from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpRequest, HttpResponse from azure.core.polling import LROPoller, NoPolling, PollingMethod from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.arm_polling import ARMPolling from .. import models as _models if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar, Union T = TypeVar('T') ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] class FileServersOperations(object): """FileServersOperations operations. You should not instantiate this class directly. Instead, you should create a Client instance that instantiates it for you and attaches it as an attribute. :ivar models: Alias to model classes used in this operation group. :type models: ~batch_ai.models :param client: Client for service requests. :param config: Configuration of service client. :param serializer: An object model serializer. :param deserializer: An object model deserializer. """ models = _models def __init__(self, client, config, serializer, deserializer): self._client = client self._serialize = serializer self._deserialize = deserializer self._config = config def _create_initial( self, resource_group_name, # type: str workspace_name, # type: str file_server_name, # type: str parameters, # type: "_models.FileServerCreateParameters" **kwargs # type: Any ): # type: (...) -> Optional["_models.FileServer"] cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.FileServer"]] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2018-05-01" content_type = kwargs.pop("content_type", "application/json") accept = "application/json" # Construct URL url = self._create_initial.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', pattern=r'^[-\w\._]+$'), 'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'fileServerName': self._serialize.url("file_server_name", file_server_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), '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 = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') body_content_kwargs = {} # type: Dict[str, Any] body_content = self._serialize.body(parameters, 'FileServerCreateParameters') body_content_kwargs['content'] = body_content request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = None if response.status_code == 200: deserialized = self._deserialize('FileServer', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized _create_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces/{workspaceName}/fileServers/{fileServerName}'} # type: ignore def begin_create( self, resource_group_name, # type: str workspace_name, # type: str file_server_name, # type: str parameters, # type: "_models.FileServerCreateParameters" **kwargs # type: Any ): # type: (...) -> LROPoller["_models.FileServer"] """Creates a File Server in the given workspace. :param resource_group_name: Name of the resource group to which the resource belongs. :type resource_group_name: str :param workspace_name: The name of the workspace. Workspace names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type workspace_name: str :param file_server_name: The name of the file server within the specified resource group. File server names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type file_server_name: str :param parameters: The parameters to provide for File Server creation. :type parameters: ~batch_ai.models.FileServerCreateParameters :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.PollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of LROPoller that returns either FileServer or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~batch_ai.models.FileServer] :raises ~azure.core.exceptions.HttpResponseError: """ polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] cls = kwargs.pop('cls', None) # type: ClsType["_models.FileServer"] lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval ) cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] if cont_token is None: raw_result = self._create_initial( resource_group_name=resource_group_name, workspace_name=workspace_name, file_server_name=file_server_name, parameters=parameters, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map', None) kwargs.pop('content_type', None) def get_long_running_output(pipeline_response): deserialized = self._deserialize('FileServer', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', pattern=r'^[-\w\._]+$'), 'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'fileServerName': self._serialize.url("file_server_name", file_server_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } if polling is True: polling_method = ARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) elif polling is False: polling_method = NoPolling() else: polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output ) else: return LROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_create.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces/{workspaceName}/fileServers/{fileServerName}'} # type: ignore def list_by_workspace( self, resource_group_name, # type: str workspace_name, # type: str file_servers_list_by_workspace_options=None, # type: Optional["_models.FileServersListByWorkspaceOptions"] **kwargs # type: Any ): # type: (...) -> Iterable["_models.FileServerListResult"] """Gets a list of File Servers associated with the specified workspace. :param resource_group_name: Name of the resource group to which the resource belongs. :type resource_group_name: str :param workspace_name: The name of the workspace. Workspace names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type workspace_name: str :param file_servers_list_by_workspace_options: Parameter group. :type file_servers_list_by_workspace_options: ~batch_ai.models.FileServersListByWorkspaceOptions :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either FileServerListResult or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~batch_ai.models.FileServerListResult] :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.FileServerListResult"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) _max_results = None if file_servers_list_by_workspace_options is not None: _max_results = file_servers_list_by_workspace_options.max_results api_version = "2018-05-01" accept = "application/json" def prepare_request(next_link=None): # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') if not next_link: # Construct URL url = self.list_by_workspace.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', pattern=r'^[-\w\._]+$'), 'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), '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 = {} # type: Dict[str, Any] if _max_results is not None: query_parameters['maxresults'] = self._serialize.query("max_results", _max_results, 'int', maximum=1000, minimum=1) query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') request = self._client.get(url, query_parameters, header_parameters) else: url = next_link query_parameters = {} # type: Dict[str, Any] request = self._client.get(url, query_parameters, header_parameters) return request def extract_data(pipeline_response): deserialized = self._deserialize('FileServerListResult', pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return ItemPaged( get_next, extract_data ) list_by_workspace.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces/{workspaceName}/fileServers'} # type: ignore
0.830319
0.078395
from typing import TYPE_CHECKING import warnings from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpRequest, HttpResponse from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar T = TypeVar('T') ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] class UsagesOperations(object): """UsagesOperations operations. You should not instantiate this class directly. Instead, you should create a Client instance that instantiates it for you and attaches it as an attribute. :ivar models: Alias to model classes used in this operation group. :type models: ~batch_ai.models :param client: Client for service requests. :param config: Configuration of service client. :param serializer: An object model serializer. :param deserializer: An object model deserializer. """ models = _models def __init__(self, client, config, serializer, deserializer): self._client = client self._serialize = serializer self._deserialize = deserializer self._config = config def list( self, location, # type: str **kwargs # type: Any ): # type: (...) -> Iterable["_models.ListUsagesResult"] """Gets the current usage information as well as limits for Batch AI resources for given subscription. :param location: The location for which resource usage is queried. :type location: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ListUsagesResult or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~batch_ai.models.ListUsagesResult] :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.ListUsagesResult"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2018-05-01" accept = "application/json" def prepare_request(next_link=None): # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') if not next_link: # Construct URL url = self.list.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), 'location': self._serialize.url("location", location, 'str', pattern=r'^[-\w\._]+$'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') request = self._client.get(url, query_parameters, header_parameters) else: url = next_link query_parameters = {} # type: Dict[str, Any] request = self._client.get(url, query_parameters, header_parameters) return request def extract_data(pipeline_response): deserialized = self._deserialize('ListUsagesResult', pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return ItemPaged( get_next, extract_data ) list.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.BatchAI/locations/{location}/usages'} # type: ignore
azure-mgmt-batchai
/azure-mgmt-batchai-7.0.0b1.zip/azure-mgmt-batchai-7.0.0b1/azure/mgmt/batchai/operations/_usages_operations.py
_usages_operations.py
from typing import TYPE_CHECKING import warnings from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpRequest, HttpResponse from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar T = TypeVar('T') ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] class UsagesOperations(object): """UsagesOperations operations. You should not instantiate this class directly. Instead, you should create a Client instance that instantiates it for you and attaches it as an attribute. :ivar models: Alias to model classes used in this operation group. :type models: ~batch_ai.models :param client: Client for service requests. :param config: Configuration of service client. :param serializer: An object model serializer. :param deserializer: An object model deserializer. """ models = _models def __init__(self, client, config, serializer, deserializer): self._client = client self._serialize = serializer self._deserialize = deserializer self._config = config def list( self, location, # type: str **kwargs # type: Any ): # type: (...) -> Iterable["_models.ListUsagesResult"] """Gets the current usage information as well as limits for Batch AI resources for given subscription. :param location: The location for which resource usage is queried. :type location: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ListUsagesResult or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~batch_ai.models.ListUsagesResult] :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.ListUsagesResult"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2018-05-01" accept = "application/json" def prepare_request(next_link=None): # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') if not next_link: # Construct URL url = self.list.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), 'location': self._serialize.url("location", location, 'str', pattern=r'^[-\w\._]+$'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') request = self._client.get(url, query_parameters, header_parameters) else: url = next_link query_parameters = {} # type: Dict[str, Any] request = self._client.get(url, query_parameters, header_parameters) return request def extract_data(pipeline_response): deserialized = self._deserialize('ListUsagesResult', pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return ItemPaged( get_next, extract_data ) list.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.BatchAI/locations/{location}/usages'} # type: ignore
0.859546
0.103115
from typing import TYPE_CHECKING import warnings from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpRequest, HttpResponse from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar T = TypeVar('T') ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] class Operations(object): """Operations operations. You should not instantiate this class directly. Instead, you should create a Client instance that instantiates it for you and attaches it as an attribute. :ivar models: Alias to model classes used in this operation group. :type models: ~batch_ai.models :param client: Client for service requests. :param config: Configuration of service client. :param serializer: An object model serializer. :param deserializer: An object model deserializer. """ models = _models def __init__(self, client, config, serializer, deserializer): self._client = client self._serialize = serializer self._deserialize = deserializer self._config = config def list( self, **kwargs # type: Any ): # type: (...) -> Iterable["_models.OperationListResult"] """Lists available operations for the Microsoft.BatchAI provider. :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either OperationListResult or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~batch_ai.models.OperationListResult] :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.OperationListResult"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2018-05-01" accept = "application/json" def prepare_request(next_link=None): # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') if not next_link: # Construct URL url = self.list.metadata['url'] # type: ignore # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') request = self._client.get(url, query_parameters, header_parameters) else: url = next_link query_parameters = {} # type: Dict[str, Any] request = self._client.get(url, query_parameters, header_parameters) return request def extract_data(pipeline_response): deserialized = self._deserialize('OperationListResult', pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return ItemPaged( get_next, extract_data ) list.metadata = {'url': '/providers/Microsoft.BatchAI/operations'} # type: ignore
azure-mgmt-batchai
/azure-mgmt-batchai-7.0.0b1.zip/azure-mgmt-batchai-7.0.0b1/azure/mgmt/batchai/operations/_operations.py
_operations.py
from typing import TYPE_CHECKING import warnings from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpRequest, HttpResponse from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar T = TypeVar('T') ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] class Operations(object): """Operations operations. You should not instantiate this class directly. Instead, you should create a Client instance that instantiates it for you and attaches it as an attribute. :ivar models: Alias to model classes used in this operation group. :type models: ~batch_ai.models :param client: Client for service requests. :param config: Configuration of service client. :param serializer: An object model serializer. :param deserializer: An object model deserializer. """ models = _models def __init__(self, client, config, serializer, deserializer): self._client = client self._serialize = serializer self._deserialize = deserializer self._config = config def list( self, **kwargs # type: Any ): # type: (...) -> Iterable["_models.OperationListResult"] """Lists available operations for the Microsoft.BatchAI provider. :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either OperationListResult or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~batch_ai.models.OperationListResult] :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.OperationListResult"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2018-05-01" accept = "application/json" def prepare_request(next_link=None): # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') if not next_link: # Construct URL url = self.list.metadata['url'] # type: ignore # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') request = self._client.get(url, query_parameters, header_parameters) else: url = next_link query_parameters = {} # type: Dict[str, Any] request = self._client.get(url, query_parameters, header_parameters) return request def extract_data(pipeline_response): deserialized = self._deserialize('OperationListResult', pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return ItemPaged( get_next, extract_data ) list.metadata = {'url': '/providers/Microsoft.BatchAI/operations'} # type: ignore
0.854824
0.097777
from typing import Any, TYPE_CHECKING from azure.core.configuration import Configuration from azure.core.pipeline import policies from azure.mgmt.core.policies import ARMHttpLoggingPolicy from .._version import VERSION if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential class BatchAIConfiguration(Configuration): """Configuration for BatchAI. Note that all parameters used to create this instance are saved as instance attributes. :param credential: Credential needed for the client to connect to Azure. :type credential: ~azure.core.credentials_async.AsyncTokenCredential :param subscription_id: The subscriptionID for the Azure user. :type subscription_id: str """ def __init__( self, credential: "AsyncTokenCredential", subscription_id: str, **kwargs: Any ) -> None: if credential is None: raise ValueError("Parameter 'credential' must not be None.") if subscription_id is None: raise ValueError("Parameter 'subscription_id' must not be None.") super(BatchAIConfiguration, self).__init__(**kwargs) self.credential = credential self.subscription_id = subscription_id self.api_version = "2018-05-01" self.credential_scopes = kwargs.pop('credential_scopes', ['https://management.azure.com/.default']) kwargs.setdefault('sdk_moniker', 'mgmt-batchai/{}'.format(VERSION)) self._configure(**kwargs) def _configure( self, **kwargs: Any ) -> None: self.user_agent_policy = kwargs.get('user_agent_policy') or policies.UserAgentPolicy(**kwargs) self.headers_policy = kwargs.get('headers_policy') or policies.HeadersPolicy(**kwargs) self.proxy_policy = kwargs.get('proxy_policy') or policies.ProxyPolicy(**kwargs) self.logging_policy = kwargs.get('logging_policy') or policies.NetworkTraceLoggingPolicy(**kwargs) self.http_logging_policy = kwargs.get('http_logging_policy') or ARMHttpLoggingPolicy(**kwargs) self.retry_policy = kwargs.get('retry_policy') or policies.AsyncRetryPolicy(**kwargs) self.custom_hook_policy = kwargs.get('custom_hook_policy') or policies.CustomHookPolicy(**kwargs) self.redirect_policy = kwargs.get('redirect_policy') or policies.AsyncRedirectPolicy(**kwargs) self.authentication_policy = kwargs.get('authentication_policy') if self.credential and not self.authentication_policy: self.authentication_policy = policies.AsyncBearerTokenCredentialPolicy(self.credential, *self.credential_scopes, **kwargs)
azure-mgmt-batchai
/azure-mgmt-batchai-7.0.0b1.zip/azure-mgmt-batchai-7.0.0b1/azure/mgmt/batchai/aio/_configuration.py
_configuration.py
from typing import Any, TYPE_CHECKING from azure.core.configuration import Configuration from azure.core.pipeline import policies from azure.mgmt.core.policies import ARMHttpLoggingPolicy from .._version import VERSION if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential class BatchAIConfiguration(Configuration): """Configuration for BatchAI. Note that all parameters used to create this instance are saved as instance attributes. :param credential: Credential needed for the client to connect to Azure. :type credential: ~azure.core.credentials_async.AsyncTokenCredential :param subscription_id: The subscriptionID for the Azure user. :type subscription_id: str """ def __init__( self, credential: "AsyncTokenCredential", subscription_id: str, **kwargs: Any ) -> None: if credential is None: raise ValueError("Parameter 'credential' must not be None.") if subscription_id is None: raise ValueError("Parameter 'subscription_id' must not be None.") super(BatchAIConfiguration, self).__init__(**kwargs) self.credential = credential self.subscription_id = subscription_id self.api_version = "2018-05-01" self.credential_scopes = kwargs.pop('credential_scopes', ['https://management.azure.com/.default']) kwargs.setdefault('sdk_moniker', 'mgmt-batchai/{}'.format(VERSION)) self._configure(**kwargs) def _configure( self, **kwargs: Any ) -> None: self.user_agent_policy = kwargs.get('user_agent_policy') or policies.UserAgentPolicy(**kwargs) self.headers_policy = kwargs.get('headers_policy') or policies.HeadersPolicy(**kwargs) self.proxy_policy = kwargs.get('proxy_policy') or policies.ProxyPolicy(**kwargs) self.logging_policy = kwargs.get('logging_policy') or policies.NetworkTraceLoggingPolicy(**kwargs) self.http_logging_policy = kwargs.get('http_logging_policy') or ARMHttpLoggingPolicy(**kwargs) self.retry_policy = kwargs.get('retry_policy') or policies.AsyncRetryPolicy(**kwargs) self.custom_hook_policy = kwargs.get('custom_hook_policy') or policies.CustomHookPolicy(**kwargs) self.redirect_policy = kwargs.get('redirect_policy') or policies.AsyncRedirectPolicy(**kwargs) self.authentication_policy = kwargs.get('authentication_policy') if self.credential and not self.authentication_policy: self.authentication_policy = policies.AsyncBearerTokenCredentialPolicy(self.credential, *self.credential_scopes, **kwargs)
0.81841
0.08886
from typing import Any, Optional, TYPE_CHECKING from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest from azure.mgmt.core import AsyncARMPipelineClient from msrest import Deserializer, Serializer if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential from ._configuration import BatchAIConfiguration from .operations import Operations from .operations import UsagesOperations from .operations import WorkspacesOperations from .operations import ExperimentsOperations from .operations import JobsOperations from .operations import FileServersOperations from .operations import ClustersOperations from .. import models class BatchAI(object): """The Azure BatchAI Management API. :ivar operations: Operations operations :vartype operations: batch_ai.aio.operations.Operations :ivar usages: UsagesOperations operations :vartype usages: batch_ai.aio.operations.UsagesOperations :ivar workspaces: WorkspacesOperations operations :vartype workspaces: batch_ai.aio.operations.WorkspacesOperations :ivar experiments: ExperimentsOperations operations :vartype experiments: batch_ai.aio.operations.ExperimentsOperations :ivar jobs: JobsOperations operations :vartype jobs: batch_ai.aio.operations.JobsOperations :ivar file_servers: FileServersOperations operations :vartype file_servers: batch_ai.aio.operations.FileServersOperations :ivar clusters: ClustersOperations operations :vartype clusters: batch_ai.aio.operations.ClustersOperations :param credential: Credential needed for the client to connect to Azure. :type credential: ~azure.core.credentials_async.AsyncTokenCredential :param subscription_id: The subscriptionID for the Azure user. :type subscription_id: str :param str base_url: Service URL :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. """ def __init__( self, credential: "AsyncTokenCredential", subscription_id: str, base_url: Optional[str] = None, **kwargs: Any ) -> None: if not base_url: base_url = 'https://management.azure.com' self._config = BatchAIConfiguration(credential, subscription_id, **kwargs) self._client = AsyncARMPipelineClient(base_url=base_url, config=self._config, **kwargs) client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} self._serialize = Serializer(client_models) self._serialize.client_side_validation = False self._deserialize = Deserializer(client_models) self.operations = Operations( self._client, self._config, self._serialize, self._deserialize) self.usages = UsagesOperations( self._client, self._config, self._serialize, self._deserialize) self.workspaces = WorkspacesOperations( self._client, self._config, self._serialize, self._deserialize) self.experiments = ExperimentsOperations( self._client, self._config, self._serialize, self._deserialize) self.jobs = JobsOperations( self._client, self._config, self._serialize, self._deserialize) self.file_servers = FileServersOperations( self._client, self._config, self._serialize, self._deserialize) self.clusters = ClustersOperations( self._client, self._config, self._serialize, self._deserialize) async def _send_request(self, http_request: HttpRequest, **kwargs: Any) -> AsyncHttpResponse: """Runs the network request through the client's chained policies. :param http_request: The network request you want to make. Required. :type http_request: ~azure.core.pipeline.transport.HttpRequest :keyword bool stream: Whether the response payload will be streamed. Defaults to True. :return: The response of your network call. Does not do error handling on your response. :rtype: ~azure.core.pipeline.transport.AsyncHttpResponse """ path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } http_request.url = self._client.format_url(http_request.url, **path_format_arguments) stream = kwargs.pop("stream", True) pipeline_response = await self._client._pipeline.run(http_request, stream=stream, **kwargs) return pipeline_response.http_response async def close(self) -> None: await self._client.close() async def __aenter__(self) -> "BatchAI": await self._client.__aenter__() return self async def __aexit__(self, *exc_details) -> None: await self._client.__aexit__(*exc_details)
azure-mgmt-batchai
/azure-mgmt-batchai-7.0.0b1.zip/azure-mgmt-batchai-7.0.0b1/azure/mgmt/batchai/aio/_batch_ai.py
_batch_ai.py
from typing import Any, Optional, TYPE_CHECKING from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest from azure.mgmt.core import AsyncARMPipelineClient from msrest import Deserializer, Serializer if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential from ._configuration import BatchAIConfiguration from .operations import Operations from .operations import UsagesOperations from .operations import WorkspacesOperations from .operations import ExperimentsOperations from .operations import JobsOperations from .operations import FileServersOperations from .operations import ClustersOperations from .. import models class BatchAI(object): """The Azure BatchAI Management API. :ivar operations: Operations operations :vartype operations: batch_ai.aio.operations.Operations :ivar usages: UsagesOperations operations :vartype usages: batch_ai.aio.operations.UsagesOperations :ivar workspaces: WorkspacesOperations operations :vartype workspaces: batch_ai.aio.operations.WorkspacesOperations :ivar experiments: ExperimentsOperations operations :vartype experiments: batch_ai.aio.operations.ExperimentsOperations :ivar jobs: JobsOperations operations :vartype jobs: batch_ai.aio.operations.JobsOperations :ivar file_servers: FileServersOperations operations :vartype file_servers: batch_ai.aio.operations.FileServersOperations :ivar clusters: ClustersOperations operations :vartype clusters: batch_ai.aio.operations.ClustersOperations :param credential: Credential needed for the client to connect to Azure. :type credential: ~azure.core.credentials_async.AsyncTokenCredential :param subscription_id: The subscriptionID for the Azure user. :type subscription_id: str :param str base_url: Service URL :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. """ def __init__( self, credential: "AsyncTokenCredential", subscription_id: str, base_url: Optional[str] = None, **kwargs: Any ) -> None: if not base_url: base_url = 'https://management.azure.com' self._config = BatchAIConfiguration(credential, subscription_id, **kwargs) self._client = AsyncARMPipelineClient(base_url=base_url, config=self._config, **kwargs) client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} self._serialize = Serializer(client_models) self._serialize.client_side_validation = False self._deserialize = Deserializer(client_models) self.operations = Operations( self._client, self._config, self._serialize, self._deserialize) self.usages = UsagesOperations( self._client, self._config, self._serialize, self._deserialize) self.workspaces = WorkspacesOperations( self._client, self._config, self._serialize, self._deserialize) self.experiments = ExperimentsOperations( self._client, self._config, self._serialize, self._deserialize) self.jobs = JobsOperations( self._client, self._config, self._serialize, self._deserialize) self.file_servers = FileServersOperations( self._client, self._config, self._serialize, self._deserialize) self.clusters = ClustersOperations( self._client, self._config, self._serialize, self._deserialize) async def _send_request(self, http_request: HttpRequest, **kwargs: Any) -> AsyncHttpResponse: """Runs the network request through the client's chained policies. :param http_request: The network request you want to make. Required. :type http_request: ~azure.core.pipeline.transport.HttpRequest :keyword bool stream: Whether the response payload will be streamed. Defaults to True. :return: The response of your network call. Does not do error handling on your response. :rtype: ~azure.core.pipeline.transport.AsyncHttpResponse """ path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } http_request.url = self._client.format_url(http_request.url, **path_format_arguments) stream = kwargs.pop("stream", True) pipeline_response = await self._client._pipeline.run(http_request, stream=stream, **kwargs) return pipeline_response.http_response async def close(self) -> None: await self._client.close() async def __aenter__(self) -> "BatchAI": await self._client.__aenter__() return self async def __aexit__(self, *exc_details) -> None: await self._client.__aexit__(*exc_details)
0.866429
0.10942
from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union import warnings from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling from ... import models as _models T = TypeVar('T') ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] class ExperimentsOperations: """ExperimentsOperations async operations. You should not instantiate this class directly. Instead, you should create a Client instance that instantiates it for you and attaches it as an attribute. :ivar models: Alias to model classes used in this operation group. :type models: ~batch_ai.models :param client: Client for service requests. :param config: Configuration of service client. :param serializer: An object model serializer. :param deserializer: An object model deserializer. """ models = _models def __init__(self, client, config, serializer, deserializer) -> None: self._client = client self._serialize = serializer self._deserialize = deserializer self._config = config def list_by_workspace( self, resource_group_name: str, workspace_name: str, experiments_list_by_workspace_options: Optional["_models.ExperimentsListByWorkspaceOptions"] = None, **kwargs: Any ) -> AsyncIterable["_models.ExperimentListResult"]: """Gets a list of Experiments within the specified Workspace. :param resource_group_name: Name of the resource group to which the resource belongs. :type resource_group_name: str :param workspace_name: The name of the workspace. Workspace names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type workspace_name: str :param experiments_list_by_workspace_options: Parameter group. :type experiments_list_by_workspace_options: ~batch_ai.models.ExperimentsListByWorkspaceOptions :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ExperimentListResult or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~batch_ai.models.ExperimentListResult] :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.ExperimentListResult"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) _max_results = None if experiments_list_by_workspace_options is not None: _max_results = experiments_list_by_workspace_options.max_results api_version = "2018-05-01" accept = "application/json" def prepare_request(next_link=None): # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') if not next_link: # Construct URL url = self.list_by_workspace.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', pattern=r'^[-\w\._]+$'), 'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), '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 = {} # type: Dict[str, Any] if _max_results is not None: query_parameters['maxresults'] = self._serialize.query("max_results", _max_results, 'int', maximum=1000, minimum=1) query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') request = self._client.get(url, query_parameters, header_parameters) else: url = next_link query_parameters = {} # type: Dict[str, Any] request = self._client.get(url, query_parameters, header_parameters) return request async def extract_data(pipeline_response): deserialized = self._deserialize('ExperimentListResult', pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged( get_next, extract_data ) list_by_workspace.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces/{workspaceName}/experiments'} # type: ignore async def _create_initial( self, resource_group_name: str, workspace_name: str, experiment_name: str, **kwargs: Any ) -> Optional["_models.Experiment"]: cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.Experiment"]] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2018-05-01" accept = "application/json" # Construct URL url = self._create_initial.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', pattern=r'^[-\w\._]+$'), 'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'experimentName': self._serialize.url("experiment_name", experiment_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), '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 = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') request = self._client.put(url, query_parameters, header_parameters) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = None if response.status_code == 200: deserialized = self._deserialize('Experiment', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized _create_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces/{workspaceName}/experiments/{experimentName}'} # type: ignore async def begin_create( self, resource_group_name: str, workspace_name: str, experiment_name: str, **kwargs: Any ) -> AsyncLROPoller["_models.Experiment"]: """Creates an Experiment. :param resource_group_name: Name of the resource group to which the resource belongs. :type resource_group_name: str :param workspace_name: The name of the workspace. Workspace names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type workspace_name: str :param experiment_name: The name of the experiment. Experiment names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type experiment_name: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of AsyncLROPoller that returns either Experiment or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~batch_ai.models.Experiment] :raises ~azure.core.exceptions.HttpResponseError: """ polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] cls = kwargs.pop('cls', None) # type: ClsType["_models.Experiment"] lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval ) cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] if cont_token is None: raw_result = await self._create_initial( resource_group_name=resource_group_name, workspace_name=workspace_name, experiment_name=experiment_name, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map', None) kwargs.pop('content_type', None) def get_long_running_output(pipeline_response): deserialized = self._deserialize('Experiment', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', pattern=r'^[-\w\._]+$'), 'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'experimentName': self._serialize.url("experiment_name", experiment_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } if polling is True: polling_method = AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) elif polling is False: polling_method = AsyncNoPolling() else: polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output ) else: return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_create.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces/{workspaceName}/experiments/{experimentName}'} # type: ignore async def _delete_initial( self, resource_group_name: str, workspace_name: str, experiment_name: str, **kwargs: Any ) -> None: cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2018-05-01" accept = "application/json" # Construct URL url = self._delete_initial.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', pattern=r'^[-\w\._]+$'), 'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'experimentName': self._serialize.url("experiment_name", experiment_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), '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 = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') request = self._client.delete(url, query_parameters, header_parameters) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) _delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces/{workspaceName}/experiments/{experimentName}'} # type: ignore async def begin_delete( self, resource_group_name: str, workspace_name: str, experiment_name: str, **kwargs: Any ) -> AsyncLROPoller[None]: """Deletes an Experiment. :param resource_group_name: Name of the resource group to which the resource belongs. :type resource_group_name: str :param workspace_name: The name of the workspace. Workspace names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type workspace_name: str :param experiment_name: The name of the experiment. Experiment names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type experiment_name: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[None] :raises ~azure.core.exceptions.HttpResponseError: """ polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] cls = kwargs.pop('cls', None) # type: ClsType[None] lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval ) cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] if cont_token is None: raw_result = await self._delete_initial( resource_group_name=resource_group_name, workspace_name=workspace_name, experiment_name=experiment_name, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map', None) kwargs.pop('content_type', None) def get_long_running_output(pipeline_response): if cls: return cls(pipeline_response, None, {}) path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', pattern=r'^[-\w\._]+$'), 'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'experimentName': self._serialize.url("experiment_name", experiment_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } if polling is True: polling_method = AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) elif polling is False: polling_method = AsyncNoPolling() else: polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output ) else: return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces/{workspaceName}/experiments/{experimentName}'} # type: ignore async def get( self, resource_group_name: str, workspace_name: str, experiment_name: str, **kwargs: Any ) -> "_models.Experiment": """Gets information about an Experiment. :param resource_group_name: Name of the resource group to which the resource belongs. :type resource_group_name: str :param workspace_name: The name of the workspace. Workspace names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type workspace_name: str :param experiment_name: The name of the experiment. Experiment names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type experiment_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Experiment, or the result of cls(response) :rtype: ~batch_ai.models.Experiment :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.Experiment"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2018-05-01" accept = "application/json" # Construct URL url = self.get.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', pattern=r'^[-\w\._]+$'), 'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'experimentName': self._serialize.url("experiment_name", experiment_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), '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 = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') request = self._client.get(url, query_parameters, header_parameters) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize('Experiment', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces/{workspaceName}/experiments/{experimentName}'} # type: ignore
azure-mgmt-batchai
/azure-mgmt-batchai-7.0.0b1.zip/azure-mgmt-batchai-7.0.0b1/azure/mgmt/batchai/aio/operations/_experiments_operations.py
_experiments_operations.py
from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union import warnings from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling from ... import models as _models T = TypeVar('T') ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] class ExperimentsOperations: """ExperimentsOperations async operations. You should not instantiate this class directly. Instead, you should create a Client instance that instantiates it for you and attaches it as an attribute. :ivar models: Alias to model classes used in this operation group. :type models: ~batch_ai.models :param client: Client for service requests. :param config: Configuration of service client. :param serializer: An object model serializer. :param deserializer: An object model deserializer. """ models = _models def __init__(self, client, config, serializer, deserializer) -> None: self._client = client self._serialize = serializer self._deserialize = deserializer self._config = config def list_by_workspace( self, resource_group_name: str, workspace_name: str, experiments_list_by_workspace_options: Optional["_models.ExperimentsListByWorkspaceOptions"] = None, **kwargs: Any ) -> AsyncIterable["_models.ExperimentListResult"]: """Gets a list of Experiments within the specified Workspace. :param resource_group_name: Name of the resource group to which the resource belongs. :type resource_group_name: str :param workspace_name: The name of the workspace. Workspace names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type workspace_name: str :param experiments_list_by_workspace_options: Parameter group. :type experiments_list_by_workspace_options: ~batch_ai.models.ExperimentsListByWorkspaceOptions :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ExperimentListResult or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~batch_ai.models.ExperimentListResult] :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.ExperimentListResult"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) _max_results = None if experiments_list_by_workspace_options is not None: _max_results = experiments_list_by_workspace_options.max_results api_version = "2018-05-01" accept = "application/json" def prepare_request(next_link=None): # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') if not next_link: # Construct URL url = self.list_by_workspace.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', pattern=r'^[-\w\._]+$'), 'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), '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 = {} # type: Dict[str, Any] if _max_results is not None: query_parameters['maxresults'] = self._serialize.query("max_results", _max_results, 'int', maximum=1000, minimum=1) query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') request = self._client.get(url, query_parameters, header_parameters) else: url = next_link query_parameters = {} # type: Dict[str, Any] request = self._client.get(url, query_parameters, header_parameters) return request async def extract_data(pipeline_response): deserialized = self._deserialize('ExperimentListResult', pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged( get_next, extract_data ) list_by_workspace.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces/{workspaceName}/experiments'} # type: ignore async def _create_initial( self, resource_group_name: str, workspace_name: str, experiment_name: str, **kwargs: Any ) -> Optional["_models.Experiment"]: cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.Experiment"]] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2018-05-01" accept = "application/json" # Construct URL url = self._create_initial.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', pattern=r'^[-\w\._]+$'), 'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'experimentName': self._serialize.url("experiment_name", experiment_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), '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 = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') request = self._client.put(url, query_parameters, header_parameters) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = None if response.status_code == 200: deserialized = self._deserialize('Experiment', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized _create_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces/{workspaceName}/experiments/{experimentName}'} # type: ignore async def begin_create( self, resource_group_name: str, workspace_name: str, experiment_name: str, **kwargs: Any ) -> AsyncLROPoller["_models.Experiment"]: """Creates an Experiment. :param resource_group_name: Name of the resource group to which the resource belongs. :type resource_group_name: str :param workspace_name: The name of the workspace. Workspace names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type workspace_name: str :param experiment_name: The name of the experiment. Experiment names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type experiment_name: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of AsyncLROPoller that returns either Experiment or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~batch_ai.models.Experiment] :raises ~azure.core.exceptions.HttpResponseError: """ polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] cls = kwargs.pop('cls', None) # type: ClsType["_models.Experiment"] lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval ) cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] if cont_token is None: raw_result = await self._create_initial( resource_group_name=resource_group_name, workspace_name=workspace_name, experiment_name=experiment_name, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map', None) kwargs.pop('content_type', None) def get_long_running_output(pipeline_response): deserialized = self._deserialize('Experiment', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', pattern=r'^[-\w\._]+$'), 'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'experimentName': self._serialize.url("experiment_name", experiment_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } if polling is True: polling_method = AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) elif polling is False: polling_method = AsyncNoPolling() else: polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output ) else: return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_create.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces/{workspaceName}/experiments/{experimentName}'} # type: ignore async def _delete_initial( self, resource_group_name: str, workspace_name: str, experiment_name: str, **kwargs: Any ) -> None: cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2018-05-01" accept = "application/json" # Construct URL url = self._delete_initial.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', pattern=r'^[-\w\._]+$'), 'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'experimentName': self._serialize.url("experiment_name", experiment_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), '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 = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') request = self._client.delete(url, query_parameters, header_parameters) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) _delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces/{workspaceName}/experiments/{experimentName}'} # type: ignore async def begin_delete( self, resource_group_name: str, workspace_name: str, experiment_name: str, **kwargs: Any ) -> AsyncLROPoller[None]: """Deletes an Experiment. :param resource_group_name: Name of the resource group to which the resource belongs. :type resource_group_name: str :param workspace_name: The name of the workspace. Workspace names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type workspace_name: str :param experiment_name: The name of the experiment. Experiment names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type experiment_name: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[None] :raises ~azure.core.exceptions.HttpResponseError: """ polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] cls = kwargs.pop('cls', None) # type: ClsType[None] lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval ) cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] if cont_token is None: raw_result = await self._delete_initial( resource_group_name=resource_group_name, workspace_name=workspace_name, experiment_name=experiment_name, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map', None) kwargs.pop('content_type', None) def get_long_running_output(pipeline_response): if cls: return cls(pipeline_response, None, {}) path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', pattern=r'^[-\w\._]+$'), 'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'experimentName': self._serialize.url("experiment_name", experiment_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } if polling is True: polling_method = AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) elif polling is False: polling_method = AsyncNoPolling() else: polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output ) else: return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces/{workspaceName}/experiments/{experimentName}'} # type: ignore async def get( self, resource_group_name: str, workspace_name: str, experiment_name: str, **kwargs: Any ) -> "_models.Experiment": """Gets information about an Experiment. :param resource_group_name: Name of the resource group to which the resource belongs. :type resource_group_name: str :param workspace_name: The name of the workspace. Workspace names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type workspace_name: str :param experiment_name: The name of the experiment. Experiment names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type experiment_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Experiment, or the result of cls(response) :rtype: ~batch_ai.models.Experiment :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.Experiment"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2018-05-01" accept = "application/json" # Construct URL url = self.get.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', pattern=r'^[-\w\._]+$'), 'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'experimentName': self._serialize.url("experiment_name", experiment_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), '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 = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') request = self._client.get(url, query_parameters, header_parameters) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize('Experiment', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces/{workspaceName}/experiments/{experimentName}'} # type: ignore
0.915171
0.13707
from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union import warnings from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling from ... import models as _models T = TypeVar('T') ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] class JobsOperations: """JobsOperations async operations. You should not instantiate this class directly. Instead, you should create a Client instance that instantiates it for you and attaches it as an attribute. :ivar models: Alias to model classes used in this operation group. :type models: ~batch_ai.models :param client: Client for service requests. :param config: Configuration of service client. :param serializer: An object model serializer. :param deserializer: An object model deserializer. """ models = _models def __init__(self, client, config, serializer, deserializer) -> None: self._client = client self._serialize = serializer self._deserialize = deserializer self._config = config def list_by_experiment( self, resource_group_name: str, workspace_name: str, experiment_name: str, jobs_list_by_experiment_options: Optional["_models.JobsListByExperimentOptions"] = None, **kwargs: Any ) -> AsyncIterable["_models.JobListResult"]: """Gets a list of Jobs within the specified Experiment. :param resource_group_name: Name of the resource group to which the resource belongs. :type resource_group_name: str :param workspace_name: The name of the workspace. Workspace names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type workspace_name: str :param experiment_name: The name of the experiment. Experiment names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type experiment_name: str :param jobs_list_by_experiment_options: Parameter group. :type jobs_list_by_experiment_options: ~batch_ai.models.JobsListByExperimentOptions :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either JobListResult or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~batch_ai.models.JobListResult] :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.JobListResult"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) _max_results = None if jobs_list_by_experiment_options is not None: _max_results = jobs_list_by_experiment_options.max_results api_version = "2018-05-01" accept = "application/json" def prepare_request(next_link=None): # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') if not next_link: # Construct URL url = self.list_by_experiment.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', pattern=r'^[-\w\._]+$'), 'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'experimentName': self._serialize.url("experiment_name", experiment_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), '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 = {} # type: Dict[str, Any] if _max_results is not None: query_parameters['maxresults'] = self._serialize.query("max_results", _max_results, 'int', maximum=1000, minimum=1) query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') request = self._client.get(url, query_parameters, header_parameters) else: url = next_link query_parameters = {} # type: Dict[str, Any] request = self._client.get(url, query_parameters, header_parameters) return request async def extract_data(pipeline_response): deserialized = self._deserialize('JobListResult', pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged( get_next, extract_data ) list_by_experiment.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces/{workspaceName}/experiments/{experimentName}/jobs'} # type: ignore async def _create_initial( self, resource_group_name: str, workspace_name: str, experiment_name: str, job_name: str, parameters: "_models.JobCreateParameters", **kwargs: Any ) -> Optional["_models.Job"]: cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.Job"]] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2018-05-01" content_type = kwargs.pop("content_type", "application/json") accept = "application/json" # Construct URL url = self._create_initial.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', pattern=r'^[-\w\._]+$'), 'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'experimentName': self._serialize.url("experiment_name", experiment_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'jobName': self._serialize.url("job_name", job_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), '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 = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') body_content_kwargs = {} # type: Dict[str, Any] body_content = self._serialize.body(parameters, 'JobCreateParameters') body_content_kwargs['content'] = body_content request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = None if response.status_code == 200: deserialized = self._deserialize('Job', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized _create_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces/{workspaceName}/experiments/{experimentName}/jobs/{jobName}'} # type: ignore async def begin_create( self, resource_group_name: str, workspace_name: str, experiment_name: str, job_name: str, parameters: "_models.JobCreateParameters", **kwargs: Any ) -> AsyncLROPoller["_models.Job"]: """Creates a Job in the given Experiment. :param resource_group_name: Name of the resource group to which the resource belongs. :type resource_group_name: str :param workspace_name: The name of the workspace. Workspace names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type workspace_name: str :param experiment_name: The name of the experiment. Experiment names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type experiment_name: str :param job_name: The name of the job within the specified resource group. Job names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type job_name: str :param parameters: The parameters to provide for job creation. :type parameters: ~batch_ai.models.JobCreateParameters :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of AsyncLROPoller that returns either Job or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~batch_ai.models.Job] :raises ~azure.core.exceptions.HttpResponseError: """ polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] cls = kwargs.pop('cls', None) # type: ClsType["_models.Job"] lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval ) cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] if cont_token is None: raw_result = await self._create_initial( resource_group_name=resource_group_name, workspace_name=workspace_name, experiment_name=experiment_name, job_name=job_name, parameters=parameters, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map', None) kwargs.pop('content_type', None) def get_long_running_output(pipeline_response): deserialized = self._deserialize('Job', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', pattern=r'^[-\w\._]+$'), 'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'experimentName': self._serialize.url("experiment_name", experiment_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'jobName': self._serialize.url("job_name", job_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } if polling is True: polling_method = AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) elif polling is False: polling_method = AsyncNoPolling() else: polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output ) else: return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_create.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces/{workspaceName}/experiments/{experimentName}/jobs/{jobName}'} # type: ignore async def _delete_initial( self, resource_group_name: str, workspace_name: str, experiment_name: str, job_name: str, **kwargs: Any ) -> None: cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2018-05-01" accept = "application/json" # Construct URL url = self._delete_initial.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', pattern=r'^[-\w\._]+$'), 'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'experimentName': self._serialize.url("experiment_name", experiment_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'jobName': self._serialize.url("job_name", job_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), '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 = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') request = self._client.delete(url, query_parameters, header_parameters) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) _delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces/{workspaceName}/experiments/{experimentName}/jobs/{jobName}'} # type: ignore async def begin_delete( self, resource_group_name: str, workspace_name: str, experiment_name: str, job_name: str, **kwargs: Any ) -> AsyncLROPoller[None]: """Deletes a Job. :param resource_group_name: Name of the resource group to which the resource belongs. :type resource_group_name: str :param workspace_name: The name of the workspace. Workspace names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type workspace_name: str :param experiment_name: The name of the experiment. Experiment names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type experiment_name: str :param job_name: The name of the job within the specified resource group. Job names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type job_name: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[None] :raises ~azure.core.exceptions.HttpResponseError: """ polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] cls = kwargs.pop('cls', None) # type: ClsType[None] lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval ) cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] if cont_token is None: raw_result = await self._delete_initial( resource_group_name=resource_group_name, workspace_name=workspace_name, experiment_name=experiment_name, job_name=job_name, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map', None) kwargs.pop('content_type', None) def get_long_running_output(pipeline_response): if cls: return cls(pipeline_response, None, {}) path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', pattern=r'^[-\w\._]+$'), 'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'experimentName': self._serialize.url("experiment_name", experiment_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'jobName': self._serialize.url("job_name", job_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } if polling is True: polling_method = AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) elif polling is False: polling_method = AsyncNoPolling() else: polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output ) else: return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces/{workspaceName}/experiments/{experimentName}/jobs/{jobName}'} # type: ignore async def get( self, resource_group_name: str, workspace_name: str, experiment_name: str, job_name: str, **kwargs: Any ) -> "_models.Job": """Gets information about a Job. :param resource_group_name: Name of the resource group to which the resource belongs. :type resource_group_name: str :param workspace_name: The name of the workspace. Workspace names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type workspace_name: str :param experiment_name: The name of the experiment. Experiment names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type experiment_name: str :param job_name: The name of the job within the specified resource group. Job names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type job_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Job, or the result of cls(response) :rtype: ~batch_ai.models.Job :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.Job"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2018-05-01" accept = "application/json" # Construct URL url = self.get.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', pattern=r'^[-\w\._]+$'), 'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'experimentName': self._serialize.url("experiment_name", experiment_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'jobName': self._serialize.url("job_name", job_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), '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 = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') request = self._client.get(url, query_parameters, header_parameters) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize('Job', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces/{workspaceName}/experiments/{experimentName}/jobs/{jobName}'} # type: ignore def list_output_files( self, resource_group_name: str, workspace_name: str, experiment_name: str, job_name: str, jobs_list_output_files_options: "_models.JobsListOutputFilesOptions", **kwargs: Any ) -> AsyncIterable["_models.FileListResult"]: """List all directories and files inside the given directory of the Job's output directory (if the output directory is on Azure File Share or Azure Storage Container). :param resource_group_name: Name of the resource group to which the resource belongs. :type resource_group_name: str :param workspace_name: The name of the workspace. Workspace names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type workspace_name: str :param experiment_name: The name of the experiment. Experiment names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type experiment_name: str :param job_name: The name of the job within the specified resource group. Job names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type job_name: str :param jobs_list_output_files_options: Parameter group. :type jobs_list_output_files_options: ~batch_ai.models.JobsListOutputFilesOptions :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either FileListResult or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~batch_ai.models.FileListResult] :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.FileListResult"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) _outputdirectoryid = None _directory = None _linkexpiryinminutes = None _max_results = None if jobs_list_output_files_options is not None: _outputdirectoryid = jobs_list_output_files_options.outputdirectoryid _directory = jobs_list_output_files_options.directory _linkexpiryinminutes = jobs_list_output_files_options.linkexpiryinminutes _max_results = jobs_list_output_files_options.max_results api_version = "2018-05-01" accept = "application/json" def prepare_request(next_link=None): # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') if not next_link: # Construct URL url = self.list_output_files.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', pattern=r'^[-\w\._]+$'), 'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'experimentName': self._serialize.url("experiment_name", experiment_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'jobName': self._serialize.url("job_name", job_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), '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 = {} # type: Dict[str, Any] query_parameters['outputdirectoryid'] = self._serialize.query("outputdirectoryid", _outputdirectoryid, 'str') if _directory is not None: query_parameters['directory'] = self._serialize.query("directory", _directory, 'str') if _linkexpiryinminutes is not None: query_parameters['linkexpiryinminutes'] = self._serialize.query("linkexpiryinminutes", _linkexpiryinminutes, 'int', maximum=600, minimum=5) if _max_results is not None: query_parameters['maxresults'] = self._serialize.query("max_results", _max_results, 'int', maximum=1000, minimum=1) query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') request = self._client.post(url, query_parameters, header_parameters) else: url = next_link query_parameters = {} # type: Dict[str, Any] request = self._client.get(url, query_parameters, header_parameters) return request async def extract_data(pipeline_response): deserialized = self._deserialize('FileListResult', pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged( get_next, extract_data ) list_output_files.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces/{workspaceName}/experiments/{experimentName}/jobs/{jobName}/listOutputFiles'} # type: ignore def list_remote_login_information( self, resource_group_name: str, workspace_name: str, experiment_name: str, job_name: str, **kwargs: Any ) -> AsyncIterable["_models.RemoteLoginInformationListResult"]: """Gets a list of currently existing nodes which were used for the Job execution. The returned information contains the node ID, its public IP and SSH port. :param resource_group_name: Name of the resource group to which the resource belongs. :type resource_group_name: str :param workspace_name: The name of the workspace. Workspace names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type workspace_name: str :param experiment_name: The name of the experiment. Experiment names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type experiment_name: str :param job_name: The name of the job within the specified resource group. Job names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type job_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either RemoteLoginInformationListResult or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~batch_ai.models.RemoteLoginInformationListResult] :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.RemoteLoginInformationListResult"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2018-05-01" accept = "application/json" def prepare_request(next_link=None): # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') if not next_link: # Construct URL url = self.list_remote_login_information.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', pattern=r'^[-\w\._]+$'), 'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'experimentName': self._serialize.url("experiment_name", experiment_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'jobName': self._serialize.url("job_name", job_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), '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 = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') request = self._client.post(url, query_parameters, header_parameters) else: url = next_link query_parameters = {} # type: Dict[str, Any] request = self._client.get(url, query_parameters, header_parameters) return request async def extract_data(pipeline_response): deserialized = self._deserialize('RemoteLoginInformationListResult', pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged( get_next, extract_data ) list_remote_login_information.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces/{workspaceName}/experiments/{experimentName}/jobs/{jobName}/listRemoteLoginInformation'} # type: ignore async def _terminate_initial( self, resource_group_name: str, workspace_name: str, experiment_name: str, job_name: str, **kwargs: Any ) -> None: cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2018-05-01" accept = "application/json" # Construct URL url = self._terminate_initial.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', pattern=r'^[-\w\._]+$'), 'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'experimentName': self._serialize.url("experiment_name", experiment_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'jobName': self._serialize.url("job_name", job_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), '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 = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') request = self._client.post(url, query_parameters, header_parameters) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) _terminate_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces/{workspaceName}/experiments/{experimentName}/jobs/{jobName}/terminate'} # type: ignore async def begin_terminate( self, resource_group_name: str, workspace_name: str, experiment_name: str, job_name: str, **kwargs: Any ) -> AsyncLROPoller[None]: """Terminates a job. :param resource_group_name: Name of the resource group to which the resource belongs. :type resource_group_name: str :param workspace_name: The name of the workspace. Workspace names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type workspace_name: str :param experiment_name: The name of the experiment. Experiment names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type experiment_name: str :param job_name: The name of the job within the specified resource group. Job names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type job_name: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[None] :raises ~azure.core.exceptions.HttpResponseError: """ polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] cls = kwargs.pop('cls', None) # type: ClsType[None] lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval ) cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] if cont_token is None: raw_result = await self._terminate_initial( resource_group_name=resource_group_name, workspace_name=workspace_name, experiment_name=experiment_name, job_name=job_name, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map', None) kwargs.pop('content_type', None) def get_long_running_output(pipeline_response): if cls: return cls(pipeline_response, None, {}) path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', pattern=r'^[-\w\._]+$'), 'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'experimentName': self._serialize.url("experiment_name", experiment_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'jobName': self._serialize.url("job_name", job_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } if polling is True: polling_method = AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) elif polling is False: polling_method = AsyncNoPolling() else: polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output ) else: return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_terminate.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces/{workspaceName}/experiments/{experimentName}/jobs/{jobName}/terminate'} # type: ignore
azure-mgmt-batchai
/azure-mgmt-batchai-7.0.0b1.zip/azure-mgmt-batchai-7.0.0b1/azure/mgmt/batchai/aio/operations/_jobs_operations.py
_jobs_operations.py
from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union import warnings from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling from ... import models as _models T = TypeVar('T') ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] class JobsOperations: """JobsOperations async operations. You should not instantiate this class directly. Instead, you should create a Client instance that instantiates it for you and attaches it as an attribute. :ivar models: Alias to model classes used in this operation group. :type models: ~batch_ai.models :param client: Client for service requests. :param config: Configuration of service client. :param serializer: An object model serializer. :param deserializer: An object model deserializer. """ models = _models def __init__(self, client, config, serializer, deserializer) -> None: self._client = client self._serialize = serializer self._deserialize = deserializer self._config = config def list_by_experiment( self, resource_group_name: str, workspace_name: str, experiment_name: str, jobs_list_by_experiment_options: Optional["_models.JobsListByExperimentOptions"] = None, **kwargs: Any ) -> AsyncIterable["_models.JobListResult"]: """Gets a list of Jobs within the specified Experiment. :param resource_group_name: Name of the resource group to which the resource belongs. :type resource_group_name: str :param workspace_name: The name of the workspace. Workspace names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type workspace_name: str :param experiment_name: The name of the experiment. Experiment names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type experiment_name: str :param jobs_list_by_experiment_options: Parameter group. :type jobs_list_by_experiment_options: ~batch_ai.models.JobsListByExperimentOptions :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either JobListResult or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~batch_ai.models.JobListResult] :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.JobListResult"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) _max_results = None if jobs_list_by_experiment_options is not None: _max_results = jobs_list_by_experiment_options.max_results api_version = "2018-05-01" accept = "application/json" def prepare_request(next_link=None): # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') if not next_link: # Construct URL url = self.list_by_experiment.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', pattern=r'^[-\w\._]+$'), 'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'experimentName': self._serialize.url("experiment_name", experiment_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), '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 = {} # type: Dict[str, Any] if _max_results is not None: query_parameters['maxresults'] = self._serialize.query("max_results", _max_results, 'int', maximum=1000, minimum=1) query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') request = self._client.get(url, query_parameters, header_parameters) else: url = next_link query_parameters = {} # type: Dict[str, Any] request = self._client.get(url, query_parameters, header_parameters) return request async def extract_data(pipeline_response): deserialized = self._deserialize('JobListResult', pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged( get_next, extract_data ) list_by_experiment.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces/{workspaceName}/experiments/{experimentName}/jobs'} # type: ignore async def _create_initial( self, resource_group_name: str, workspace_name: str, experiment_name: str, job_name: str, parameters: "_models.JobCreateParameters", **kwargs: Any ) -> Optional["_models.Job"]: cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.Job"]] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2018-05-01" content_type = kwargs.pop("content_type", "application/json") accept = "application/json" # Construct URL url = self._create_initial.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', pattern=r'^[-\w\._]+$'), 'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'experimentName': self._serialize.url("experiment_name", experiment_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'jobName': self._serialize.url("job_name", job_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), '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 = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') body_content_kwargs = {} # type: Dict[str, Any] body_content = self._serialize.body(parameters, 'JobCreateParameters') body_content_kwargs['content'] = body_content request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = None if response.status_code == 200: deserialized = self._deserialize('Job', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized _create_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces/{workspaceName}/experiments/{experimentName}/jobs/{jobName}'} # type: ignore async def begin_create( self, resource_group_name: str, workspace_name: str, experiment_name: str, job_name: str, parameters: "_models.JobCreateParameters", **kwargs: Any ) -> AsyncLROPoller["_models.Job"]: """Creates a Job in the given Experiment. :param resource_group_name: Name of the resource group to which the resource belongs. :type resource_group_name: str :param workspace_name: The name of the workspace. Workspace names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type workspace_name: str :param experiment_name: The name of the experiment. Experiment names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type experiment_name: str :param job_name: The name of the job within the specified resource group. Job names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type job_name: str :param parameters: The parameters to provide for job creation. :type parameters: ~batch_ai.models.JobCreateParameters :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of AsyncLROPoller that returns either Job or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~batch_ai.models.Job] :raises ~azure.core.exceptions.HttpResponseError: """ polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] cls = kwargs.pop('cls', None) # type: ClsType["_models.Job"] lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval ) cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] if cont_token is None: raw_result = await self._create_initial( resource_group_name=resource_group_name, workspace_name=workspace_name, experiment_name=experiment_name, job_name=job_name, parameters=parameters, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map', None) kwargs.pop('content_type', None) def get_long_running_output(pipeline_response): deserialized = self._deserialize('Job', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', pattern=r'^[-\w\._]+$'), 'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'experimentName': self._serialize.url("experiment_name", experiment_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'jobName': self._serialize.url("job_name", job_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } if polling is True: polling_method = AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) elif polling is False: polling_method = AsyncNoPolling() else: polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output ) else: return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_create.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces/{workspaceName}/experiments/{experimentName}/jobs/{jobName}'} # type: ignore async def _delete_initial( self, resource_group_name: str, workspace_name: str, experiment_name: str, job_name: str, **kwargs: Any ) -> None: cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2018-05-01" accept = "application/json" # Construct URL url = self._delete_initial.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', pattern=r'^[-\w\._]+$'), 'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'experimentName': self._serialize.url("experiment_name", experiment_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'jobName': self._serialize.url("job_name", job_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), '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 = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') request = self._client.delete(url, query_parameters, header_parameters) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) _delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces/{workspaceName}/experiments/{experimentName}/jobs/{jobName}'} # type: ignore async def begin_delete( self, resource_group_name: str, workspace_name: str, experiment_name: str, job_name: str, **kwargs: Any ) -> AsyncLROPoller[None]: """Deletes a Job. :param resource_group_name: Name of the resource group to which the resource belongs. :type resource_group_name: str :param workspace_name: The name of the workspace. Workspace names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type workspace_name: str :param experiment_name: The name of the experiment. Experiment names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type experiment_name: str :param job_name: The name of the job within the specified resource group. Job names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type job_name: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[None] :raises ~azure.core.exceptions.HttpResponseError: """ polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] cls = kwargs.pop('cls', None) # type: ClsType[None] lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval ) cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] if cont_token is None: raw_result = await self._delete_initial( resource_group_name=resource_group_name, workspace_name=workspace_name, experiment_name=experiment_name, job_name=job_name, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map', None) kwargs.pop('content_type', None) def get_long_running_output(pipeline_response): if cls: return cls(pipeline_response, None, {}) path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', pattern=r'^[-\w\._]+$'), 'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'experimentName': self._serialize.url("experiment_name", experiment_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'jobName': self._serialize.url("job_name", job_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } if polling is True: polling_method = AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) elif polling is False: polling_method = AsyncNoPolling() else: polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output ) else: return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces/{workspaceName}/experiments/{experimentName}/jobs/{jobName}'} # type: ignore async def get( self, resource_group_name: str, workspace_name: str, experiment_name: str, job_name: str, **kwargs: Any ) -> "_models.Job": """Gets information about a Job. :param resource_group_name: Name of the resource group to which the resource belongs. :type resource_group_name: str :param workspace_name: The name of the workspace. Workspace names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type workspace_name: str :param experiment_name: The name of the experiment. Experiment names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type experiment_name: str :param job_name: The name of the job within the specified resource group. Job names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type job_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Job, or the result of cls(response) :rtype: ~batch_ai.models.Job :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.Job"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2018-05-01" accept = "application/json" # Construct URL url = self.get.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', pattern=r'^[-\w\._]+$'), 'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'experimentName': self._serialize.url("experiment_name", experiment_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'jobName': self._serialize.url("job_name", job_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), '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 = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') request = self._client.get(url, query_parameters, header_parameters) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize('Job', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces/{workspaceName}/experiments/{experimentName}/jobs/{jobName}'} # type: ignore def list_output_files( self, resource_group_name: str, workspace_name: str, experiment_name: str, job_name: str, jobs_list_output_files_options: "_models.JobsListOutputFilesOptions", **kwargs: Any ) -> AsyncIterable["_models.FileListResult"]: """List all directories and files inside the given directory of the Job's output directory (if the output directory is on Azure File Share or Azure Storage Container). :param resource_group_name: Name of the resource group to which the resource belongs. :type resource_group_name: str :param workspace_name: The name of the workspace. Workspace names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type workspace_name: str :param experiment_name: The name of the experiment. Experiment names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type experiment_name: str :param job_name: The name of the job within the specified resource group. Job names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type job_name: str :param jobs_list_output_files_options: Parameter group. :type jobs_list_output_files_options: ~batch_ai.models.JobsListOutputFilesOptions :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either FileListResult or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~batch_ai.models.FileListResult] :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.FileListResult"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) _outputdirectoryid = None _directory = None _linkexpiryinminutes = None _max_results = None if jobs_list_output_files_options is not None: _outputdirectoryid = jobs_list_output_files_options.outputdirectoryid _directory = jobs_list_output_files_options.directory _linkexpiryinminutes = jobs_list_output_files_options.linkexpiryinminutes _max_results = jobs_list_output_files_options.max_results api_version = "2018-05-01" accept = "application/json" def prepare_request(next_link=None): # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') if not next_link: # Construct URL url = self.list_output_files.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', pattern=r'^[-\w\._]+$'), 'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'experimentName': self._serialize.url("experiment_name", experiment_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'jobName': self._serialize.url("job_name", job_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), '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 = {} # type: Dict[str, Any] query_parameters['outputdirectoryid'] = self._serialize.query("outputdirectoryid", _outputdirectoryid, 'str') if _directory is not None: query_parameters['directory'] = self._serialize.query("directory", _directory, 'str') if _linkexpiryinminutes is not None: query_parameters['linkexpiryinminutes'] = self._serialize.query("linkexpiryinminutes", _linkexpiryinminutes, 'int', maximum=600, minimum=5) if _max_results is not None: query_parameters['maxresults'] = self._serialize.query("max_results", _max_results, 'int', maximum=1000, minimum=1) query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') request = self._client.post(url, query_parameters, header_parameters) else: url = next_link query_parameters = {} # type: Dict[str, Any] request = self._client.get(url, query_parameters, header_parameters) return request async def extract_data(pipeline_response): deserialized = self._deserialize('FileListResult', pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged( get_next, extract_data ) list_output_files.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces/{workspaceName}/experiments/{experimentName}/jobs/{jobName}/listOutputFiles'} # type: ignore def list_remote_login_information( self, resource_group_name: str, workspace_name: str, experiment_name: str, job_name: str, **kwargs: Any ) -> AsyncIterable["_models.RemoteLoginInformationListResult"]: """Gets a list of currently existing nodes which were used for the Job execution. The returned information contains the node ID, its public IP and SSH port. :param resource_group_name: Name of the resource group to which the resource belongs. :type resource_group_name: str :param workspace_name: The name of the workspace. Workspace names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type workspace_name: str :param experiment_name: The name of the experiment. Experiment names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type experiment_name: str :param job_name: The name of the job within the specified resource group. Job names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type job_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either RemoteLoginInformationListResult or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~batch_ai.models.RemoteLoginInformationListResult] :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.RemoteLoginInformationListResult"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2018-05-01" accept = "application/json" def prepare_request(next_link=None): # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') if not next_link: # Construct URL url = self.list_remote_login_information.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', pattern=r'^[-\w\._]+$'), 'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'experimentName': self._serialize.url("experiment_name", experiment_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'jobName': self._serialize.url("job_name", job_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), '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 = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') request = self._client.post(url, query_parameters, header_parameters) else: url = next_link query_parameters = {} # type: Dict[str, Any] request = self._client.get(url, query_parameters, header_parameters) return request async def extract_data(pipeline_response): deserialized = self._deserialize('RemoteLoginInformationListResult', pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged( get_next, extract_data ) list_remote_login_information.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces/{workspaceName}/experiments/{experimentName}/jobs/{jobName}/listRemoteLoginInformation'} # type: ignore async def _terminate_initial( self, resource_group_name: str, workspace_name: str, experiment_name: str, job_name: str, **kwargs: Any ) -> None: cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2018-05-01" accept = "application/json" # Construct URL url = self._terminate_initial.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', pattern=r'^[-\w\._]+$'), 'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'experimentName': self._serialize.url("experiment_name", experiment_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'jobName': self._serialize.url("job_name", job_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), '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 = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') request = self._client.post(url, query_parameters, header_parameters) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) _terminate_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces/{workspaceName}/experiments/{experimentName}/jobs/{jobName}/terminate'} # type: ignore async def begin_terminate( self, resource_group_name: str, workspace_name: str, experiment_name: str, job_name: str, **kwargs: Any ) -> AsyncLROPoller[None]: """Terminates a job. :param resource_group_name: Name of the resource group to which the resource belongs. :type resource_group_name: str :param workspace_name: The name of the workspace. Workspace names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type workspace_name: str :param experiment_name: The name of the experiment. Experiment names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type experiment_name: str :param job_name: The name of the job within the specified resource group. Job names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type job_name: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[None] :raises ~azure.core.exceptions.HttpResponseError: """ polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] cls = kwargs.pop('cls', None) # type: ClsType[None] lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval ) cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] if cont_token is None: raw_result = await self._terminate_initial( resource_group_name=resource_group_name, workspace_name=workspace_name, experiment_name=experiment_name, job_name=job_name, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map', None) kwargs.pop('content_type', None) def get_long_running_output(pipeline_response): if cls: return cls(pipeline_response, None, {}) path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', pattern=r'^[-\w\._]+$'), 'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'experimentName': self._serialize.url("experiment_name", experiment_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'jobName': self._serialize.url("job_name", job_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } if polling is True: polling_method = AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) elif polling is False: polling_method = AsyncNoPolling() else: polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output ) else: return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_terminate.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces/{workspaceName}/experiments/{experimentName}/jobs/{jobName}/terminate'} # type: ignore
0.910252
0.120465
from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union import warnings from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling from ... import models as _models T = TypeVar('T') ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] class WorkspacesOperations: """WorkspacesOperations async operations. You should not instantiate this class directly. Instead, you should create a Client instance that instantiates it for you and attaches it as an attribute. :ivar models: Alias to model classes used in this operation group. :type models: ~batch_ai.models :param client: Client for service requests. :param config: Configuration of service client. :param serializer: An object model serializer. :param deserializer: An object model deserializer. """ models = _models def __init__(self, client, config, serializer, deserializer) -> None: self._client = client self._serialize = serializer self._deserialize = deserializer self._config = config def list( self, workspaces_list_options: Optional["_models.WorkspacesListOptions"] = None, **kwargs: Any ) -> AsyncIterable["_models.WorkspaceListResult"]: """Gets a list of Workspaces associated with the given subscription. :param workspaces_list_options: Parameter group. :type workspaces_list_options: ~batch_ai.models.WorkspacesListOptions :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either WorkspaceListResult or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~batch_ai.models.WorkspaceListResult] :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.WorkspaceListResult"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) _max_results = None if workspaces_list_options is not None: _max_results = workspaces_list_options.max_results api_version = "2018-05-01" accept = "application/json" def prepare_request(next_link=None): # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') if not next_link: # Construct URL url = self.list.metadata['url'] # type: ignore 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 = {} # type: Dict[str, Any] if _max_results is not None: query_parameters['maxresults'] = self._serialize.query("max_results", _max_results, 'int', maximum=1000, minimum=1) query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') request = self._client.get(url, query_parameters, header_parameters) else: url = next_link query_parameters = {} # type: Dict[str, Any] request = self._client.get(url, query_parameters, header_parameters) return request async def extract_data(pipeline_response): deserialized = self._deserialize('WorkspaceListResult', pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged( get_next, extract_data ) list.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.BatchAI/workspaces'} # type: ignore def list_by_resource_group( self, resource_group_name: str, workspaces_list_by_resource_group_options: Optional["_models.WorkspacesListByResourceGroupOptions"] = None, **kwargs: Any ) -> AsyncIterable["_models.WorkspaceListResult"]: """Gets a list of Workspaces within the specified resource group. :param resource_group_name: Name of the resource group to which the resource belongs. :type resource_group_name: str :param workspaces_list_by_resource_group_options: Parameter group. :type workspaces_list_by_resource_group_options: ~batch_ai.models.WorkspacesListByResourceGroupOptions :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either WorkspaceListResult or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~batch_ai.models.WorkspaceListResult] :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.WorkspaceListResult"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) _max_results = None if workspaces_list_by_resource_group_options is not None: _max_results = workspaces_list_by_resource_group_options.max_results api_version = "2018-05-01" accept = "application/json" def prepare_request(next_link=None): # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') if not next_link: # Construct URL url = self.list_by_resource_group.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', pattern=r'^[-\w\._]+$'), '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 = {} # type: Dict[str, Any] if _max_results is not None: query_parameters['maxresults'] = self._serialize.query("max_results", _max_results, 'int', maximum=1000, minimum=1) query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') request = self._client.get(url, query_parameters, header_parameters) else: url = next_link query_parameters = {} # type: Dict[str, Any] request = self._client.get(url, query_parameters, header_parameters) return request async def extract_data(pipeline_response): deserialized = self._deserialize('WorkspaceListResult', pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged( get_next, extract_data ) list_by_resource_group.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces'} # type: ignore async def _create_initial( self, resource_group_name: str, workspace_name: str, parameters: "_models.WorkspaceCreateParameters", **kwargs: Any ) -> Optional["_models.Workspace"]: cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.Workspace"]] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2018-05-01" content_type = kwargs.pop("content_type", "application/json") accept = "application/json" # Construct URL url = self._create_initial.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', pattern=r'^[-\w\._]+$'), 'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), '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 = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') body_content_kwargs = {} # type: Dict[str, Any] body_content = self._serialize.body(parameters, 'WorkspaceCreateParameters') body_content_kwargs['content'] = body_content request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = None if response.status_code == 200: deserialized = self._deserialize('Workspace', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized _create_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces/{workspaceName}'} # type: ignore async def begin_create( self, resource_group_name: str, workspace_name: str, parameters: "_models.WorkspaceCreateParameters", **kwargs: Any ) -> AsyncLROPoller["_models.Workspace"]: """Creates a Workspace. :param resource_group_name: Name of the resource group to which the resource belongs. :type resource_group_name: str :param workspace_name: The name of the workspace. Workspace names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type workspace_name: str :param parameters: Workspace creation parameters. :type parameters: ~batch_ai.models.WorkspaceCreateParameters :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of AsyncLROPoller that returns either Workspace or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~batch_ai.models.Workspace] :raises ~azure.core.exceptions.HttpResponseError: """ polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] cls = kwargs.pop('cls', None) # type: ClsType["_models.Workspace"] lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval ) cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] if cont_token is None: raw_result = await self._create_initial( resource_group_name=resource_group_name, workspace_name=workspace_name, parameters=parameters, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map', None) kwargs.pop('content_type', None) def get_long_running_output(pipeline_response): deserialized = self._deserialize('Workspace', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', pattern=r'^[-\w\._]+$'), 'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } if polling is True: polling_method = AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) elif polling is False: polling_method = AsyncNoPolling() else: polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output ) else: return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_create.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces/{workspaceName}'} # type: ignore async def update( self, resource_group_name: str, workspace_name: str, parameters: "_models.WorkspaceUpdateParameters", **kwargs: Any ) -> "_models.Workspace": """Updates properties of a Workspace. :param resource_group_name: Name of the resource group to which the resource belongs. :type resource_group_name: str :param workspace_name: The name of the workspace. Workspace names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type workspace_name: str :param parameters: Additional parameters for workspace update. :type parameters: ~batch_ai.models.WorkspaceUpdateParameters :keyword callable cls: A custom type or function that will be passed the direct response :return: Workspace, or the result of cls(response) :rtype: ~batch_ai.models.Workspace :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.Workspace"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2018-05-01" content_type = kwargs.pop("content_type", "application/json") accept = "application/json" # Construct URL url = self.update.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', pattern=r'^[-\w\._]+$'), 'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), '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 = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') body_content_kwargs = {} # type: Dict[str, Any] body_content = self._serialize.body(parameters, 'WorkspaceUpdateParameters') body_content_kwargs['content'] = body_content request = self._client.patch(url, query_parameters, header_parameters, **body_content_kwargs) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize('Workspace', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces/{workspaceName}'} # type: ignore async def _delete_initial( self, resource_group_name: str, workspace_name: str, **kwargs: Any ) -> None: cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2018-05-01" accept = "application/json" # Construct URL url = self._delete_initial.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', pattern=r'^[-\w\._]+$'), 'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), '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 = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') request = self._client.delete(url, query_parameters, header_parameters) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) _delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces/{workspaceName}'} # type: ignore async def begin_delete( self, resource_group_name: str, workspace_name: str, **kwargs: Any ) -> AsyncLROPoller[None]: """Deletes a Workspace. :param resource_group_name: Name of the resource group to which the resource belongs. :type resource_group_name: str :param workspace_name: The name of the workspace. Workspace names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type workspace_name: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[None] :raises ~azure.core.exceptions.HttpResponseError: """ polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] cls = kwargs.pop('cls', None) # type: ClsType[None] lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval ) cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] if cont_token is None: raw_result = await self._delete_initial( resource_group_name=resource_group_name, workspace_name=workspace_name, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map', None) kwargs.pop('content_type', None) def get_long_running_output(pipeline_response): if cls: return cls(pipeline_response, None, {}) path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', pattern=r'^[-\w\._]+$'), 'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } if polling is True: polling_method = AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) elif polling is False: polling_method = AsyncNoPolling() else: polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output ) else: return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces/{workspaceName}'} # type: ignore async def get( self, resource_group_name: str, workspace_name: str, **kwargs: Any ) -> "_models.Workspace": """Gets information about a Workspace. :param resource_group_name: Name of the resource group to which the resource belongs. :type resource_group_name: str :param workspace_name: The name of the workspace. Workspace names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type workspace_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Workspace, or the result of cls(response) :rtype: ~batch_ai.models.Workspace :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.Workspace"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2018-05-01" accept = "application/json" # Construct URL url = self.get.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', pattern=r'^[-\w\._]+$'), 'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), '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 = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') request = self._client.get(url, query_parameters, header_parameters) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize('Workspace', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces/{workspaceName}'} # type: ignore
azure-mgmt-batchai
/azure-mgmt-batchai-7.0.0b1.zip/azure-mgmt-batchai-7.0.0b1/azure/mgmt/batchai/aio/operations/_workspaces_operations.py
_workspaces_operations.py
from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union import warnings from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling from ... import models as _models T = TypeVar('T') ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] class WorkspacesOperations: """WorkspacesOperations async operations. You should not instantiate this class directly. Instead, you should create a Client instance that instantiates it for you and attaches it as an attribute. :ivar models: Alias to model classes used in this operation group. :type models: ~batch_ai.models :param client: Client for service requests. :param config: Configuration of service client. :param serializer: An object model serializer. :param deserializer: An object model deserializer. """ models = _models def __init__(self, client, config, serializer, deserializer) -> None: self._client = client self._serialize = serializer self._deserialize = deserializer self._config = config def list( self, workspaces_list_options: Optional["_models.WorkspacesListOptions"] = None, **kwargs: Any ) -> AsyncIterable["_models.WorkspaceListResult"]: """Gets a list of Workspaces associated with the given subscription. :param workspaces_list_options: Parameter group. :type workspaces_list_options: ~batch_ai.models.WorkspacesListOptions :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either WorkspaceListResult or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~batch_ai.models.WorkspaceListResult] :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.WorkspaceListResult"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) _max_results = None if workspaces_list_options is not None: _max_results = workspaces_list_options.max_results api_version = "2018-05-01" accept = "application/json" def prepare_request(next_link=None): # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') if not next_link: # Construct URL url = self.list.metadata['url'] # type: ignore 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 = {} # type: Dict[str, Any] if _max_results is not None: query_parameters['maxresults'] = self._serialize.query("max_results", _max_results, 'int', maximum=1000, minimum=1) query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') request = self._client.get(url, query_parameters, header_parameters) else: url = next_link query_parameters = {} # type: Dict[str, Any] request = self._client.get(url, query_parameters, header_parameters) return request async def extract_data(pipeline_response): deserialized = self._deserialize('WorkspaceListResult', pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged( get_next, extract_data ) list.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.BatchAI/workspaces'} # type: ignore def list_by_resource_group( self, resource_group_name: str, workspaces_list_by_resource_group_options: Optional["_models.WorkspacesListByResourceGroupOptions"] = None, **kwargs: Any ) -> AsyncIterable["_models.WorkspaceListResult"]: """Gets a list of Workspaces within the specified resource group. :param resource_group_name: Name of the resource group to which the resource belongs. :type resource_group_name: str :param workspaces_list_by_resource_group_options: Parameter group. :type workspaces_list_by_resource_group_options: ~batch_ai.models.WorkspacesListByResourceGroupOptions :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either WorkspaceListResult or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~batch_ai.models.WorkspaceListResult] :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.WorkspaceListResult"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) _max_results = None if workspaces_list_by_resource_group_options is not None: _max_results = workspaces_list_by_resource_group_options.max_results api_version = "2018-05-01" accept = "application/json" def prepare_request(next_link=None): # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') if not next_link: # Construct URL url = self.list_by_resource_group.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', pattern=r'^[-\w\._]+$'), '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 = {} # type: Dict[str, Any] if _max_results is not None: query_parameters['maxresults'] = self._serialize.query("max_results", _max_results, 'int', maximum=1000, minimum=1) query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') request = self._client.get(url, query_parameters, header_parameters) else: url = next_link query_parameters = {} # type: Dict[str, Any] request = self._client.get(url, query_parameters, header_parameters) return request async def extract_data(pipeline_response): deserialized = self._deserialize('WorkspaceListResult', pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged( get_next, extract_data ) list_by_resource_group.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces'} # type: ignore async def _create_initial( self, resource_group_name: str, workspace_name: str, parameters: "_models.WorkspaceCreateParameters", **kwargs: Any ) -> Optional["_models.Workspace"]: cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.Workspace"]] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2018-05-01" content_type = kwargs.pop("content_type", "application/json") accept = "application/json" # Construct URL url = self._create_initial.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', pattern=r'^[-\w\._]+$'), 'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), '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 = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') body_content_kwargs = {} # type: Dict[str, Any] body_content = self._serialize.body(parameters, 'WorkspaceCreateParameters') body_content_kwargs['content'] = body_content request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = None if response.status_code == 200: deserialized = self._deserialize('Workspace', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized _create_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces/{workspaceName}'} # type: ignore async def begin_create( self, resource_group_name: str, workspace_name: str, parameters: "_models.WorkspaceCreateParameters", **kwargs: Any ) -> AsyncLROPoller["_models.Workspace"]: """Creates a Workspace. :param resource_group_name: Name of the resource group to which the resource belongs. :type resource_group_name: str :param workspace_name: The name of the workspace. Workspace names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type workspace_name: str :param parameters: Workspace creation parameters. :type parameters: ~batch_ai.models.WorkspaceCreateParameters :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of AsyncLROPoller that returns either Workspace or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~batch_ai.models.Workspace] :raises ~azure.core.exceptions.HttpResponseError: """ polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] cls = kwargs.pop('cls', None) # type: ClsType["_models.Workspace"] lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval ) cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] if cont_token is None: raw_result = await self._create_initial( resource_group_name=resource_group_name, workspace_name=workspace_name, parameters=parameters, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map', None) kwargs.pop('content_type', None) def get_long_running_output(pipeline_response): deserialized = self._deserialize('Workspace', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', pattern=r'^[-\w\._]+$'), 'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } if polling is True: polling_method = AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) elif polling is False: polling_method = AsyncNoPolling() else: polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output ) else: return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_create.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces/{workspaceName}'} # type: ignore async def update( self, resource_group_name: str, workspace_name: str, parameters: "_models.WorkspaceUpdateParameters", **kwargs: Any ) -> "_models.Workspace": """Updates properties of a Workspace. :param resource_group_name: Name of the resource group to which the resource belongs. :type resource_group_name: str :param workspace_name: The name of the workspace. Workspace names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type workspace_name: str :param parameters: Additional parameters for workspace update. :type parameters: ~batch_ai.models.WorkspaceUpdateParameters :keyword callable cls: A custom type or function that will be passed the direct response :return: Workspace, or the result of cls(response) :rtype: ~batch_ai.models.Workspace :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.Workspace"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2018-05-01" content_type = kwargs.pop("content_type", "application/json") accept = "application/json" # Construct URL url = self.update.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', pattern=r'^[-\w\._]+$'), 'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), '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 = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') body_content_kwargs = {} # type: Dict[str, Any] body_content = self._serialize.body(parameters, 'WorkspaceUpdateParameters') body_content_kwargs['content'] = body_content request = self._client.patch(url, query_parameters, header_parameters, **body_content_kwargs) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize('Workspace', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces/{workspaceName}'} # type: ignore async def _delete_initial( self, resource_group_name: str, workspace_name: str, **kwargs: Any ) -> None: cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2018-05-01" accept = "application/json" # Construct URL url = self._delete_initial.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', pattern=r'^[-\w\._]+$'), 'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), '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 = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') request = self._client.delete(url, query_parameters, header_parameters) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) _delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces/{workspaceName}'} # type: ignore async def begin_delete( self, resource_group_name: str, workspace_name: str, **kwargs: Any ) -> AsyncLROPoller[None]: """Deletes a Workspace. :param resource_group_name: Name of the resource group to which the resource belongs. :type resource_group_name: str :param workspace_name: The name of the workspace. Workspace names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type workspace_name: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[None] :raises ~azure.core.exceptions.HttpResponseError: """ polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] cls = kwargs.pop('cls', None) # type: ClsType[None] lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval ) cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] if cont_token is None: raw_result = await self._delete_initial( resource_group_name=resource_group_name, workspace_name=workspace_name, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map', None) kwargs.pop('content_type', None) def get_long_running_output(pipeline_response): if cls: return cls(pipeline_response, None, {}) path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', pattern=r'^[-\w\._]+$'), 'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } if polling is True: polling_method = AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) elif polling is False: polling_method = AsyncNoPolling() else: polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output ) else: return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces/{workspaceName}'} # type: ignore async def get( self, resource_group_name: str, workspace_name: str, **kwargs: Any ) -> "_models.Workspace": """Gets information about a Workspace. :param resource_group_name: Name of the resource group to which the resource belongs. :type resource_group_name: str :param workspace_name: The name of the workspace. Workspace names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type workspace_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Workspace, or the result of cls(response) :rtype: ~batch_ai.models.Workspace :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.Workspace"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2018-05-01" accept = "application/json" # Construct URL url = self.get.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', pattern=r'^[-\w\._]+$'), 'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), '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 = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') request = self._client.get(url, query_parameters, header_parameters) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize('Workspace', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces/{workspaceName}'} # type: ignore
0.896331
0.102529
from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union import warnings from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling from ... import models as _models T = TypeVar('T') ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] class ClustersOperations: """ClustersOperations async operations. You should not instantiate this class directly. Instead, you should create a Client instance that instantiates it for you and attaches it as an attribute. :ivar models: Alias to model classes used in this operation group. :type models: ~batch_ai.models :param client: Client for service requests. :param config: Configuration of service client. :param serializer: An object model serializer. :param deserializer: An object model deserializer. """ models = _models def __init__(self, client, config, serializer, deserializer) -> None: self._client = client self._serialize = serializer self._deserialize = deserializer self._config = config async def _create_initial( self, resource_group_name: str, workspace_name: str, cluster_name: str, parameters: "_models.ClusterCreateParameters", **kwargs: Any ) -> Optional["_models.Cluster"]: cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.Cluster"]] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2018-05-01" content_type = kwargs.pop("content_type", "application/json") accept = "application/json" # Construct URL url = self._create_initial.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', pattern=r'^[-\w\._]+$'), 'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), '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 = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') body_content_kwargs = {} # type: Dict[str, Any] body_content = self._serialize.body(parameters, 'ClusterCreateParameters') body_content_kwargs['content'] = body_content request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = None if response.status_code == 200: deserialized = self._deserialize('Cluster', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized _create_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces/{workspaceName}/clusters/{clusterName}'} # type: ignore async def begin_create( self, resource_group_name: str, workspace_name: str, cluster_name: str, parameters: "_models.ClusterCreateParameters", **kwargs: Any ) -> AsyncLROPoller["_models.Cluster"]: """Creates a Cluster in the given Workspace. :param resource_group_name: Name of the resource group to which the resource belongs. :type resource_group_name: str :param workspace_name: The name of the workspace. Workspace names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type workspace_name: str :param cluster_name: The name of the cluster within the specified resource group. Cluster names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type cluster_name: str :param parameters: The parameters to provide for the Cluster creation. :type parameters: ~batch_ai.models.ClusterCreateParameters :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of AsyncLROPoller that returns either Cluster or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~batch_ai.models.Cluster] :raises ~azure.core.exceptions.HttpResponseError: """ polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] cls = kwargs.pop('cls', None) # type: ClsType["_models.Cluster"] lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval ) cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] if cont_token is None: raw_result = await self._create_initial( resource_group_name=resource_group_name, workspace_name=workspace_name, cluster_name=cluster_name, parameters=parameters, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map', None) kwargs.pop('content_type', None) def get_long_running_output(pipeline_response): deserialized = self._deserialize('Cluster', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', pattern=r'^[-\w\._]+$'), 'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } if polling is True: polling_method = AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) elif polling is False: polling_method = AsyncNoPolling() else: polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output ) else: return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_create.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces/{workspaceName}/clusters/{clusterName}'} # type: ignore async def update( self, resource_group_name: str, workspace_name: str, cluster_name: str, parameters: "_models.ClusterUpdateParameters", **kwargs: Any ) -> "_models.Cluster": """Updates properties of a Cluster. :param resource_group_name: Name of the resource group to which the resource belongs. :type resource_group_name: str :param workspace_name: The name of the workspace. Workspace names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type workspace_name: str :param cluster_name: The name of the cluster within the specified resource group. Cluster names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type cluster_name: str :param parameters: Additional parameters for cluster update. :type parameters: ~batch_ai.models.ClusterUpdateParameters :keyword callable cls: A custom type or function that will be passed the direct response :return: Cluster, or the result of cls(response) :rtype: ~batch_ai.models.Cluster :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.Cluster"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2018-05-01" content_type = kwargs.pop("content_type", "application/json") accept = "application/json" # Construct URL url = self.update.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', pattern=r'^[-\w\._]+$'), 'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), '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 = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') body_content_kwargs = {} # type: Dict[str, Any] body_content = self._serialize.body(parameters, 'ClusterUpdateParameters') body_content_kwargs['content'] = body_content request = self._client.patch(url, query_parameters, header_parameters, **body_content_kwargs) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize('Cluster', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces/{workspaceName}/clusters/{clusterName}'} # type: ignore async def _delete_initial( self, resource_group_name: str, workspace_name: str, cluster_name: str, **kwargs: Any ) -> None: cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2018-05-01" accept = "application/json" # Construct URL url = self._delete_initial.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', pattern=r'^[-\w\._]+$'), 'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), '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 = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') request = self._client.delete(url, query_parameters, header_parameters) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) _delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces/{workspaceName}/clusters/{clusterName}'} # type: ignore async def begin_delete( self, resource_group_name: str, workspace_name: str, cluster_name: str, **kwargs: Any ) -> AsyncLROPoller[None]: """Deletes a Cluster. :param resource_group_name: Name of the resource group to which the resource belongs. :type resource_group_name: str :param workspace_name: The name of the workspace. Workspace names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type workspace_name: str :param cluster_name: The name of the cluster within the specified resource group. Cluster names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type cluster_name: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[None] :raises ~azure.core.exceptions.HttpResponseError: """ polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] cls = kwargs.pop('cls', None) # type: ClsType[None] lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval ) cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] if cont_token is None: raw_result = await self._delete_initial( resource_group_name=resource_group_name, workspace_name=workspace_name, cluster_name=cluster_name, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map', None) kwargs.pop('content_type', None) def get_long_running_output(pipeline_response): if cls: return cls(pipeline_response, None, {}) path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', pattern=r'^[-\w\._]+$'), 'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } if polling is True: polling_method = AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) elif polling is False: polling_method = AsyncNoPolling() else: polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output ) else: return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces/{workspaceName}/clusters/{clusterName}'} # type: ignore async def get( self, resource_group_name: str, workspace_name: str, cluster_name: str, **kwargs: Any ) -> "_models.Cluster": """Gets information about a Cluster. :param resource_group_name: Name of the resource group to which the resource belongs. :type resource_group_name: str :param workspace_name: The name of the workspace. Workspace names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type workspace_name: str :param cluster_name: The name of the cluster within the specified resource group. Cluster names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type cluster_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Cluster, or the result of cls(response) :rtype: ~batch_ai.models.Cluster :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.Cluster"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2018-05-01" accept = "application/json" # Construct URL url = self.get.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', pattern=r'^[-\w\._]+$'), 'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), '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 = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') request = self._client.get(url, query_parameters, header_parameters) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize('Cluster', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces/{workspaceName}/clusters/{clusterName}'} # type: ignore def list_remote_login_information( self, resource_group_name: str, workspace_name: str, cluster_name: str, **kwargs: Any ) -> AsyncIterable["_models.RemoteLoginInformationListResult"]: """Get the IP address, port of all the compute nodes in the Cluster. :param resource_group_name: Name of the resource group to which the resource belongs. :type resource_group_name: str :param workspace_name: The name of the workspace. Workspace names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type workspace_name: str :param cluster_name: The name of the cluster within the specified resource group. Cluster names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type cluster_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either RemoteLoginInformationListResult or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~batch_ai.models.RemoteLoginInformationListResult] :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.RemoteLoginInformationListResult"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2018-05-01" accept = "application/json" def prepare_request(next_link=None): # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') if not next_link: # Construct URL url = self.list_remote_login_information.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', pattern=r'^[-\w\._]+$'), 'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), '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 = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') request = self._client.post(url, query_parameters, header_parameters) else: url = next_link query_parameters = {} # type: Dict[str, Any] request = self._client.get(url, query_parameters, header_parameters) return request async def extract_data(pipeline_response): deserialized = self._deserialize('RemoteLoginInformationListResult', pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged( get_next, extract_data ) list_remote_login_information.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces/{workspaceName}/clusters/{clusterName}/listRemoteLoginInformation'} # type: ignore def list_by_workspace( self, resource_group_name: str, workspace_name: str, clusters_list_by_workspace_options: Optional["_models.ClustersListByWorkspaceOptions"] = None, **kwargs: Any ) -> AsyncIterable["_models.ClusterListResult"]: """Gets information about Clusters associated with the given Workspace. :param resource_group_name: Name of the resource group to which the resource belongs. :type resource_group_name: str :param workspace_name: The name of the workspace. Workspace names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type workspace_name: str :param clusters_list_by_workspace_options: Parameter group. :type clusters_list_by_workspace_options: ~batch_ai.models.ClustersListByWorkspaceOptions :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ClusterListResult or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~batch_ai.models.ClusterListResult] :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.ClusterListResult"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) _max_results = None if clusters_list_by_workspace_options is not None: _max_results = clusters_list_by_workspace_options.max_results api_version = "2018-05-01" accept = "application/json" def prepare_request(next_link=None): # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') if not next_link: # Construct URL url = self.list_by_workspace.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', pattern=r'^[-\w\._]+$'), 'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), '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 = {} # type: Dict[str, Any] if _max_results is not None: query_parameters['maxresults'] = self._serialize.query("max_results", _max_results, 'int', maximum=1000, minimum=1) query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') request = self._client.get(url, query_parameters, header_parameters) else: url = next_link query_parameters = {} # type: Dict[str, Any] request = self._client.get(url, query_parameters, header_parameters) return request async def extract_data(pipeline_response): deserialized = self._deserialize('ClusterListResult', pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged( get_next, extract_data ) list_by_workspace.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces/{workspaceName}/clusters'} # type: ignore
azure-mgmt-batchai
/azure-mgmt-batchai-7.0.0b1.zip/azure-mgmt-batchai-7.0.0b1/azure/mgmt/batchai/aio/operations/_clusters_operations.py
_clusters_operations.py
from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union import warnings from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling from ... import models as _models T = TypeVar('T') ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] class ClustersOperations: """ClustersOperations async operations. You should not instantiate this class directly. Instead, you should create a Client instance that instantiates it for you and attaches it as an attribute. :ivar models: Alias to model classes used in this operation group. :type models: ~batch_ai.models :param client: Client for service requests. :param config: Configuration of service client. :param serializer: An object model serializer. :param deserializer: An object model deserializer. """ models = _models def __init__(self, client, config, serializer, deserializer) -> None: self._client = client self._serialize = serializer self._deserialize = deserializer self._config = config async def _create_initial( self, resource_group_name: str, workspace_name: str, cluster_name: str, parameters: "_models.ClusterCreateParameters", **kwargs: Any ) -> Optional["_models.Cluster"]: cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.Cluster"]] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2018-05-01" content_type = kwargs.pop("content_type", "application/json") accept = "application/json" # Construct URL url = self._create_initial.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', pattern=r'^[-\w\._]+$'), 'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), '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 = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') body_content_kwargs = {} # type: Dict[str, Any] body_content = self._serialize.body(parameters, 'ClusterCreateParameters') body_content_kwargs['content'] = body_content request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = None if response.status_code == 200: deserialized = self._deserialize('Cluster', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized _create_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces/{workspaceName}/clusters/{clusterName}'} # type: ignore async def begin_create( self, resource_group_name: str, workspace_name: str, cluster_name: str, parameters: "_models.ClusterCreateParameters", **kwargs: Any ) -> AsyncLROPoller["_models.Cluster"]: """Creates a Cluster in the given Workspace. :param resource_group_name: Name of the resource group to which the resource belongs. :type resource_group_name: str :param workspace_name: The name of the workspace. Workspace names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type workspace_name: str :param cluster_name: The name of the cluster within the specified resource group. Cluster names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type cluster_name: str :param parameters: The parameters to provide for the Cluster creation. :type parameters: ~batch_ai.models.ClusterCreateParameters :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of AsyncLROPoller that returns either Cluster or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~batch_ai.models.Cluster] :raises ~azure.core.exceptions.HttpResponseError: """ polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] cls = kwargs.pop('cls', None) # type: ClsType["_models.Cluster"] lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval ) cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] if cont_token is None: raw_result = await self._create_initial( resource_group_name=resource_group_name, workspace_name=workspace_name, cluster_name=cluster_name, parameters=parameters, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map', None) kwargs.pop('content_type', None) def get_long_running_output(pipeline_response): deserialized = self._deserialize('Cluster', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', pattern=r'^[-\w\._]+$'), 'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } if polling is True: polling_method = AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) elif polling is False: polling_method = AsyncNoPolling() else: polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output ) else: return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_create.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces/{workspaceName}/clusters/{clusterName}'} # type: ignore async def update( self, resource_group_name: str, workspace_name: str, cluster_name: str, parameters: "_models.ClusterUpdateParameters", **kwargs: Any ) -> "_models.Cluster": """Updates properties of a Cluster. :param resource_group_name: Name of the resource group to which the resource belongs. :type resource_group_name: str :param workspace_name: The name of the workspace. Workspace names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type workspace_name: str :param cluster_name: The name of the cluster within the specified resource group. Cluster names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type cluster_name: str :param parameters: Additional parameters for cluster update. :type parameters: ~batch_ai.models.ClusterUpdateParameters :keyword callable cls: A custom type or function that will be passed the direct response :return: Cluster, or the result of cls(response) :rtype: ~batch_ai.models.Cluster :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.Cluster"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2018-05-01" content_type = kwargs.pop("content_type", "application/json") accept = "application/json" # Construct URL url = self.update.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', pattern=r'^[-\w\._]+$'), 'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), '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 = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') body_content_kwargs = {} # type: Dict[str, Any] body_content = self._serialize.body(parameters, 'ClusterUpdateParameters') body_content_kwargs['content'] = body_content request = self._client.patch(url, query_parameters, header_parameters, **body_content_kwargs) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize('Cluster', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces/{workspaceName}/clusters/{clusterName}'} # type: ignore async def _delete_initial( self, resource_group_name: str, workspace_name: str, cluster_name: str, **kwargs: Any ) -> None: cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2018-05-01" accept = "application/json" # Construct URL url = self._delete_initial.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', pattern=r'^[-\w\._]+$'), 'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), '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 = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') request = self._client.delete(url, query_parameters, header_parameters) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) _delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces/{workspaceName}/clusters/{clusterName}'} # type: ignore async def begin_delete( self, resource_group_name: str, workspace_name: str, cluster_name: str, **kwargs: Any ) -> AsyncLROPoller[None]: """Deletes a Cluster. :param resource_group_name: Name of the resource group to which the resource belongs. :type resource_group_name: str :param workspace_name: The name of the workspace. Workspace names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type workspace_name: str :param cluster_name: The name of the cluster within the specified resource group. Cluster names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type cluster_name: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[None] :raises ~azure.core.exceptions.HttpResponseError: """ polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] cls = kwargs.pop('cls', None) # type: ClsType[None] lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval ) cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] if cont_token is None: raw_result = await self._delete_initial( resource_group_name=resource_group_name, workspace_name=workspace_name, cluster_name=cluster_name, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map', None) kwargs.pop('content_type', None) def get_long_running_output(pipeline_response): if cls: return cls(pipeline_response, None, {}) path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', pattern=r'^[-\w\._]+$'), 'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } if polling is True: polling_method = AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) elif polling is False: polling_method = AsyncNoPolling() else: polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output ) else: return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces/{workspaceName}/clusters/{clusterName}'} # type: ignore async def get( self, resource_group_name: str, workspace_name: str, cluster_name: str, **kwargs: Any ) -> "_models.Cluster": """Gets information about a Cluster. :param resource_group_name: Name of the resource group to which the resource belongs. :type resource_group_name: str :param workspace_name: The name of the workspace. Workspace names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type workspace_name: str :param cluster_name: The name of the cluster within the specified resource group. Cluster names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type cluster_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Cluster, or the result of cls(response) :rtype: ~batch_ai.models.Cluster :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.Cluster"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2018-05-01" accept = "application/json" # Construct URL url = self.get.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', pattern=r'^[-\w\._]+$'), 'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), '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 = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') request = self._client.get(url, query_parameters, header_parameters) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize('Cluster', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces/{workspaceName}/clusters/{clusterName}'} # type: ignore def list_remote_login_information( self, resource_group_name: str, workspace_name: str, cluster_name: str, **kwargs: Any ) -> AsyncIterable["_models.RemoteLoginInformationListResult"]: """Get the IP address, port of all the compute nodes in the Cluster. :param resource_group_name: Name of the resource group to which the resource belongs. :type resource_group_name: str :param workspace_name: The name of the workspace. Workspace names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type workspace_name: str :param cluster_name: The name of the cluster within the specified resource group. Cluster names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type cluster_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either RemoteLoginInformationListResult or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~batch_ai.models.RemoteLoginInformationListResult] :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.RemoteLoginInformationListResult"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2018-05-01" accept = "application/json" def prepare_request(next_link=None): # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') if not next_link: # Construct URL url = self.list_remote_login_information.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', pattern=r'^[-\w\._]+$'), 'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), '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 = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') request = self._client.post(url, query_parameters, header_parameters) else: url = next_link query_parameters = {} # type: Dict[str, Any] request = self._client.get(url, query_parameters, header_parameters) return request async def extract_data(pipeline_response): deserialized = self._deserialize('RemoteLoginInformationListResult', pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged( get_next, extract_data ) list_remote_login_information.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces/{workspaceName}/clusters/{clusterName}/listRemoteLoginInformation'} # type: ignore def list_by_workspace( self, resource_group_name: str, workspace_name: str, clusters_list_by_workspace_options: Optional["_models.ClustersListByWorkspaceOptions"] = None, **kwargs: Any ) -> AsyncIterable["_models.ClusterListResult"]: """Gets information about Clusters associated with the given Workspace. :param resource_group_name: Name of the resource group to which the resource belongs. :type resource_group_name: str :param workspace_name: The name of the workspace. Workspace names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type workspace_name: str :param clusters_list_by_workspace_options: Parameter group. :type clusters_list_by_workspace_options: ~batch_ai.models.ClustersListByWorkspaceOptions :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ClusterListResult or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~batch_ai.models.ClusterListResult] :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.ClusterListResult"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) _max_results = None if clusters_list_by_workspace_options is not None: _max_results = clusters_list_by_workspace_options.max_results api_version = "2018-05-01" accept = "application/json" def prepare_request(next_link=None): # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') if not next_link: # Construct URL url = self.list_by_workspace.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', pattern=r'^[-\w\._]+$'), 'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), '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 = {} # type: Dict[str, Any] if _max_results is not None: query_parameters['maxresults'] = self._serialize.query("max_results", _max_results, 'int', maximum=1000, minimum=1) query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') request = self._client.get(url, query_parameters, header_parameters) else: url = next_link query_parameters = {} # type: Dict[str, Any] request = self._client.get(url, query_parameters, header_parameters) return request async def extract_data(pipeline_response): deserialized = self._deserialize('ClusterListResult', pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged( get_next, extract_data ) list_by_workspace.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces/{workspaceName}/clusters'} # type: ignore
0.91267
0.122996
from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union import warnings from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling from ... import models as _models T = TypeVar('T') ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] class FileServersOperations: """FileServersOperations async operations. You should not instantiate this class directly. Instead, you should create a Client instance that instantiates it for you and attaches it as an attribute. :ivar models: Alias to model classes used in this operation group. :type models: ~batch_ai.models :param client: Client for service requests. :param config: Configuration of service client. :param serializer: An object model serializer. :param deserializer: An object model deserializer. """ models = _models def __init__(self, client, config, serializer, deserializer) -> None: self._client = client self._serialize = serializer self._deserialize = deserializer self._config = config async def _create_initial( self, resource_group_name: str, workspace_name: str, file_server_name: str, parameters: "_models.FileServerCreateParameters", **kwargs: Any ) -> Optional["_models.FileServer"]: cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.FileServer"]] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2018-05-01" content_type = kwargs.pop("content_type", "application/json") accept = "application/json" # Construct URL url = self._create_initial.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', pattern=r'^[-\w\._]+$'), 'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'fileServerName': self._serialize.url("file_server_name", file_server_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), '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 = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') body_content_kwargs = {} # type: Dict[str, Any] body_content = self._serialize.body(parameters, 'FileServerCreateParameters') body_content_kwargs['content'] = body_content request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = None if response.status_code == 200: deserialized = self._deserialize('FileServer', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized _create_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces/{workspaceName}/fileServers/{fileServerName}'} # type: ignore async def begin_create( self, resource_group_name: str, workspace_name: str, file_server_name: str, parameters: "_models.FileServerCreateParameters", **kwargs: Any ) -> AsyncLROPoller["_models.FileServer"]: """Creates a File Server in the given workspace. :param resource_group_name: Name of the resource group to which the resource belongs. :type resource_group_name: str :param workspace_name: The name of the workspace. Workspace names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type workspace_name: str :param file_server_name: The name of the file server within the specified resource group. File server names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type file_server_name: str :param parameters: The parameters to provide for File Server creation. :type parameters: ~batch_ai.models.FileServerCreateParameters :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of AsyncLROPoller that returns either FileServer or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~batch_ai.models.FileServer] :raises ~azure.core.exceptions.HttpResponseError: """ polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] cls = kwargs.pop('cls', None) # type: ClsType["_models.FileServer"] lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval ) cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] if cont_token is None: raw_result = await self._create_initial( resource_group_name=resource_group_name, workspace_name=workspace_name, file_server_name=file_server_name, parameters=parameters, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map', None) kwargs.pop('content_type', None) def get_long_running_output(pipeline_response): deserialized = self._deserialize('FileServer', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', pattern=r'^[-\w\._]+$'), 'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'fileServerName': self._serialize.url("file_server_name", file_server_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } if polling is True: polling_method = AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) elif polling is False: polling_method = AsyncNoPolling() else: polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output ) else: return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_create.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces/{workspaceName}/fileServers/{fileServerName}'} # type: ignore def list_by_workspace( self, resource_group_name: str, workspace_name: str, file_servers_list_by_workspace_options: Optional["_models.FileServersListByWorkspaceOptions"] = None, **kwargs: Any ) -> AsyncIterable["_models.FileServerListResult"]: """Gets a list of File Servers associated with the specified workspace. :param resource_group_name: Name of the resource group to which the resource belongs. :type resource_group_name: str :param workspace_name: The name of the workspace. Workspace names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type workspace_name: str :param file_servers_list_by_workspace_options: Parameter group. :type file_servers_list_by_workspace_options: ~batch_ai.models.FileServersListByWorkspaceOptions :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either FileServerListResult or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~batch_ai.models.FileServerListResult] :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.FileServerListResult"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) _max_results = None if file_servers_list_by_workspace_options is not None: _max_results = file_servers_list_by_workspace_options.max_results api_version = "2018-05-01" accept = "application/json" def prepare_request(next_link=None): # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') if not next_link: # Construct URL url = self.list_by_workspace.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', pattern=r'^[-\w\._]+$'), 'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), '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 = {} # type: Dict[str, Any] if _max_results is not None: query_parameters['maxresults'] = self._serialize.query("max_results", _max_results, 'int', maximum=1000, minimum=1) query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') request = self._client.get(url, query_parameters, header_parameters) else: url = next_link query_parameters = {} # type: Dict[str, Any] request = self._client.get(url, query_parameters, header_parameters) return request async def extract_data(pipeline_response): deserialized = self._deserialize('FileServerListResult', pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged( get_next, extract_data ) list_by_workspace.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces/{workspaceName}/fileServers'} # type: ignore
azure-mgmt-batchai
/azure-mgmt-batchai-7.0.0b1.zip/azure-mgmt-batchai-7.0.0b1/azure/mgmt/batchai/aio/operations/_file_servers_operations.py
_file_servers_operations.py
from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union import warnings from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling from ... import models as _models T = TypeVar('T') ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] class FileServersOperations: """FileServersOperations async operations. You should not instantiate this class directly. Instead, you should create a Client instance that instantiates it for you and attaches it as an attribute. :ivar models: Alias to model classes used in this operation group. :type models: ~batch_ai.models :param client: Client for service requests. :param config: Configuration of service client. :param serializer: An object model serializer. :param deserializer: An object model deserializer. """ models = _models def __init__(self, client, config, serializer, deserializer) -> None: self._client = client self._serialize = serializer self._deserialize = deserializer self._config = config async def _create_initial( self, resource_group_name: str, workspace_name: str, file_server_name: str, parameters: "_models.FileServerCreateParameters", **kwargs: Any ) -> Optional["_models.FileServer"]: cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.FileServer"]] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2018-05-01" content_type = kwargs.pop("content_type", "application/json") accept = "application/json" # Construct URL url = self._create_initial.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', pattern=r'^[-\w\._]+$'), 'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'fileServerName': self._serialize.url("file_server_name", file_server_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), '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 = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') body_content_kwargs = {} # type: Dict[str, Any] body_content = self._serialize.body(parameters, 'FileServerCreateParameters') body_content_kwargs['content'] = body_content request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = None if response.status_code == 200: deserialized = self._deserialize('FileServer', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized _create_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces/{workspaceName}/fileServers/{fileServerName}'} # type: ignore async def begin_create( self, resource_group_name: str, workspace_name: str, file_server_name: str, parameters: "_models.FileServerCreateParameters", **kwargs: Any ) -> AsyncLROPoller["_models.FileServer"]: """Creates a File Server in the given workspace. :param resource_group_name: Name of the resource group to which the resource belongs. :type resource_group_name: str :param workspace_name: The name of the workspace. Workspace names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type workspace_name: str :param file_server_name: The name of the file server within the specified resource group. File server names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type file_server_name: str :param parameters: The parameters to provide for File Server creation. :type parameters: ~batch_ai.models.FileServerCreateParameters :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of AsyncLROPoller that returns either FileServer or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~batch_ai.models.FileServer] :raises ~azure.core.exceptions.HttpResponseError: """ polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] cls = kwargs.pop('cls', None) # type: ClsType["_models.FileServer"] lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval ) cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] if cont_token is None: raw_result = await self._create_initial( resource_group_name=resource_group_name, workspace_name=workspace_name, file_server_name=file_server_name, parameters=parameters, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map', None) kwargs.pop('content_type', None) def get_long_running_output(pipeline_response): deserialized = self._deserialize('FileServer', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', pattern=r'^[-\w\._]+$'), 'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'fileServerName': self._serialize.url("file_server_name", file_server_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } if polling is True: polling_method = AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) elif polling is False: polling_method = AsyncNoPolling() else: polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output ) else: return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_create.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces/{workspaceName}/fileServers/{fileServerName}'} # type: ignore def list_by_workspace( self, resource_group_name: str, workspace_name: str, file_servers_list_by_workspace_options: Optional["_models.FileServersListByWorkspaceOptions"] = None, **kwargs: Any ) -> AsyncIterable["_models.FileServerListResult"]: """Gets a list of File Servers associated with the specified workspace. :param resource_group_name: Name of the resource group to which the resource belongs. :type resource_group_name: str :param workspace_name: The name of the workspace. Workspace names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. :type workspace_name: str :param file_servers_list_by_workspace_options: Parameter group. :type file_servers_list_by_workspace_options: ~batch_ai.models.FileServersListByWorkspaceOptions :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either FileServerListResult or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~batch_ai.models.FileServerListResult] :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.FileServerListResult"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) _max_results = None if file_servers_list_by_workspace_options is not None: _max_results = file_servers_list_by_workspace_options.max_results api_version = "2018-05-01" accept = "application/json" def prepare_request(next_link=None): # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') if not next_link: # Construct URL url = self.list_by_workspace.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', pattern=r'^[-\w\._]+$'), 'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'), '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 = {} # type: Dict[str, Any] if _max_results is not None: query_parameters['maxresults'] = self._serialize.query("max_results", _max_results, 'int', maximum=1000, minimum=1) query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') request = self._client.get(url, query_parameters, header_parameters) else: url = next_link query_parameters = {} # type: Dict[str, Any] request = self._client.get(url, query_parameters, header_parameters) return request async def extract_data(pipeline_response): deserialized = self._deserialize('FileServerListResult', pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged( get_next, extract_data ) list_by_workspace.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces/{workspaceName}/fileServers'} # type: ignore
0.884713
0.104706
from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar import warnings from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models T = TypeVar('T') ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] class UsagesOperations: """UsagesOperations async operations. You should not instantiate this class directly. Instead, you should create a Client instance that instantiates it for you and attaches it as an attribute. :ivar models: Alias to model classes used in this operation group. :type models: ~batch_ai.models :param client: Client for service requests. :param config: Configuration of service client. :param serializer: An object model serializer. :param deserializer: An object model deserializer. """ models = _models def __init__(self, client, config, serializer, deserializer) -> None: self._client = client self._serialize = serializer self._deserialize = deserializer self._config = config def list( self, location: str, **kwargs: Any ) -> AsyncIterable["_models.ListUsagesResult"]: """Gets the current usage information as well as limits for Batch AI resources for given subscription. :param location: The location for which resource usage is queried. :type location: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ListUsagesResult or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~batch_ai.models.ListUsagesResult] :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.ListUsagesResult"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2018-05-01" accept = "application/json" def prepare_request(next_link=None): # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') if not next_link: # Construct URL url = self.list.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), 'location': self._serialize.url("location", location, 'str', pattern=r'^[-\w\._]+$'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') request = self._client.get(url, query_parameters, header_parameters) else: url = next_link query_parameters = {} # type: Dict[str, Any] request = self._client.get(url, query_parameters, header_parameters) return request async def extract_data(pipeline_response): deserialized = self._deserialize('ListUsagesResult', pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged( get_next, extract_data ) list.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.BatchAI/locations/{location}/usages'} # type: ignore
azure-mgmt-batchai
/azure-mgmt-batchai-7.0.0b1.zip/azure-mgmt-batchai-7.0.0b1/azure/mgmt/batchai/aio/operations/_usages_operations.py
_usages_operations.py
from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar import warnings from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models T = TypeVar('T') ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] class UsagesOperations: """UsagesOperations async operations. You should not instantiate this class directly. Instead, you should create a Client instance that instantiates it for you and attaches it as an attribute. :ivar models: Alias to model classes used in this operation group. :type models: ~batch_ai.models :param client: Client for service requests. :param config: Configuration of service client. :param serializer: An object model serializer. :param deserializer: An object model deserializer. """ models = _models def __init__(self, client, config, serializer, deserializer) -> None: self._client = client self._serialize = serializer self._deserialize = deserializer self._config = config def list( self, location: str, **kwargs: Any ) -> AsyncIterable["_models.ListUsagesResult"]: """Gets the current usage information as well as limits for Batch AI resources for given subscription. :param location: The location for which resource usage is queried. :type location: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ListUsagesResult or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~batch_ai.models.ListUsagesResult] :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.ListUsagesResult"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2018-05-01" accept = "application/json" def prepare_request(next_link=None): # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') if not next_link: # Construct URL url = self.list.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), 'location': self._serialize.url("location", location, 'str', pattern=r'^[-\w\._]+$'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') request = self._client.get(url, query_parameters, header_parameters) else: url = next_link query_parameters = {} # type: Dict[str, Any] request = self._client.get(url, query_parameters, header_parameters) return request async def extract_data(pipeline_response): deserialized = self._deserialize('ListUsagesResult', pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged( get_next, extract_data ) list.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.BatchAI/locations/{location}/usages'} # type: ignore
0.90355
0.127245
from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar import warnings from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models T = TypeVar('T') ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] class Operations: """Operations async operations. You should not instantiate this class directly. Instead, you should create a Client instance that instantiates it for you and attaches it as an attribute. :ivar models: Alias to model classes used in this operation group. :type models: ~batch_ai.models :param client: Client for service requests. :param config: Configuration of service client. :param serializer: An object model serializer. :param deserializer: An object model deserializer. """ models = _models def __init__(self, client, config, serializer, deserializer) -> None: self._client = client self._serialize = serializer self._deserialize = deserializer self._config = config def list( self, **kwargs: Any ) -> AsyncIterable["_models.OperationListResult"]: """Lists available operations for the Microsoft.BatchAI provider. :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either OperationListResult or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~batch_ai.models.OperationListResult] :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.OperationListResult"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2018-05-01" accept = "application/json" def prepare_request(next_link=None): # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') if not next_link: # Construct URL url = self.list.metadata['url'] # type: ignore # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') request = self._client.get(url, query_parameters, header_parameters) else: url = next_link query_parameters = {} # type: Dict[str, Any] request = self._client.get(url, query_parameters, header_parameters) return request async def extract_data(pipeline_response): deserialized = self._deserialize('OperationListResult', pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged( get_next, extract_data ) list.metadata = {'url': '/providers/Microsoft.BatchAI/operations'} # type: ignore
azure-mgmt-batchai
/azure-mgmt-batchai-7.0.0b1.zip/azure-mgmt-batchai-7.0.0b1/azure/mgmt/batchai/aio/operations/_operations.py
_operations.py
from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar import warnings from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models T = TypeVar('T') ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] class Operations: """Operations async operations. You should not instantiate this class directly. Instead, you should create a Client instance that instantiates it for you and attaches it as an attribute. :ivar models: Alias to model classes used in this operation group. :type models: ~batch_ai.models :param client: Client for service requests. :param config: Configuration of service client. :param serializer: An object model serializer. :param deserializer: An object model deserializer. """ models = _models def __init__(self, client, config, serializer, deserializer) -> None: self._client = client self._serialize = serializer self._deserialize = deserializer self._config = config def list( self, **kwargs: Any ) -> AsyncIterable["_models.OperationListResult"]: """Lists available operations for the Microsoft.BatchAI provider. :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either OperationListResult or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~batch_ai.models.OperationListResult] :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.OperationListResult"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2018-05-01" accept = "application/json" def prepare_request(next_link=None): # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') if not next_link: # Construct URL url = self.list.metadata['url'] # type: ignore # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') request = self._client.get(url, query_parameters, header_parameters) else: url = next_link query_parameters = {} # type: Dict[str, Any] request = self._client.get(url, query_parameters, header_parameters) return request async def extract_data(pipeline_response): deserialized = self._deserialize('OperationListResult', pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged( get_next, extract_data ) list.metadata = {'url': '/providers/Microsoft.BatchAI/operations'} # type: ignore
0.887162
0.115836
import msrest.serialization class AppInsightsReference(msrest.serialization.Model): """Azure Application Insights information for performance counters reporting. All required parameters must be populated in order to send to Azure. :param component: Required. Azure Application Insights component resource ID. :type component: ~batch_ai.models.ResourceId :param instrumentation_key: Value of the Azure Application Insights instrumentation key. :type instrumentation_key: str :param instrumentation_key_secret_reference: KeyVault Store and Secret which contains Azure Application Insights instrumentation key. One of instrumentationKey or instrumentationKeySecretReference must be specified. :type instrumentation_key_secret_reference: ~batch_ai.models.KeyVaultSecretReference """ _validation = { 'component': {'required': True}, } _attribute_map = { 'component': {'key': 'component', 'type': 'ResourceId'}, 'instrumentation_key': {'key': 'instrumentationKey', 'type': 'str'}, 'instrumentation_key_secret_reference': {'key': 'instrumentationKeySecretReference', 'type': 'KeyVaultSecretReference'}, } def __init__( self, **kwargs ): super(AppInsightsReference, self).__init__(**kwargs) self.component = kwargs['component'] self.instrumentation_key = kwargs.get('instrumentation_key', None) self.instrumentation_key_secret_reference = kwargs.get('instrumentation_key_secret_reference', None) class AutoScaleSettings(msrest.serialization.Model): """Auto-scale settings for the cluster. The system automatically scales the cluster up and down (within minimumNodeCount and maximumNodeCount) based on the number of queued and running jobs assigned to the cluster. All required parameters must be populated in order to send to Azure. :param minimum_node_count: Required. The minimum number of compute nodes the Batch AI service will try to allocate for the cluster. Note, the actual number of nodes can be less than the specified value if the subscription has not enough quota to fulfill the request. :type minimum_node_count: int :param maximum_node_count: Required. The maximum number of compute nodes the cluster can have. :type maximum_node_count: int :param initial_node_count: The number of compute nodes to allocate on cluster creation. Note that this value is used only during cluster creation. Default: 0. :type initial_node_count: int """ _validation = { 'minimum_node_count': {'required': True}, 'maximum_node_count': {'required': True}, } _attribute_map = { 'minimum_node_count': {'key': 'minimumNodeCount', 'type': 'int'}, 'maximum_node_count': {'key': 'maximumNodeCount', 'type': 'int'}, 'initial_node_count': {'key': 'initialNodeCount', 'type': 'int'}, } def __init__( self, **kwargs ): super(AutoScaleSettings, self).__init__(**kwargs) self.minimum_node_count = kwargs['minimum_node_count'] self.maximum_node_count = kwargs['maximum_node_count'] self.initial_node_count = kwargs.get('initial_node_count', 0) class AzureBlobFileSystemReference(msrest.serialization.Model): """Azure Blob Storage Container mounting configuration. All required parameters must be populated in order to send to Azure. :param account_name: Required. Name of the Azure storage account. :type account_name: str :param container_name: Required. Name of the Azure Blob Storage container to mount on the cluster. :type container_name: str :param credentials: Required. Information about the Azure storage credentials. :type credentials: ~batch_ai.models.AzureStorageCredentialsInfo :param relative_mount_path: Required. The relative path on the compute node where the Azure File container will be mounted. Note that all cluster level containers will be mounted under $AZ_BATCHAI_MOUNT_ROOT location and all job level containers will be mounted under $AZ_BATCHAI_JOB_MOUNT_ROOT. :type relative_mount_path: str :param mount_options: Mount options for mounting blobfuse file system. :type mount_options: str """ _validation = { 'account_name': {'required': True}, 'container_name': {'required': True}, 'credentials': {'required': True}, 'relative_mount_path': {'required': True}, } _attribute_map = { 'account_name': {'key': 'accountName', 'type': 'str'}, 'container_name': {'key': 'containerName', 'type': 'str'}, 'credentials': {'key': 'credentials', 'type': 'AzureStorageCredentialsInfo'}, 'relative_mount_path': {'key': 'relativeMountPath', 'type': 'str'}, 'mount_options': {'key': 'mountOptions', 'type': 'str'}, } def __init__( self, **kwargs ): super(AzureBlobFileSystemReference, self).__init__(**kwargs) self.account_name = kwargs['account_name'] self.container_name = kwargs['container_name'] self.credentials = kwargs['credentials'] self.relative_mount_path = kwargs['relative_mount_path'] self.mount_options = kwargs.get('mount_options', None) class AzureFileShareReference(msrest.serialization.Model): """Azure File Share mounting configuration. All required parameters must be populated in order to send to Azure. :param account_name: Required. Name of the Azure storage account. :type account_name: str :param azure_file_url: Required. URL to access the Azure File. :type azure_file_url: str :param credentials: Required. Information about the Azure storage credentials. :type credentials: ~batch_ai.models.AzureStorageCredentialsInfo :param relative_mount_path: Required. The relative path on the compute node where the Azure File share will be mounted. Note that all cluster level file shares will be mounted under $AZ_BATCHAI_MOUNT_ROOT location and all job level file shares will be mounted under $AZ_BATCHAI_JOB_MOUNT_ROOT. :type relative_mount_path: str :param file_mode: File mode for files on the mounted file share. Default value: 0777. :type file_mode: str :param directory_mode: File mode for directories on the mounted file share. Default value: 0777. :type directory_mode: str """ _validation = { 'account_name': {'required': True}, 'azure_file_url': {'required': True}, 'credentials': {'required': True}, 'relative_mount_path': {'required': True}, } _attribute_map = { 'account_name': {'key': 'accountName', 'type': 'str'}, 'azure_file_url': {'key': 'azureFileUrl', 'type': 'str'}, 'credentials': {'key': 'credentials', 'type': 'AzureStorageCredentialsInfo'}, 'relative_mount_path': {'key': 'relativeMountPath', 'type': 'str'}, 'file_mode': {'key': 'fileMode', 'type': 'str'}, 'directory_mode': {'key': 'directoryMode', 'type': 'str'}, } def __init__( self, **kwargs ): super(AzureFileShareReference, self).__init__(**kwargs) self.account_name = kwargs['account_name'] self.azure_file_url = kwargs['azure_file_url'] self.credentials = kwargs['credentials'] self.relative_mount_path = kwargs['relative_mount_path'] self.file_mode = kwargs.get('file_mode', "0777") self.directory_mode = kwargs.get('directory_mode', "0777") class AzureStorageCredentialsInfo(msrest.serialization.Model): """Azure storage account credentials. :param account_key: Storage account key. One of accountKey or accountKeySecretReference must be specified. :type account_key: str :param account_key_secret_reference: Information about KeyVault secret storing the storage account key. One of accountKey or accountKeySecretReference must be specified. :type account_key_secret_reference: ~batch_ai.models.KeyVaultSecretReference """ _attribute_map = { 'account_key': {'key': 'accountKey', 'type': 'str'}, 'account_key_secret_reference': {'key': 'accountKeySecretReference', 'type': 'KeyVaultSecretReference'}, } def __init__( self, **kwargs ): super(AzureStorageCredentialsInfo, self).__init__(**kwargs) self.account_key = kwargs.get('account_key', None) self.account_key_secret_reference = kwargs.get('account_key_secret_reference', None) class BatchAIError(msrest.serialization.Model): """An error response from the Batch AI service. Variables are only populated by the server, and will be ignored when sending a request. :ivar code: An identifier of the error. Codes are invariant and are intended to be consumed programmatically. :vartype code: str :ivar message: A message describing the error, intended to be suitable for display in a user interface. :vartype message: str :ivar details: A list of additional details about the error. :vartype details: list[~batch_ai.models.NameValuePair] """ _validation = { 'code': {'readonly': True}, 'message': {'readonly': True}, 'details': {'readonly': True}, } _attribute_map = { 'code': {'key': 'code', 'type': 'str'}, 'message': {'key': 'message', 'type': 'str'}, 'details': {'key': 'details', 'type': '[NameValuePair]'}, } def __init__( self, **kwargs ): super(BatchAIError, self).__init__(**kwargs) self.code = None self.message = None self.details = None class Caffe2Settings(msrest.serialization.Model): """Caffe2 job settings. All required parameters must be populated in order to send to Azure. :param python_script_file_path: Required. The python script to execute. :type python_script_file_path: str :param python_interpreter_path: The path to the Python interpreter. :type python_interpreter_path: str :param command_line_args: Command line arguments that need to be passed to the python script. :type command_line_args: str """ _validation = { 'python_script_file_path': {'required': True}, } _attribute_map = { 'python_script_file_path': {'key': 'pythonScriptFilePath', 'type': 'str'}, 'python_interpreter_path': {'key': 'pythonInterpreterPath', 'type': 'str'}, 'command_line_args': {'key': 'commandLineArgs', 'type': 'str'}, } def __init__( self, **kwargs ): super(Caffe2Settings, self).__init__(**kwargs) self.python_script_file_path = kwargs['python_script_file_path'] self.python_interpreter_path = kwargs.get('python_interpreter_path', None) self.command_line_args = kwargs.get('command_line_args', None) class CaffeSettings(msrest.serialization.Model): """Caffe job settings. :param config_file_path: Path of the config file for the job. This property cannot be specified if pythonScriptFilePath is specified. :type config_file_path: str :param python_script_file_path: Python script to execute. This property cannot be specified if configFilePath is specified. :type python_script_file_path: str :param python_interpreter_path: The path to the Python interpreter. The property can be specified only if the pythonScriptFilePath is specified. :type python_interpreter_path: str :param command_line_args: Command line arguments that need to be passed to the Caffe job. :type command_line_args: str :param process_count: Number of processes to launch for the job execution. The default value for this property is equal to nodeCount property. :type process_count: int """ _attribute_map = { 'config_file_path': {'key': 'configFilePath', 'type': 'str'}, 'python_script_file_path': {'key': 'pythonScriptFilePath', 'type': 'str'}, 'python_interpreter_path': {'key': 'pythonInterpreterPath', 'type': 'str'}, 'command_line_args': {'key': 'commandLineArgs', 'type': 'str'}, 'process_count': {'key': 'processCount', 'type': 'int'}, } def __init__( self, **kwargs ): super(CaffeSettings, self).__init__(**kwargs) self.config_file_path = kwargs.get('config_file_path', None) self.python_script_file_path = kwargs.get('python_script_file_path', None) self.python_interpreter_path = kwargs.get('python_interpreter_path', None) self.command_line_args = kwargs.get('command_line_args', None) self.process_count = kwargs.get('process_count', None) class ChainerSettings(msrest.serialization.Model): """Chainer job settings. All required parameters must be populated in order to send to Azure. :param python_script_file_path: Required. The python script to execute. :type python_script_file_path: str :param python_interpreter_path: The path to the Python interpreter. :type python_interpreter_path: str :param command_line_args: Command line arguments that need to be passed to the python script. :type command_line_args: str :param process_count: Number of processes to launch for the job execution. The default value for this property is equal to nodeCount property. :type process_count: int """ _validation = { 'python_script_file_path': {'required': True}, } _attribute_map = { 'python_script_file_path': {'key': 'pythonScriptFilePath', 'type': 'str'}, 'python_interpreter_path': {'key': 'pythonInterpreterPath', 'type': 'str'}, 'command_line_args': {'key': 'commandLineArgs', 'type': 'str'}, 'process_count': {'key': 'processCount', 'type': 'int'}, } def __init__( self, **kwargs ): super(ChainerSettings, self).__init__(**kwargs) self.python_script_file_path = kwargs['python_script_file_path'] self.python_interpreter_path = kwargs.get('python_interpreter_path', None) self.command_line_args = kwargs.get('command_line_args', None) self.process_count = kwargs.get('process_count', None) class CloudErrorBody(msrest.serialization.Model): """An error response from the Batch AI service. Variables are only populated by the server, and will be ignored when sending a request. :ivar code: An identifier for the error. Codes are invariant and are intended to be consumed programmatically. :vartype code: str :ivar message: A message describing the error, intended to be suitable for display in a user interface. :vartype message: str :ivar target: The target of the particular error. For example, the name of the property in error. :vartype target: str :ivar details: A list of additional details about the error. :vartype details: list[~batch_ai.models.CloudErrorBody] """ _validation = { 'code': {'readonly': True}, 'message': {'readonly': True}, 'target': {'readonly': True}, 'details': {'readonly': True}, } _attribute_map = { 'code': {'key': 'code', 'type': 'str'}, 'message': {'key': 'message', 'type': 'str'}, 'target': {'key': 'target', 'type': 'str'}, 'details': {'key': 'details', 'type': '[CloudErrorBody]'}, } def __init__( self, **kwargs ): super(CloudErrorBody, self).__init__(**kwargs) self.code = None self.message = None self.target = None self.details = None class ProxyResource(msrest.serialization.Model): """A definition of an Azure proxy resource. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: The ID of the resource. :vartype id: str :ivar name: The name of the resource. :vartype name: str :ivar type: The type of the resource. :vartype type: str """ _validation = { 'id': {'readonly': True}, 'name': {'readonly': True}, 'type': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, } def __init__( self, **kwargs ): super(ProxyResource, self).__init__(**kwargs) self.id = None self.name = None self.type = None class Cluster(ProxyResource): """Information about a Cluster. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: The ID of the resource. :vartype id: str :ivar name: The name of the resource. :vartype name: str :ivar type: The type of the resource. :vartype type: str :param vm_size: The size of the virtual machines in the cluster. All nodes in a cluster have the same VM size. :type vm_size: str :param vm_priority: VM priority of cluster nodes. Possible values include: "dedicated", "lowpriority". :type vm_priority: str or ~batch_ai.models.VmPriority :param scale_settings: Scale settings of the cluster. :type scale_settings: ~batch_ai.models.ScaleSettings :param virtual_machine_configuration: Virtual machine configuration (OS image) of the compute nodes. All nodes in a cluster have the same OS image configuration. :type virtual_machine_configuration: ~batch_ai.models.VirtualMachineConfiguration :param node_setup: Setup (mount file systems, performance counters settings and custom setup task) to be performed on each compute node in the cluster. :type node_setup: ~batch_ai.models.NodeSetup :param user_account_settings: Administrator user account settings which can be used to SSH to compute nodes. :type user_account_settings: ~batch_ai.models.UserAccountSettings :param subnet: Virtual network subnet resource ID the cluster nodes belong to. :type subnet: ~batch_ai.models.ResourceId :ivar creation_time: The time when the cluster was created. :vartype creation_time: ~datetime.datetime :ivar provisioning_state: Provisioning state of the cluster. Possible value are: creating - Specifies that the cluster is being created. succeeded - Specifies that the cluster has been created successfully. failed - Specifies that the cluster creation has failed. deleting - Specifies that the cluster is being deleted. Possible values include: "creating", "succeeded", "failed", "deleting". :vartype provisioning_state: str or ~batch_ai.models.ProvisioningState :ivar provisioning_state_transition_time: Time when the provisioning state was changed. :vartype provisioning_state_transition_time: ~datetime.datetime :ivar allocation_state: Allocation state of the cluster. Possible values are: steady - Indicates that the cluster is not resizing. There are no changes to the number of compute nodes in the cluster in progress. A cluster enters this state when it is created and when no operations are being performed on the cluster to change the number of compute nodes. resizing - Indicates that the cluster is resizing; that is, compute nodes are being added to or removed from the cluster. Possible values include: "steady", "resizing". :vartype allocation_state: str or ~batch_ai.models.AllocationState :ivar allocation_state_transition_time: The time at which the cluster entered its current allocation state. :vartype allocation_state_transition_time: ~datetime.datetime :ivar errors: Collection of errors encountered by various compute nodes during node setup. :vartype errors: list[~batch_ai.models.BatchAIError] :ivar current_node_count: The number of compute nodes currently assigned to the cluster. :vartype current_node_count: int :ivar node_state_counts: Counts of various node states on the cluster. :vartype node_state_counts: ~batch_ai.models.NodeStateCounts """ _validation = { 'id': {'readonly': True}, 'name': {'readonly': True}, 'type': {'readonly': True}, 'creation_time': {'readonly': True}, 'provisioning_state': {'readonly': True}, 'provisioning_state_transition_time': {'readonly': True}, 'allocation_state': {'readonly': True}, 'allocation_state_transition_time': {'readonly': True}, 'errors': {'readonly': True}, 'current_node_count': {'readonly': True}, 'node_state_counts': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'vm_size': {'key': 'properties.vmSize', 'type': 'str'}, 'vm_priority': {'key': 'properties.vmPriority', 'type': 'str'}, 'scale_settings': {'key': 'properties.scaleSettings', 'type': 'ScaleSettings'}, 'virtual_machine_configuration': {'key': 'properties.virtualMachineConfiguration', 'type': 'VirtualMachineConfiguration'}, 'node_setup': {'key': 'properties.nodeSetup', 'type': 'NodeSetup'}, 'user_account_settings': {'key': 'properties.userAccountSettings', 'type': 'UserAccountSettings'}, 'subnet': {'key': 'properties.subnet', 'type': 'ResourceId'}, 'creation_time': {'key': 'properties.creationTime', 'type': 'iso-8601'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'provisioning_state_transition_time': {'key': 'properties.provisioningStateTransitionTime', 'type': 'iso-8601'}, 'allocation_state': {'key': 'properties.allocationState', 'type': 'str'}, 'allocation_state_transition_time': {'key': 'properties.allocationStateTransitionTime', 'type': 'iso-8601'}, 'errors': {'key': 'properties.errors', 'type': '[BatchAIError]'}, 'current_node_count': {'key': 'properties.currentNodeCount', 'type': 'int'}, 'node_state_counts': {'key': 'properties.nodeStateCounts', 'type': 'NodeStateCounts'}, } def __init__( self, **kwargs ): super(Cluster, self).__init__(**kwargs) self.vm_size = kwargs.get('vm_size', None) self.vm_priority = kwargs.get('vm_priority', None) self.scale_settings = kwargs.get('scale_settings', None) self.virtual_machine_configuration = kwargs.get('virtual_machine_configuration', None) self.node_setup = kwargs.get('node_setup', None) self.user_account_settings = kwargs.get('user_account_settings', None) self.subnet = kwargs.get('subnet', None) self.creation_time = None self.provisioning_state = None self.provisioning_state_transition_time = None self.allocation_state = None self.allocation_state_transition_time = None self.errors = None self.current_node_count = None self.node_state_counts = None class ClusterCreateParameters(msrest.serialization.Model): """Cluster creation operation. :param vm_size: The size of the virtual machines in the cluster. All nodes in a cluster have the same VM size. For information about available VM sizes for clusters using images from the Virtual Machines Marketplace see Sizes for Virtual Machines (Linux). Batch AI service supports all Azure VM sizes except STANDARD_A0 and those with premium storage (STANDARD_GS, STANDARD_DS, and STANDARD_DSV2 series). :type vm_size: str :param vm_priority: VM priority. Allowed values are: dedicated (default) and lowpriority. Possible values include: "dedicated", "lowpriority". :type vm_priority: str or ~batch_ai.models.VmPriority :param scale_settings: Scale settings for the cluster. Batch AI service supports manual and auto scale clusters. :type scale_settings: ~batch_ai.models.ScaleSettings :param virtual_machine_configuration: OS image configuration for cluster nodes. All nodes in a cluster have the same OS image. :type virtual_machine_configuration: ~batch_ai.models.VirtualMachineConfiguration :param node_setup: Setup to be performed on each compute node in the cluster. :type node_setup: ~batch_ai.models.NodeSetup :param user_account_settings: Settings for an administrator user account that will be created on each compute node in the cluster. :type user_account_settings: ~batch_ai.models.UserAccountSettings :param subnet: Existing virtual network subnet to put the cluster nodes in. Note, if a File Server mount configured in node setup, the File Server's subnet will be used automatically. :type subnet: ~batch_ai.models.ResourceId """ _attribute_map = { 'vm_size': {'key': 'properties.vmSize', 'type': 'str'}, 'vm_priority': {'key': 'properties.vmPriority', 'type': 'str'}, 'scale_settings': {'key': 'properties.scaleSettings', 'type': 'ScaleSettings'}, 'virtual_machine_configuration': {'key': 'properties.virtualMachineConfiguration', 'type': 'VirtualMachineConfiguration'}, 'node_setup': {'key': 'properties.nodeSetup', 'type': 'NodeSetup'}, 'user_account_settings': {'key': 'properties.userAccountSettings', 'type': 'UserAccountSettings'}, 'subnet': {'key': 'properties.subnet', 'type': 'ResourceId'}, } def __init__( self, **kwargs ): super(ClusterCreateParameters, self).__init__(**kwargs) self.vm_size = kwargs.get('vm_size', None) self.vm_priority = kwargs.get('vm_priority', None) self.scale_settings = kwargs.get('scale_settings', None) self.virtual_machine_configuration = kwargs.get('virtual_machine_configuration', None) self.node_setup = kwargs.get('node_setup', None) self.user_account_settings = kwargs.get('user_account_settings', None) self.subnet = kwargs.get('subnet', None) class ClusterListResult(msrest.serialization.Model): """Values returned by the List Clusters operation. Variables are only populated by the server, and will be ignored when sending a request. :ivar value: The collection of returned Clusters. :vartype value: list[~batch_ai.models.Cluster] :ivar next_link: The continuation token. :vartype next_link: str """ _validation = { 'value': {'readonly': True}, 'next_link': {'readonly': True}, } _attribute_map = { 'value': {'key': 'value', 'type': '[Cluster]'}, 'next_link': {'key': 'nextLink', 'type': 'str'}, } def __init__( self, **kwargs ): super(ClusterListResult, self).__init__(**kwargs) self.value = None self.next_link = None class ClustersListByWorkspaceOptions(msrest.serialization.Model): """Parameter group. :param max_results: The maximum number of items to return in the response. A maximum of 1000 files can be returned. :type max_results: int """ _validation = { 'max_results': {'maximum': 1000, 'minimum': 1}, } _attribute_map = { 'max_results': {'key': 'maxResults', 'type': 'int'}, } def __init__( self, **kwargs ): super(ClustersListByWorkspaceOptions, self).__init__(**kwargs) self.max_results = kwargs.get('max_results', 1000) class ClusterUpdateParameters(msrest.serialization.Model): """Cluster update parameters. :param scale_settings: Desired scale settings for the cluster. Batch AI service supports manual and auto scale clusters. :type scale_settings: ~batch_ai.models.ScaleSettings """ _attribute_map = { 'scale_settings': {'key': 'properties.scaleSettings', 'type': 'ScaleSettings'}, } def __init__( self, **kwargs ): super(ClusterUpdateParameters, self).__init__(**kwargs) self.scale_settings = kwargs.get('scale_settings', None) class CNTKsettings(msrest.serialization.Model): """CNTK (aka Microsoft Cognitive Toolkit) job settings. :param language_type: The language to use for launching CNTK (aka Microsoft Cognitive Toolkit) job. Valid values are 'BrainScript' or 'Python'. :type language_type: str :param config_file_path: Specifies the path of the BrainScript config file. This property can be specified only if the languageType is 'BrainScript'. :type config_file_path: str :param python_script_file_path: Python script to execute. This property can be specified only if the languageType is 'Python'. :type python_script_file_path: str :param python_interpreter_path: The path to the Python interpreter. This property can be specified only if the languageType is 'Python'. :type python_interpreter_path: str :param command_line_args: Command line arguments that need to be passed to the python script or cntk executable. :type command_line_args: str :param process_count: Number of processes to launch for the job execution. The default value for this property is equal to nodeCount property. :type process_count: int """ _attribute_map = { 'language_type': {'key': 'languageType', 'type': 'str'}, 'config_file_path': {'key': 'configFilePath', 'type': 'str'}, 'python_script_file_path': {'key': 'pythonScriptFilePath', 'type': 'str'}, 'python_interpreter_path': {'key': 'pythonInterpreterPath', 'type': 'str'}, 'command_line_args': {'key': 'commandLineArgs', 'type': 'str'}, 'process_count': {'key': 'processCount', 'type': 'int'}, } def __init__( self, **kwargs ): super(CNTKsettings, self).__init__(**kwargs) self.language_type = kwargs.get('language_type', None) self.config_file_path = kwargs.get('config_file_path', None) self.python_script_file_path = kwargs.get('python_script_file_path', None) self.python_interpreter_path = kwargs.get('python_interpreter_path', None) self.command_line_args = kwargs.get('command_line_args', None) self.process_count = kwargs.get('process_count', None) class ContainerSettings(msrest.serialization.Model): """Docker container settings. All required parameters must be populated in order to send to Azure. :param image_source_registry: Required. Information about docker image and docker registry to download the container from. :type image_source_registry: ~batch_ai.models.ImageSourceRegistry :param shm_size: Size of /dev/shm. Please refer to docker documentation for supported argument formats. :type shm_size: str """ _validation = { 'image_source_registry': {'required': True}, } _attribute_map = { 'image_source_registry': {'key': 'imageSourceRegistry', 'type': 'ImageSourceRegistry'}, 'shm_size': {'key': 'shmSize', 'type': 'str'}, } def __init__( self, **kwargs ): super(ContainerSettings, self).__init__(**kwargs) self.image_source_registry = kwargs['image_source_registry'] self.shm_size = kwargs.get('shm_size', None) class CustomMpiSettings(msrest.serialization.Model): """Custom MPI job settings. All required parameters must be populated in order to send to Azure. :param command_line: Required. The command line to be executed by mpi runtime on each compute node. :type command_line: str :param process_count: Number of processes to launch for the job execution. The default value for this property is equal to nodeCount property. :type process_count: int """ _validation = { 'command_line': {'required': True}, } _attribute_map = { 'command_line': {'key': 'commandLine', 'type': 'str'}, 'process_count': {'key': 'processCount', 'type': 'int'}, } def __init__( self, **kwargs ): super(CustomMpiSettings, self).__init__(**kwargs) self.command_line = kwargs['command_line'] self.process_count = kwargs.get('process_count', None) class CustomToolkitSettings(msrest.serialization.Model): """Custom tool kit job settings. :param command_line: The command line to execute on the master node. :type command_line: str """ _attribute_map = { 'command_line': {'key': 'commandLine', 'type': 'str'}, } def __init__( self, **kwargs ): super(CustomToolkitSettings, self).__init__(**kwargs) self.command_line = kwargs.get('command_line', None) class DataDisks(msrest.serialization.Model): """Data disks settings. All required parameters must be populated in order to send to Azure. :param disk_size_in_gb: Required. Disk size in GB for the blank data disks. :type disk_size_in_gb: int :param caching_type: Caching type for the disks. Available values are none (default), readonly, readwrite. Caching type can be set only for VM sizes supporting premium storage. Possible values include: "none", "readonly", "readwrite". Default value: "none". :type caching_type: str or ~batch_ai.models.CachingType :param disk_count: Required. Number of data disks attached to the File Server. If multiple disks attached, they will be configured in RAID level 0. :type disk_count: int :param storage_account_type: Required. Type of storage account to be used on the disk. Possible values are: Standard_LRS or Premium_LRS. Premium storage account type can only be used with VM sizes supporting premium storage. Possible values include: "Standard_LRS", "Premium_LRS". :type storage_account_type: str or ~batch_ai.models.StorageAccountType """ _validation = { 'disk_size_in_gb': {'required': True}, 'disk_count': {'required': True}, 'storage_account_type': {'required': True}, } _attribute_map = { 'disk_size_in_gb': {'key': 'diskSizeInGB', 'type': 'int'}, 'caching_type': {'key': 'cachingType', 'type': 'str'}, 'disk_count': {'key': 'diskCount', 'type': 'int'}, 'storage_account_type': {'key': 'storageAccountType', 'type': 'str'}, } def __init__( self, **kwargs ): super(DataDisks, self).__init__(**kwargs) self.disk_size_in_gb = kwargs['disk_size_in_gb'] self.caching_type = kwargs.get('caching_type', "none") self.disk_count = kwargs['disk_count'] self.storage_account_type = kwargs['storage_account_type'] class EnvironmentVariable(msrest.serialization.Model): """An environment variable definition. All required parameters must be populated in order to send to Azure. :param name: Required. The name of the environment variable. :type name: str :param value: Required. The value of the environment variable. :type value: str """ _validation = { 'name': {'required': True}, 'value': {'required': True}, } _attribute_map = { 'name': {'key': 'name', 'type': 'str'}, 'value': {'key': 'value', 'type': 'str'}, } def __init__( self, **kwargs ): super(EnvironmentVariable, self).__init__(**kwargs) self.name = kwargs['name'] self.value = kwargs['value'] class EnvironmentVariableWithSecretValue(msrest.serialization.Model): """An environment variable with secret value definition. All required parameters must be populated in order to send to Azure. :param name: Required. The name of the environment variable to store the secret value. :type name: str :param value: The value of the environment variable. This value will never be reported back by Batch AI. :type value: str :param value_secret_reference: KeyVault store and secret which contains the value for the environment variable. One of value or valueSecretReference must be provided. :type value_secret_reference: ~batch_ai.models.KeyVaultSecretReference """ _validation = { 'name': {'required': True}, } _attribute_map = { 'name': {'key': 'name', 'type': 'str'}, 'value': {'key': 'value', 'type': 'str'}, 'value_secret_reference': {'key': 'valueSecretReference', 'type': 'KeyVaultSecretReference'}, } def __init__( self, **kwargs ): super(EnvironmentVariableWithSecretValue, self).__init__(**kwargs) self.name = kwargs['name'] self.value = kwargs.get('value', None) self.value_secret_reference = kwargs.get('value_secret_reference', None) class Experiment(ProxyResource): """Experiment information. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: The ID of the resource. :vartype id: str :ivar name: The name of the resource. :vartype name: str :ivar type: The type of the resource. :vartype type: str :ivar creation_time: Time when the Experiment was created. :vartype creation_time: ~datetime.datetime :ivar provisioning_state: The provisioned state of the experiment. Possible values include: "creating", "succeeded", "failed", "deleting". :vartype provisioning_state: str or ~batch_ai.models.ProvisioningState :ivar provisioning_state_transition_time: The time at which the experiment entered its current provisioning state. :vartype provisioning_state_transition_time: ~datetime.datetime """ _validation = { 'id': {'readonly': True}, 'name': {'readonly': True}, 'type': {'readonly': True}, 'creation_time': {'readonly': True}, 'provisioning_state': {'readonly': True}, 'provisioning_state_transition_time': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'creation_time': {'key': 'properties.creationTime', 'type': 'iso-8601'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'provisioning_state_transition_time': {'key': 'properties.provisioningStateTransitionTime', 'type': 'iso-8601'}, } def __init__( self, **kwargs ): super(Experiment, self).__init__(**kwargs) self.creation_time = None self.provisioning_state = None self.provisioning_state_transition_time = None class ExperimentListResult(msrest.serialization.Model): """Values returned by the List operation. Variables are only populated by the server, and will be ignored when sending a request. :ivar value: The collection of experiments. :vartype value: list[~batch_ai.models.Experiment] :ivar next_link: The continuation token. :vartype next_link: str """ _validation = { 'value': {'readonly': True}, 'next_link': {'readonly': True}, } _attribute_map = { 'value': {'key': 'value', 'type': '[Experiment]'}, 'next_link': {'key': 'nextLink', 'type': 'str'}, } def __init__( self, **kwargs ): super(ExperimentListResult, self).__init__(**kwargs) self.value = None self.next_link = None class ExperimentsListByWorkspaceOptions(msrest.serialization.Model): """Parameter group. :param max_results: The maximum number of items to return in the response. A maximum of 1000 files can be returned. :type max_results: int """ _validation = { 'max_results': {'maximum': 1000, 'minimum': 1}, } _attribute_map = { 'max_results': {'key': 'maxResults', 'type': 'int'}, } def __init__( self, **kwargs ): super(ExperimentsListByWorkspaceOptions, self).__init__(**kwargs) self.max_results = kwargs.get('max_results', 1000) class File(msrest.serialization.Model): """Properties of the file or directory. Variables are only populated by the server, and will be ignored when sending a request. :ivar name: Name of the file. :vartype name: str :ivar file_type: Type of the file. Possible values are file and directory. Possible values include: "file", "directory". :vartype file_type: str or ~batch_ai.models.FileType :ivar download_url: URL to download the corresponding file. The downloadUrl is not returned for directories. :vartype download_url: str :ivar last_modified: The time at which the file was last modified. :vartype last_modified: ~datetime.datetime :ivar content_length: The file of the size. :vartype content_length: long """ _validation = { 'name': {'readonly': True}, 'file_type': {'readonly': True}, 'download_url': {'readonly': True}, 'last_modified': {'readonly': True}, 'content_length': {'readonly': True}, } _attribute_map = { 'name': {'key': 'name', 'type': 'str'}, 'file_type': {'key': 'fileType', 'type': 'str'}, 'download_url': {'key': 'downloadUrl', 'type': 'str'}, 'last_modified': {'key': 'properties.lastModified', 'type': 'iso-8601'}, 'content_length': {'key': 'properties.contentLength', 'type': 'long'}, } def __init__( self, **kwargs ): super(File, self).__init__(**kwargs) self.name = None self.file_type = None self.download_url = None self.last_modified = None self.content_length = None class FileListResult(msrest.serialization.Model): """Values returned by the List operation. Variables are only populated by the server, and will be ignored when sending a request. :ivar value: The collection of returned job directories and files. :vartype value: list[~batch_ai.models.File] :ivar next_link: The continuation token. :vartype next_link: str """ _validation = { 'value': {'readonly': True}, 'next_link': {'readonly': True}, } _attribute_map = { 'value': {'key': 'value', 'type': '[File]'}, 'next_link': {'key': 'nextLink', 'type': 'str'}, } def __init__( self, **kwargs ): super(FileListResult, self).__init__(**kwargs) self.value = None self.next_link = None class FileServer(ProxyResource): """File Server information. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: The ID of the resource. :vartype id: str :ivar name: The name of the resource. :vartype name: str :ivar type: The type of the resource. :vartype type: str :param vm_size: VM size of the File Server. :type vm_size: str :param ssh_configuration: SSH configuration for accessing the File Server node. :type ssh_configuration: ~batch_ai.models.SshConfiguration :param data_disks: Information about disks attached to File Server VM. :type data_disks: ~batch_ai.models.DataDisks :param subnet: File Server virtual network subnet resource ID. :type subnet: ~batch_ai.models.ResourceId :ivar mount_settings: File Server mount settings. :vartype mount_settings: ~batch_ai.models.MountSettings :ivar provisioning_state_transition_time: Time when the provisioning state was changed. :vartype provisioning_state_transition_time: ~datetime.datetime :ivar creation_time: Time when the FileServer was created. :vartype creation_time: ~datetime.datetime :ivar provisioning_state: Provisioning state of the File Server. Possible values: creating - The File Server is getting created; updating - The File Server creation has been accepted and it is getting updated; deleting - The user has requested that the File Server be deleted, and it is in the process of being deleted; failed - The File Server creation has failed with the specified error code. Details about the error code are specified in the message field; succeeded - The File Server creation has succeeded. Possible values include: "creating", "updating", "deleting", "succeeded", "failed". :vartype provisioning_state: str or ~batch_ai.models.FileServerProvisioningState """ _validation = { 'id': {'readonly': True}, 'name': {'readonly': True}, 'type': {'readonly': True}, 'mount_settings': {'readonly': True}, 'provisioning_state_transition_time': {'readonly': True}, 'creation_time': {'readonly': True}, 'provisioning_state': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'vm_size': {'key': 'properties.vmSize', 'type': 'str'}, 'ssh_configuration': {'key': 'properties.sshConfiguration', 'type': 'SshConfiguration'}, 'data_disks': {'key': 'properties.dataDisks', 'type': 'DataDisks'}, 'subnet': {'key': 'properties.subnet', 'type': 'ResourceId'}, 'mount_settings': {'key': 'properties.mountSettings', 'type': 'MountSettings'}, 'provisioning_state_transition_time': {'key': 'properties.provisioningStateTransitionTime', 'type': 'iso-8601'}, 'creation_time': {'key': 'properties.creationTime', 'type': 'iso-8601'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, } def __init__( self, **kwargs ): super(FileServer, self).__init__(**kwargs) self.vm_size = kwargs.get('vm_size', None) self.ssh_configuration = kwargs.get('ssh_configuration', None) self.data_disks = kwargs.get('data_disks', None) self.subnet = kwargs.get('subnet', None) self.mount_settings = None self.provisioning_state_transition_time = None self.creation_time = None self.provisioning_state = None class FileServerCreateParameters(msrest.serialization.Model): """File Server creation parameters. :param vm_size: The size of the virtual machine for the File Server. For information about available VM sizes from the Virtual Machines Marketplace, see Sizes for Virtual Machines (Linux). :type vm_size: str :param ssh_configuration: SSH configuration for the File Server node. :type ssh_configuration: ~batch_ai.models.SshConfiguration :param data_disks: Settings for the data disks which will be created for the File Server. :type data_disks: ~batch_ai.models.DataDisks :param subnet: Identifier of an existing virtual network subnet to put the File Server in. If not provided, a new virtual network and subnet will be created. :type subnet: ~batch_ai.models.ResourceId """ _attribute_map = { 'vm_size': {'key': 'properties.vmSize', 'type': 'str'}, 'ssh_configuration': {'key': 'properties.sshConfiguration', 'type': 'SshConfiguration'}, 'data_disks': {'key': 'properties.dataDisks', 'type': 'DataDisks'}, 'subnet': {'key': 'properties.subnet', 'type': 'ResourceId'}, } def __init__( self, **kwargs ): super(FileServerCreateParameters, self).__init__(**kwargs) self.vm_size = kwargs.get('vm_size', None) self.ssh_configuration = kwargs.get('ssh_configuration', None) self.data_disks = kwargs.get('data_disks', None) self.subnet = kwargs.get('subnet', None) class FileServerListResult(msrest.serialization.Model): """Values returned by the File Server List operation. Variables are only populated by the server, and will be ignored when sending a request. :param value: The collection of File Servers. :type value: list[~batch_ai.models.FileServer] :ivar next_link: The continuation token. :vartype next_link: str """ _validation = { 'next_link': {'readonly': True}, } _attribute_map = { 'value': {'key': 'value', 'type': '[FileServer]'}, 'next_link': {'key': 'nextLink', 'type': 'str'}, } def __init__( self, **kwargs ): super(FileServerListResult, self).__init__(**kwargs) self.value = kwargs.get('value', None) self.next_link = None class FileServerReference(msrest.serialization.Model): """File Server mounting configuration. All required parameters must be populated in order to send to Azure. :param file_server: Required. Resource ID of the existing File Server to be mounted. :type file_server: ~batch_ai.models.ResourceId :param source_directory: File Server directory that needs to be mounted. If this property is not specified, the entire File Server will be mounted. :type source_directory: str :param relative_mount_path: Required. The relative path on the compute node where the File Server will be mounted. Note that all cluster level file servers will be mounted under $AZ_BATCHAI_MOUNT_ROOT location and all job level file servers will be mounted under $AZ_BATCHAI_JOB_MOUNT_ROOT. :type relative_mount_path: str :param mount_options: Mount options to be passed to mount command. :type mount_options: str """ _validation = { 'file_server': {'required': True}, 'relative_mount_path': {'required': True}, } _attribute_map = { 'file_server': {'key': 'fileServer', 'type': 'ResourceId'}, 'source_directory': {'key': 'sourceDirectory', 'type': 'str'}, 'relative_mount_path': {'key': 'relativeMountPath', 'type': 'str'}, 'mount_options': {'key': 'mountOptions', 'type': 'str'}, } def __init__( self, **kwargs ): super(FileServerReference, self).__init__(**kwargs) self.file_server = kwargs['file_server'] self.source_directory = kwargs.get('source_directory', None) self.relative_mount_path = kwargs['relative_mount_path'] self.mount_options = kwargs.get('mount_options', None) class FileServersListByWorkspaceOptions(msrest.serialization.Model): """Parameter group. :param max_results: The maximum number of items to return in the response. A maximum of 1000 files can be returned. :type max_results: int """ _validation = { 'max_results': {'maximum': 1000, 'minimum': 1}, } _attribute_map = { 'max_results': {'key': 'maxResults', 'type': 'int'}, } def __init__( self, **kwargs ): super(FileServersListByWorkspaceOptions, self).__init__(**kwargs) self.max_results = kwargs.get('max_results', 1000) class HorovodSettings(msrest.serialization.Model): """Specifies the settings for Horovod job. All required parameters must be populated in order to send to Azure. :param python_script_file_path: Required. The python script to execute. :type python_script_file_path: str :param python_interpreter_path: The path to the Python interpreter. :type python_interpreter_path: str :param command_line_args: Command line arguments that need to be passed to the python script. :type command_line_args: str :param process_count: Number of processes to launch for the job execution. The default value for this property is equal to nodeCount property. :type process_count: int """ _validation = { 'python_script_file_path': {'required': True}, } _attribute_map = { 'python_script_file_path': {'key': 'pythonScriptFilePath', 'type': 'str'}, 'python_interpreter_path': {'key': 'pythonInterpreterPath', 'type': 'str'}, 'command_line_args': {'key': 'commandLineArgs', 'type': 'str'}, 'process_count': {'key': 'processCount', 'type': 'int'}, } def __init__( self, **kwargs ): super(HorovodSettings, self).__init__(**kwargs) self.python_script_file_path = kwargs['python_script_file_path'] self.python_interpreter_path = kwargs.get('python_interpreter_path', None) self.command_line_args = kwargs.get('command_line_args', None) self.process_count = kwargs.get('process_count', None) class ImageReference(msrest.serialization.Model): """The OS image reference. All required parameters must be populated in order to send to Azure. :param publisher: Required. Publisher of the image. :type publisher: str :param offer: Required. Offer of the image. :type offer: str :param sku: Required. SKU of the image. :type sku: str :param version: Version of the image. :type version: str :param virtual_machine_image_id: The ARM resource identifier of the virtual machine image for the compute nodes. This is of the form /subscriptions/{subscriptionId}/resourceGroups/{resourceGroup}/providers/Microsoft.Compute/images/{imageName}. The virtual machine image must be in the same region and subscription as the cluster. For information about the firewall settings for the Batch node agent to communicate with the Batch service see https://docs.microsoft.com/en-us/azure/batch/batch-api-basics#virtual-network-vnet-and-firewall-configuration. Note, you need to provide publisher, offer and sku of the base OS image of which the custom image has been derived from. :type virtual_machine_image_id: str """ _validation = { 'publisher': {'required': True}, 'offer': {'required': True}, 'sku': {'required': True}, } _attribute_map = { 'publisher': {'key': 'publisher', 'type': 'str'}, 'offer': {'key': 'offer', 'type': 'str'}, 'sku': {'key': 'sku', 'type': 'str'}, 'version': {'key': 'version', 'type': 'str'}, 'virtual_machine_image_id': {'key': 'virtualMachineImageId', 'type': 'str'}, } def __init__( self, **kwargs ): super(ImageReference, self).__init__(**kwargs) self.publisher = kwargs['publisher'] self.offer = kwargs['offer'] self.sku = kwargs['sku'] self.version = kwargs.get('version', None) self.virtual_machine_image_id = kwargs.get('virtual_machine_image_id', None) class ImageSourceRegistry(msrest.serialization.Model): """Information about docker image for the job. All required parameters must be populated in order to send to Azure. :param server_url: URL for image repository. :type server_url: str :param image: Required. The name of the image in the image repository. :type image: str :param credentials: Credentials to access the private docker repository. :type credentials: ~batch_ai.models.PrivateRegistryCredentials """ _validation = { 'image': {'required': True}, } _attribute_map = { 'server_url': {'key': 'serverUrl', 'type': 'str'}, 'image': {'key': 'image', 'type': 'str'}, 'credentials': {'key': 'credentials', 'type': 'PrivateRegistryCredentials'}, } def __init__( self, **kwargs ): super(ImageSourceRegistry, self).__init__(**kwargs) self.server_url = kwargs.get('server_url', None) self.image = kwargs['image'] self.credentials = kwargs.get('credentials', None) class InputDirectory(msrest.serialization.Model): """Input directory for the job. All required parameters must be populated in order to send to Azure. :param id: Required. The ID for the input directory. The job can use AZ_BATCHAI\ *INPUT*\ :code:`<id>` environment variable to find the directory path, where :code:`<id>` is the value of id attribute. :type id: str :param path: Required. The path to the input directory. :type path: str """ _validation = { 'id': {'required': True}, 'path': {'required': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'path': {'key': 'path', 'type': 'str'}, } def __init__( self, **kwargs ): super(InputDirectory, self).__init__(**kwargs) self.id = kwargs['id'] self.path = kwargs['path'] class Job(ProxyResource): """Information about a Job. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: The ID of the resource. :vartype id: str :ivar name: The name of the resource. :vartype name: str :ivar type: The type of the resource. :vartype type: str :param scheduling_priority: Scheduling priority associated with the job. Possible values include: "low", "normal", "high". :type scheduling_priority: str or ~batch_ai.models.JobPriority :param cluster: Resource ID of the cluster associated with the job. :type cluster: ~batch_ai.models.ResourceId :param mount_volumes: Collection of mount volumes available to the job during execution. These volumes are mounted before the job execution and unmounted after the job completion. The volumes are mounted at location specified by $AZ_BATCHAI_JOB_MOUNT_ROOT environment variable. :type mount_volumes: ~batch_ai.models.MountVolumes :param node_count: The job will be gang scheduled on that many compute nodes. :type node_count: int :param container_settings: If the container was downloaded as part of cluster setup then the same container image will be used. If not provided, the job will run on the VM. :type container_settings: ~batch_ai.models.ContainerSettings :param tool_type: Possible values are: cntk, tensorflow, caffe, caffe2, chainer, pytorch, custom, custommpi, horovod. Possible values include: "cntk", "tensorflow", "caffe", "caffe2", "chainer", "horovod", "custommpi", "custom". :type tool_type: str or ~batch_ai.models.ToolType :param cntk_settings: CNTK (aka Microsoft Cognitive Toolkit) job settings. :type cntk_settings: ~batch_ai.models.CNTKsettings :param py_torch_settings: pyTorch job settings. :type py_torch_settings: ~batch_ai.models.PyTorchSettings :param tensor_flow_settings: TensorFlow job settings. :type tensor_flow_settings: ~batch_ai.models.TensorFlowSettings :param caffe_settings: Caffe job settings. :type caffe_settings: ~batch_ai.models.CaffeSettings :param caffe2_settings: Caffe2 job settings. :type caffe2_settings: ~batch_ai.models.Caffe2Settings :param chainer_settings: Chainer job settings. :type chainer_settings: ~batch_ai.models.ChainerSettings :param custom_toolkit_settings: Custom tool kit job settings. :type custom_toolkit_settings: ~batch_ai.models.CustomToolkitSettings :param custom_mpi_settings: Custom MPI job settings. :type custom_mpi_settings: ~batch_ai.models.CustomMpiSettings :param horovod_settings: Specifies the settings for Horovod job. :type horovod_settings: ~batch_ai.models.HorovodSettings :param job_preparation: The specified actions will run on all the nodes that are part of the job. :type job_preparation: ~batch_ai.models.JobPreparation :ivar job_output_directory_path_segment: A segment of job's output directories path created by Batch AI. Batch AI creates job's output directories under an unique path to avoid conflicts between jobs. This value contains a path segment generated by Batch AI to make the path unique and can be used to find the output directory on the node or mounted filesystem. :vartype job_output_directory_path_segment: str :param std_out_err_path_prefix: The path where the Batch AI service stores stdout, stderror and execution log of the job. :type std_out_err_path_prefix: str :param input_directories: A list of input directories for the job. :type input_directories: list[~batch_ai.models.InputDirectory] :param output_directories: A list of output directories for the job. :type output_directories: list[~batch_ai.models.OutputDirectory] :param environment_variables: A collection of user defined environment variables to be setup for the job. :type environment_variables: list[~batch_ai.models.EnvironmentVariable] :param secrets: A collection of user defined environment variables with secret values to be setup for the job. Server will never report values of these variables back. :type secrets: list[~batch_ai.models.EnvironmentVariableWithSecretValue] :param constraints: Constraints associated with the Job. :type constraints: ~batch_ai.models.JobPropertiesConstraints :ivar creation_time: The creation time of the job. :vartype creation_time: ~datetime.datetime :ivar provisioning_state: The provisioned state of the Batch AI job. Possible values include: "creating", "succeeded", "failed", "deleting". :vartype provisioning_state: str or ~batch_ai.models.ProvisioningState :ivar provisioning_state_transition_time: The time at which the job entered its current provisioning state. :vartype provisioning_state_transition_time: ~datetime.datetime :ivar execution_state: The current state of the job. Possible values are: queued - The job is queued and able to run. A job enters this state when it is created, or when it is awaiting a retry after a failed run. running - The job is running on a compute cluster. This includes job-level preparation such as downloading resource files or set up container specified on the job - it does not necessarily mean that the job command line has started executing. terminating - The job is terminated by the user, the terminate operation is in progress. succeeded - The job has completed running successfully and exited with exit code 0. failed - The job has finished unsuccessfully (failed with a non-zero exit code) and has exhausted its retry limit. A job is also marked as failed if an error occurred launching the job. Possible values include: "queued", "running", "terminating", "succeeded", "failed". :vartype execution_state: str or ~batch_ai.models.ExecutionState :ivar execution_state_transition_time: The time at which the job entered its current execution state. :vartype execution_state_transition_time: ~datetime.datetime :param execution_info: Information about the execution of a job. :type execution_info: ~batch_ai.models.JobPropertiesExecutionInfo """ _validation = { 'id': {'readonly': True}, 'name': {'readonly': True}, 'type': {'readonly': True}, 'job_output_directory_path_segment': {'readonly': True}, 'creation_time': {'readonly': True}, 'provisioning_state': {'readonly': True}, 'provisioning_state_transition_time': {'readonly': True}, 'execution_state': {'readonly': True}, 'execution_state_transition_time': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'scheduling_priority': {'key': 'properties.schedulingPriority', 'type': 'str'}, 'cluster': {'key': 'properties.cluster', 'type': 'ResourceId'}, 'mount_volumes': {'key': 'properties.mountVolumes', 'type': 'MountVolumes'}, 'node_count': {'key': 'properties.nodeCount', 'type': 'int'}, 'container_settings': {'key': 'properties.containerSettings', 'type': 'ContainerSettings'}, 'tool_type': {'key': 'properties.toolType', 'type': 'str'}, 'cntk_settings': {'key': 'properties.cntkSettings', 'type': 'CNTKsettings'}, 'py_torch_settings': {'key': 'properties.pyTorchSettings', 'type': 'PyTorchSettings'}, 'tensor_flow_settings': {'key': 'properties.tensorFlowSettings', 'type': 'TensorFlowSettings'}, 'caffe_settings': {'key': 'properties.caffeSettings', 'type': 'CaffeSettings'}, 'caffe2_settings': {'key': 'properties.caffe2Settings', 'type': 'Caffe2Settings'}, 'chainer_settings': {'key': 'properties.chainerSettings', 'type': 'ChainerSettings'}, 'custom_toolkit_settings': {'key': 'properties.customToolkitSettings', 'type': 'CustomToolkitSettings'}, 'custom_mpi_settings': {'key': 'properties.customMpiSettings', 'type': 'CustomMpiSettings'}, 'horovod_settings': {'key': 'properties.horovodSettings', 'type': 'HorovodSettings'}, 'job_preparation': {'key': 'properties.jobPreparation', 'type': 'JobPreparation'}, 'job_output_directory_path_segment': {'key': 'properties.jobOutputDirectoryPathSegment', 'type': 'str'}, 'std_out_err_path_prefix': {'key': 'properties.stdOutErrPathPrefix', 'type': 'str'}, 'input_directories': {'key': 'properties.inputDirectories', 'type': '[InputDirectory]'}, 'output_directories': {'key': 'properties.outputDirectories', 'type': '[OutputDirectory]'}, 'environment_variables': {'key': 'properties.environmentVariables', 'type': '[EnvironmentVariable]'}, 'secrets': {'key': 'properties.secrets', 'type': '[EnvironmentVariableWithSecretValue]'}, 'constraints': {'key': 'properties.constraints', 'type': 'JobPropertiesConstraints'}, 'creation_time': {'key': 'properties.creationTime', 'type': 'iso-8601'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'provisioning_state_transition_time': {'key': 'properties.provisioningStateTransitionTime', 'type': 'iso-8601'}, 'execution_state': {'key': 'properties.executionState', 'type': 'str'}, 'execution_state_transition_time': {'key': 'properties.executionStateTransitionTime', 'type': 'iso-8601'}, 'execution_info': {'key': 'properties.executionInfo', 'type': 'JobPropertiesExecutionInfo'}, } def __init__( self, **kwargs ): super(Job, self).__init__(**kwargs) self.scheduling_priority = kwargs.get('scheduling_priority', None) self.cluster = kwargs.get('cluster', None) self.mount_volumes = kwargs.get('mount_volumes', None) self.node_count = kwargs.get('node_count', None) self.container_settings = kwargs.get('container_settings', None) self.tool_type = kwargs.get('tool_type', None) self.cntk_settings = kwargs.get('cntk_settings', None) self.py_torch_settings = kwargs.get('py_torch_settings', None) self.tensor_flow_settings = kwargs.get('tensor_flow_settings', None) self.caffe_settings = kwargs.get('caffe_settings', None) self.caffe2_settings = kwargs.get('caffe2_settings', None) self.chainer_settings = kwargs.get('chainer_settings', None) self.custom_toolkit_settings = kwargs.get('custom_toolkit_settings', None) self.custom_mpi_settings = kwargs.get('custom_mpi_settings', None) self.horovod_settings = kwargs.get('horovod_settings', None) self.job_preparation = kwargs.get('job_preparation', None) self.job_output_directory_path_segment = None self.std_out_err_path_prefix = kwargs.get('std_out_err_path_prefix', None) self.input_directories = kwargs.get('input_directories', None) self.output_directories = kwargs.get('output_directories', None) self.environment_variables = kwargs.get('environment_variables', None) self.secrets = kwargs.get('secrets', None) self.constraints = kwargs.get('constraints', None) self.creation_time = None self.provisioning_state = None self.provisioning_state_transition_time = None self.execution_state = None self.execution_state_transition_time = None self.execution_info = kwargs.get('execution_info', None) class JobBasePropertiesConstraints(msrest.serialization.Model): """Constraints associated with the Job. :param max_wall_clock_time: Max time the job can run. Default value: 1 week. :type max_wall_clock_time: ~datetime.timedelta """ _attribute_map = { 'max_wall_clock_time': {'key': 'maxWallClockTime', 'type': 'duration'}, } def __init__( self, **kwargs ): super(JobBasePropertiesConstraints, self).__init__(**kwargs) self.max_wall_clock_time = kwargs.get('max_wall_clock_time', "7.00:00:00") class JobCreateParameters(msrest.serialization.Model): """Job creation parameters. :param scheduling_priority: Scheduling priority associated with the job. Possible values: low, normal, high. Possible values include: "low", "normal", "high". :type scheduling_priority: str or ~batch_ai.models.JobPriority :param cluster: Resource ID of the cluster on which this job will run. :type cluster: ~batch_ai.models.ResourceId :param mount_volumes: Information on mount volumes to be used by the job. These volumes will be mounted before the job execution and will be unmounted after the job completion. The volumes will be mounted at location specified by $AZ_BATCHAI_JOB_MOUNT_ROOT environment variable. :type mount_volumes: ~batch_ai.models.MountVolumes :param node_count: Number of compute nodes to run the job on. The job will be gang scheduled on that many compute nodes. :type node_count: int :param container_settings: Docker container settings for the job. If not provided, the job will run directly on the node. :type container_settings: ~batch_ai.models.ContainerSettings :param cntk_settings: Settings for CNTK (aka Microsoft Cognitive Toolkit) job. :type cntk_settings: ~batch_ai.models.CNTKsettings :param py_torch_settings: Settings for pyTorch job. :type py_torch_settings: ~batch_ai.models.PyTorchSettings :param tensor_flow_settings: Settings for Tensor Flow job. :type tensor_flow_settings: ~batch_ai.models.TensorFlowSettings :param caffe_settings: Settings for Caffe job. :type caffe_settings: ~batch_ai.models.CaffeSettings :param caffe2_settings: Settings for Caffe2 job. :type caffe2_settings: ~batch_ai.models.Caffe2Settings :param chainer_settings: Settings for Chainer job. :type chainer_settings: ~batch_ai.models.ChainerSettings :param custom_toolkit_settings: Settings for custom tool kit job. :type custom_toolkit_settings: ~batch_ai.models.CustomToolkitSettings :param custom_mpi_settings: Settings for custom MPI job. :type custom_mpi_settings: ~batch_ai.models.CustomMpiSettings :param horovod_settings: Settings for Horovod job. :type horovod_settings: ~batch_ai.models.HorovodSettings :param job_preparation: A command line to be executed on each node allocated for the job before tool kit is launched. :type job_preparation: ~batch_ai.models.JobPreparation :param std_out_err_path_prefix: The path where the Batch AI service will store stdout, stderror and execution log of the job. :type std_out_err_path_prefix: str :param input_directories: A list of input directories for the job. :type input_directories: list[~batch_ai.models.InputDirectory] :param output_directories: A list of output directories for the job. :type output_directories: list[~batch_ai.models.OutputDirectory] :param environment_variables: A list of user defined environment variables which will be setup for the job. :type environment_variables: list[~batch_ai.models.EnvironmentVariable] :param secrets: A list of user defined environment variables with secret values which will be setup for the job. Server will never report values of these variables back. :type secrets: list[~batch_ai.models.EnvironmentVariableWithSecretValue] :param constraints: Constraints associated with the Job. :type constraints: ~batch_ai.models.JobBasePropertiesConstraints """ _attribute_map = { 'scheduling_priority': {'key': 'properties.schedulingPriority', 'type': 'str'}, 'cluster': {'key': 'properties.cluster', 'type': 'ResourceId'}, 'mount_volumes': {'key': 'properties.mountVolumes', 'type': 'MountVolumes'}, 'node_count': {'key': 'properties.nodeCount', 'type': 'int'}, 'container_settings': {'key': 'properties.containerSettings', 'type': 'ContainerSettings'}, 'cntk_settings': {'key': 'properties.cntkSettings', 'type': 'CNTKsettings'}, 'py_torch_settings': {'key': 'properties.pyTorchSettings', 'type': 'PyTorchSettings'}, 'tensor_flow_settings': {'key': 'properties.tensorFlowSettings', 'type': 'TensorFlowSettings'}, 'caffe_settings': {'key': 'properties.caffeSettings', 'type': 'CaffeSettings'}, 'caffe2_settings': {'key': 'properties.caffe2Settings', 'type': 'Caffe2Settings'}, 'chainer_settings': {'key': 'properties.chainerSettings', 'type': 'ChainerSettings'}, 'custom_toolkit_settings': {'key': 'properties.customToolkitSettings', 'type': 'CustomToolkitSettings'}, 'custom_mpi_settings': {'key': 'properties.customMpiSettings', 'type': 'CustomMpiSettings'}, 'horovod_settings': {'key': 'properties.horovodSettings', 'type': 'HorovodSettings'}, 'job_preparation': {'key': 'properties.jobPreparation', 'type': 'JobPreparation'}, 'std_out_err_path_prefix': {'key': 'properties.stdOutErrPathPrefix', 'type': 'str'}, 'input_directories': {'key': 'properties.inputDirectories', 'type': '[InputDirectory]'}, 'output_directories': {'key': 'properties.outputDirectories', 'type': '[OutputDirectory]'}, 'environment_variables': {'key': 'properties.environmentVariables', 'type': '[EnvironmentVariable]'}, 'secrets': {'key': 'properties.secrets', 'type': '[EnvironmentVariableWithSecretValue]'}, 'constraints': {'key': 'properties.constraints', 'type': 'JobBasePropertiesConstraints'}, } def __init__( self, **kwargs ): super(JobCreateParameters, self).__init__(**kwargs) self.scheduling_priority = kwargs.get('scheduling_priority', None) self.cluster = kwargs.get('cluster', None) self.mount_volumes = kwargs.get('mount_volumes', None) self.node_count = kwargs.get('node_count', None) self.container_settings = kwargs.get('container_settings', None) self.cntk_settings = kwargs.get('cntk_settings', None) self.py_torch_settings = kwargs.get('py_torch_settings', None) self.tensor_flow_settings = kwargs.get('tensor_flow_settings', None) self.caffe_settings = kwargs.get('caffe_settings', None) self.caffe2_settings = kwargs.get('caffe2_settings', None) self.chainer_settings = kwargs.get('chainer_settings', None) self.custom_toolkit_settings = kwargs.get('custom_toolkit_settings', None) self.custom_mpi_settings = kwargs.get('custom_mpi_settings', None) self.horovod_settings = kwargs.get('horovod_settings', None) self.job_preparation = kwargs.get('job_preparation', None) self.std_out_err_path_prefix = kwargs.get('std_out_err_path_prefix', None) self.input_directories = kwargs.get('input_directories', None) self.output_directories = kwargs.get('output_directories', None) self.environment_variables = kwargs.get('environment_variables', None) self.secrets = kwargs.get('secrets', None) self.constraints = kwargs.get('constraints', None) class JobListResult(msrest.serialization.Model): """Values returned by the List operation. Variables are only populated by the server, and will be ignored when sending a request. :ivar value: The collection of jobs. :vartype value: list[~batch_ai.models.Job] :ivar next_link: The continuation token. :vartype next_link: str """ _validation = { 'value': {'readonly': True}, 'next_link': {'readonly': True}, } _attribute_map = { 'value': {'key': 'value', 'type': '[Job]'}, 'next_link': {'key': 'nextLink', 'type': 'str'}, } def __init__( self, **kwargs ): super(JobListResult, self).__init__(**kwargs) self.value = None self.next_link = None class JobPreparation(msrest.serialization.Model): """Job preparation settings. All required parameters must be populated in order to send to Azure. :param command_line: Required. The command line to execute. If containerSettings is specified on the job, this commandLine will be executed in the same container as job. Otherwise it will be executed on the node. :type command_line: str """ _validation = { 'command_line': {'required': True}, } _attribute_map = { 'command_line': {'key': 'commandLine', 'type': 'str'}, } def __init__( self, **kwargs ): super(JobPreparation, self).__init__(**kwargs) self.command_line = kwargs['command_line'] class JobPropertiesConstraints(msrest.serialization.Model): """Constraints associated with the Job. :param max_wall_clock_time: Max time the job can run. Default value: 1 week. :type max_wall_clock_time: ~datetime.timedelta """ _attribute_map = { 'max_wall_clock_time': {'key': 'maxWallClockTime', 'type': 'duration'}, } def __init__( self, **kwargs ): super(JobPropertiesConstraints, self).__init__(**kwargs) self.max_wall_clock_time = kwargs.get('max_wall_clock_time', "7.00:00:00") class JobPropertiesExecutionInfo(msrest.serialization.Model): """Information about the execution of a job. Variables are only populated by the server, and will be ignored when sending a request. :ivar start_time: The time at which the job started running. 'Running' corresponds to the running state. If the job has been restarted or retried, this is the most recent time at which the job started running. This property is present only for job that are in the running or completed state. :vartype start_time: ~datetime.datetime :ivar end_time: The time at which the job completed. This property is only returned if the job is in completed state. :vartype end_time: ~datetime.datetime :ivar exit_code: The exit code of the job. This property is only returned if the job is in completed state. :vartype exit_code: int :ivar errors: A collection of errors encountered by the service during job execution. :vartype errors: list[~batch_ai.models.BatchAIError] """ _validation = { 'start_time': {'readonly': True}, 'end_time': {'readonly': True}, 'exit_code': {'readonly': True}, 'errors': {'readonly': True}, } _attribute_map = { 'start_time': {'key': 'startTime', 'type': 'iso-8601'}, 'end_time': {'key': 'endTime', 'type': 'iso-8601'}, 'exit_code': {'key': 'exitCode', 'type': 'int'}, 'errors': {'key': 'errors', 'type': '[BatchAIError]'}, } def __init__( self, **kwargs ): super(JobPropertiesExecutionInfo, self).__init__(**kwargs) self.start_time = None self.end_time = None self.exit_code = None self.errors = None class JobsListByExperimentOptions(msrest.serialization.Model): """Parameter group. :param max_results: The maximum number of items to return in the response. A maximum of 1000 files can be returned. :type max_results: int """ _validation = { 'max_results': {'maximum': 1000, 'minimum': 1}, } _attribute_map = { 'max_results': {'key': 'maxResults', 'type': 'int'}, } def __init__( self, **kwargs ): super(JobsListByExperimentOptions, self).__init__(**kwargs) self.max_results = kwargs.get('max_results', 1000) class JobsListOutputFilesOptions(msrest.serialization.Model): """Parameter group. All required parameters must be populated in order to send to Azure. :param outputdirectoryid: Required. Id of the job output directory. This is the OutputDirectory-->id parameter that is given by the user during Create Job. :type outputdirectoryid: str :param directory: The path to the directory. :type directory: str :param linkexpiryinminutes: The number of minutes after which the download link will expire. :type linkexpiryinminutes: int :param max_results: The maximum number of items to return in the response. A maximum of 1000 files can be returned. :type max_results: int """ _validation = { 'outputdirectoryid': {'required': True}, 'linkexpiryinminutes': {'maximum': 600, 'minimum': 5}, 'max_results': {'maximum': 1000, 'minimum': 1}, } _attribute_map = { 'outputdirectoryid': {'key': 'outputdirectoryid', 'type': 'str'}, 'directory': {'key': 'directory', 'type': 'str'}, 'linkexpiryinminutes': {'key': 'linkexpiryinminutes', 'type': 'int'}, 'max_results': {'key': 'maxResults', 'type': 'int'}, } def __init__( self, **kwargs ): super(JobsListOutputFilesOptions, self).__init__(**kwargs) self.outputdirectoryid = kwargs['outputdirectoryid'] self.directory = kwargs.get('directory', ".") self.linkexpiryinminutes = kwargs.get('linkexpiryinminutes', 60) self.max_results = kwargs.get('max_results', 1000) class KeyVaultSecretReference(msrest.serialization.Model): """Key Vault Secret reference. All required parameters must be populated in order to send to Azure. :param source_vault: Required. Fully qualified resource identifier of the Key Vault. :type source_vault: ~batch_ai.models.ResourceId :param secret_url: Required. The URL referencing a secret in the Key Vault. :type secret_url: str """ _validation = { 'source_vault': {'required': True}, 'secret_url': {'required': True}, } _attribute_map = { 'source_vault': {'key': 'sourceVault', 'type': 'ResourceId'}, 'secret_url': {'key': 'secretUrl', 'type': 'str'}, } def __init__( self, **kwargs ): super(KeyVaultSecretReference, self).__init__(**kwargs) self.source_vault = kwargs['source_vault'] self.secret_url = kwargs['secret_url'] class ListUsagesResult(msrest.serialization.Model): """The List Usages operation response. Variables are only populated by the server, and will be ignored when sending a request. :ivar value: The list of compute resource usages. :vartype value: list[~batch_ai.models.Usage] :ivar next_link: The URI to fetch the next page of compute resource usage information. Call ListNext() with this to fetch the next page of compute resource usage information. :vartype next_link: str """ _validation = { 'value': {'readonly': True}, 'next_link': {'readonly': True}, } _attribute_map = { 'value': {'key': 'value', 'type': '[Usage]'}, 'next_link': {'key': 'nextLink', 'type': 'str'}, } def __init__( self, **kwargs ): super(ListUsagesResult, self).__init__(**kwargs) self.value = None self.next_link = None class ManualScaleSettings(msrest.serialization.Model): """Manual scale settings for the cluster. All required parameters must be populated in order to send to Azure. :param target_node_count: Required. The desired number of compute nodes in the Cluster. Default is 0. :type target_node_count: int :param node_deallocation_option: An action to be performed when the cluster size is decreasing. The default value is requeue. Possible values include: "requeue", "terminate", "waitforjobcompletion". Default value: "requeue". :type node_deallocation_option: str or ~batch_ai.models.DeallocationOption """ _validation = { 'target_node_count': {'required': True}, } _attribute_map = { 'target_node_count': {'key': 'targetNodeCount', 'type': 'int'}, 'node_deallocation_option': {'key': 'nodeDeallocationOption', 'type': 'str'}, } def __init__( self, **kwargs ): super(ManualScaleSettings, self).__init__(**kwargs) self.target_node_count = kwargs['target_node_count'] self.node_deallocation_option = kwargs.get('node_deallocation_option', "requeue") class MountSettings(msrest.serialization.Model): """File Server mount Information. :param mount_point: Path where the data disks are mounted on the File Server. :type mount_point: str :param file_server_public_ip: Public IP address of the File Server which can be used to SSH to the node from outside of the subnet. :type file_server_public_ip: str :param file_server_internal_ip: Internal IP address of the File Server which can be used to access the File Server from within the subnet. :type file_server_internal_ip: str """ _attribute_map = { 'mount_point': {'key': 'mountPoint', 'type': 'str'}, 'file_server_public_ip': {'key': 'fileServerPublicIP', 'type': 'str'}, 'file_server_internal_ip': {'key': 'fileServerInternalIP', 'type': 'str'}, } def __init__( self, **kwargs ): super(MountSettings, self).__init__(**kwargs) self.mount_point = kwargs.get('mount_point', None) self.file_server_public_ip = kwargs.get('file_server_public_ip', None) self.file_server_internal_ip = kwargs.get('file_server_internal_ip', None) class MountVolumes(msrest.serialization.Model): """Details of volumes to mount on the cluster. :param azure_file_shares: A collection of Azure File Shares that are to be mounted to the cluster nodes. :type azure_file_shares: list[~batch_ai.models.AzureFileShareReference] :param azure_blob_file_systems: A collection of Azure Blob Containers that are to be mounted to the cluster nodes. :type azure_blob_file_systems: list[~batch_ai.models.AzureBlobFileSystemReference] :param file_servers: A collection of Batch AI File Servers that are to be mounted to the cluster nodes. :type file_servers: list[~batch_ai.models.FileServerReference] :param unmanaged_file_systems: A collection of unmanaged file systems that are to be mounted to the cluster nodes. :type unmanaged_file_systems: list[~batch_ai.models.UnmanagedFileSystemReference] """ _attribute_map = { 'azure_file_shares': {'key': 'azureFileShares', 'type': '[AzureFileShareReference]'}, 'azure_blob_file_systems': {'key': 'azureBlobFileSystems', 'type': '[AzureBlobFileSystemReference]'}, 'file_servers': {'key': 'fileServers', 'type': '[FileServerReference]'}, 'unmanaged_file_systems': {'key': 'unmanagedFileSystems', 'type': '[UnmanagedFileSystemReference]'}, } def __init__( self, **kwargs ): super(MountVolumes, self).__init__(**kwargs) self.azure_file_shares = kwargs.get('azure_file_shares', None) self.azure_blob_file_systems = kwargs.get('azure_blob_file_systems', None) self.file_servers = kwargs.get('file_servers', None) self.unmanaged_file_systems = kwargs.get('unmanaged_file_systems', None) class NameValuePair(msrest.serialization.Model): """Name-value pair. :param name: The name in the name-value pair. :type name: str :param value: The value in the name-value pair. :type value: str """ _attribute_map = { 'name': {'key': 'name', 'type': 'str'}, 'value': {'key': 'value', 'type': 'str'}, } def __init__( self, **kwargs ): super(NameValuePair, self).__init__(**kwargs) self.name = kwargs.get('name', None) self.value = kwargs.get('value', None) class NodeSetup(msrest.serialization.Model): """Node setup settings. :param setup_task: Setup task to run on cluster nodes when nodes got created or rebooted. The setup task code needs to be idempotent. Generally the setup task is used to download static data that is required for all jobs that run on the cluster VMs and/or to download/install software. :type setup_task: ~batch_ai.models.SetupTask :param mount_volumes: Mount volumes to be available to setup task and all jobs executing on the cluster. The volumes will be mounted at location specified by $AZ_BATCHAI_MOUNT_ROOT environment variable. :type mount_volumes: ~batch_ai.models.MountVolumes :param performance_counters_settings: Settings for performance counters collecting and uploading. :type performance_counters_settings: ~batch_ai.models.PerformanceCountersSettings """ _attribute_map = { 'setup_task': {'key': 'setupTask', 'type': 'SetupTask'}, 'mount_volumes': {'key': 'mountVolumes', 'type': 'MountVolumes'}, 'performance_counters_settings': {'key': 'performanceCountersSettings', 'type': 'PerformanceCountersSettings'}, } def __init__( self, **kwargs ): super(NodeSetup, self).__init__(**kwargs) self.setup_task = kwargs.get('setup_task', None) self.mount_volumes = kwargs.get('mount_volumes', None) self.performance_counters_settings = kwargs.get('performance_counters_settings', None) class NodeStateCounts(msrest.serialization.Model): """Counts of various compute node states on the cluster. Variables are only populated by the server, and will be ignored when sending a request. :ivar idle_node_count: Number of compute nodes in idle state. :vartype idle_node_count: int :ivar running_node_count: Number of compute nodes which are running jobs. :vartype running_node_count: int :ivar preparing_node_count: Number of compute nodes which are being prepared. :vartype preparing_node_count: int :ivar unusable_node_count: Number of compute nodes which are in unusable state. :vartype unusable_node_count: int :ivar leaving_node_count: Number of compute nodes which are leaving the cluster. :vartype leaving_node_count: int """ _validation = { 'idle_node_count': {'readonly': True}, 'running_node_count': {'readonly': True}, 'preparing_node_count': {'readonly': True}, 'unusable_node_count': {'readonly': True}, 'leaving_node_count': {'readonly': True}, } _attribute_map = { 'idle_node_count': {'key': 'idleNodeCount', 'type': 'int'}, 'running_node_count': {'key': 'runningNodeCount', 'type': 'int'}, 'preparing_node_count': {'key': 'preparingNodeCount', 'type': 'int'}, 'unusable_node_count': {'key': 'unusableNodeCount', 'type': 'int'}, 'leaving_node_count': {'key': 'leavingNodeCount', 'type': 'int'}, } def __init__( self, **kwargs ): super(NodeStateCounts, self).__init__(**kwargs) self.idle_node_count = None self.running_node_count = None self.preparing_node_count = None self.unusable_node_count = None self.leaving_node_count = None class Operation(msrest.serialization.Model): """Details of a REST API operation. Variables are only populated by the server, and will be ignored when sending a request. :ivar name: This is of the format {provider}/{resource}/{operation}. :vartype name: str :param display: The object that describes the operation. :type display: ~batch_ai.models.OperationDisplay :ivar origin: The intended executor of the operation. :vartype origin: str :param properties: Any object. :type properties: any """ _validation = { 'name': {'readonly': True}, 'origin': {'readonly': True}, } _attribute_map = { 'name': {'key': 'name', 'type': 'str'}, 'display': {'key': 'display', 'type': 'OperationDisplay'}, 'origin': {'key': 'origin', 'type': 'str'}, 'properties': {'key': 'properties', 'type': 'object'}, } def __init__( self, **kwargs ): super(Operation, self).__init__(**kwargs) self.name = None self.display = kwargs.get('display', None) self.origin = None self.properties = kwargs.get('properties', None) class OperationDisplay(msrest.serialization.Model): """The object that describes the operation. Variables are only populated by the server, and will be ignored when sending a request. :ivar provider: Friendly name of the resource provider. :vartype provider: str :ivar operation: For example: read, write, delete, or listKeys/action. :vartype operation: str :ivar resource: The resource type on which the operation is performed. :vartype resource: str :ivar description: The friendly name of the operation. :vartype description: str """ _validation = { 'provider': {'readonly': True}, 'operation': {'readonly': True}, 'resource': {'readonly': True}, 'description': {'readonly': True}, } _attribute_map = { 'provider': {'key': 'provider', 'type': 'str'}, 'operation': {'key': 'operation', 'type': 'str'}, 'resource': {'key': 'resource', 'type': 'str'}, 'description': {'key': 'description', 'type': 'str'}, } def __init__( self, **kwargs ): super(OperationDisplay, self).__init__(**kwargs) self.provider = None self.operation = None self.resource = None self.description = None class OperationListResult(msrest.serialization.Model): """Contains the list of all operations supported by BatchAI resource provider. Variables are only populated by the server, and will be ignored when sending a request. :ivar value: The list of operations supported by the resource provider. :vartype value: list[~batch_ai.models.Operation] :ivar next_link: The URL to get the next set of operation list results if there are any. :vartype next_link: str """ _validation = { 'value': {'readonly': True}, 'next_link': {'readonly': True}, } _attribute_map = { 'value': {'key': 'value', 'type': '[Operation]'}, 'next_link': {'key': 'nextLink', 'type': 'str'}, } def __init__( self, **kwargs ): super(OperationListResult, self).__init__(**kwargs) self.value = None self.next_link = None class OutputDirectory(msrest.serialization.Model): """Output directory for the job. All required parameters must be populated in order to send to Azure. :param id: Required. The ID of the output directory. The job can use AZ_BATCHAI\ *OUTPUT*\ :code:`<id>` environment variable to find the directory path, where :code:`<id>` is the value of id attribute. :type id: str :param path_prefix: Required. The prefix path where the output directory will be created. Note, this is an absolute path to prefix. E.g. $AZ_BATCHAI_MOUNT_ROOT/MyNFS/MyLogs. The full path to the output directory by combining pathPrefix, jobOutputDirectoryPathSegment (reported by get job) and pathSuffix. :type path_prefix: str :param path_suffix: The suffix path where the output directory will be created. E.g. models. You can find the full path to the output directory by combining pathPrefix, jobOutputDirectoryPathSegment (reported by get job) and pathSuffix. :type path_suffix: str """ _validation = { 'id': {'required': True}, 'path_prefix': {'required': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'path_prefix': {'key': 'pathPrefix', 'type': 'str'}, 'path_suffix': {'key': 'pathSuffix', 'type': 'str'}, } def __init__( self, **kwargs ): super(OutputDirectory, self).__init__(**kwargs) self.id = kwargs['id'] self.path_prefix = kwargs['path_prefix'] self.path_suffix = kwargs.get('path_suffix', None) class PerformanceCountersSettings(msrest.serialization.Model): """Performance counters reporting settings. All required parameters must be populated in order to send to Azure. :param app_insights_reference: Required. Azure Application Insights information for performance counters reporting. If provided, Batch AI will upload node performance counters to the corresponding Azure Application Insights account. :type app_insights_reference: ~batch_ai.models.AppInsightsReference """ _validation = { 'app_insights_reference': {'required': True}, } _attribute_map = { 'app_insights_reference': {'key': 'appInsightsReference', 'type': 'AppInsightsReference'}, } def __init__( self, **kwargs ): super(PerformanceCountersSettings, self).__init__(**kwargs) self.app_insights_reference = kwargs['app_insights_reference'] class PrivateRegistryCredentials(msrest.serialization.Model): """Credentials to access a container image in a private repository. All required parameters must be populated in order to send to Azure. :param username: Required. User name to login to the repository. :type username: str :param password: User password to login to the docker repository. One of password or passwordSecretReference must be specified. :type password: str :param password_secret_reference: KeyVault Secret storing the password. Users can store their secrets in Azure KeyVault and pass it to the Batch AI service to integrate with KeyVault. One of password or passwordSecretReference must be specified. :type password_secret_reference: ~batch_ai.models.KeyVaultSecretReference """ _validation = { 'username': {'required': True}, } _attribute_map = { 'username': {'key': 'username', 'type': 'str'}, 'password': {'key': 'password', 'type': 'str'}, 'password_secret_reference': {'key': 'passwordSecretReference', 'type': 'KeyVaultSecretReference'}, } def __init__( self, **kwargs ): super(PrivateRegistryCredentials, self).__init__(**kwargs) self.username = kwargs['username'] self.password = kwargs.get('password', None) self.password_secret_reference = kwargs.get('password_secret_reference', None) class PyTorchSettings(msrest.serialization.Model): """pyTorch job settings. All required parameters must be populated in order to send to Azure. :param python_script_file_path: Required. The python script to execute. :type python_script_file_path: str :param python_interpreter_path: The path to the Python interpreter. :type python_interpreter_path: str :param command_line_args: Command line arguments that need to be passed to the python script. :type command_line_args: str :param process_count: Number of processes to launch for the job execution. The default value for this property is equal to nodeCount property. :type process_count: int :param communication_backend: Type of the communication backend for distributed jobs. Valid values are 'TCP', 'Gloo' or 'MPI'. Not required for non-distributed jobs. :type communication_backend: str """ _validation = { 'python_script_file_path': {'required': True}, } _attribute_map = { 'python_script_file_path': {'key': 'pythonScriptFilePath', 'type': 'str'}, 'python_interpreter_path': {'key': 'pythonInterpreterPath', 'type': 'str'}, 'command_line_args': {'key': 'commandLineArgs', 'type': 'str'}, 'process_count': {'key': 'processCount', 'type': 'int'}, 'communication_backend': {'key': 'communicationBackend', 'type': 'str'}, } def __init__( self, **kwargs ): super(PyTorchSettings, self).__init__(**kwargs) self.python_script_file_path = kwargs['python_script_file_path'] self.python_interpreter_path = kwargs.get('python_interpreter_path', None) self.command_line_args = kwargs.get('command_line_args', None) self.process_count = kwargs.get('process_count', None) self.communication_backend = kwargs.get('communication_backend', None) class RemoteLoginInformation(msrest.serialization.Model): """Login details to SSH to a compute node in cluster. Variables are only populated by the server, and will be ignored when sending a request. :ivar node_id: ID of the compute node. :vartype node_id: str :ivar ip_address: Public IP address of the compute node. :vartype ip_address: str :ivar port: SSH port number of the node. :vartype port: int """ _validation = { 'node_id': {'readonly': True}, 'ip_address': {'readonly': True}, 'port': {'readonly': True}, } _attribute_map = { 'node_id': {'key': 'nodeId', 'type': 'str'}, 'ip_address': {'key': 'ipAddress', 'type': 'str'}, 'port': {'key': 'port', 'type': 'int'}, } def __init__( self, **kwargs ): super(RemoteLoginInformation, self).__init__(**kwargs) self.node_id = None self.ip_address = None self.port = None class RemoteLoginInformationListResult(msrest.serialization.Model): """Values returned by the List operation. Variables are only populated by the server, and will be ignored when sending a request. :ivar value: The collection of returned remote login details. :vartype value: list[~batch_ai.models.RemoteLoginInformation] :ivar next_link: The continuation token. :vartype next_link: str """ _validation = { 'value': {'readonly': True}, 'next_link': {'readonly': True}, } _attribute_map = { 'value': {'key': 'value', 'type': '[RemoteLoginInformation]'}, 'next_link': {'key': 'nextLink', 'type': 'str'}, } def __init__( self, **kwargs ): super(RemoteLoginInformationListResult, self).__init__(**kwargs) self.value = None self.next_link = None class Resource(msrest.serialization.Model): """A definition of an Azure resource. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: The ID of the resource. :vartype id: str :ivar name: The name of the resource. :vartype name: str :ivar type: The type of the resource. :vartype type: str :ivar location: The location of the resource. :vartype location: str :ivar tags: A set of tags. The tags of the resource. :vartype tags: dict[str, str] """ _validation = { 'id': {'readonly': True}, 'name': {'readonly': True}, 'type': {'readonly': True}, 'location': {'readonly': True}, 'tags': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'location': {'key': 'location', 'type': 'str'}, 'tags': {'key': 'tags', 'type': '{str}'}, } def __init__( self, **kwargs ): super(Resource, self).__init__(**kwargs) self.id = None self.name = None self.type = None self.location = None self.tags = None class ResourceId(msrest.serialization.Model): """Represents a resource ID. For example, for a subnet, it is the resource URL for the subnet. All required parameters must be populated in order to send to Azure. :param id: Required. The ID of the resource. :type id: str """ _validation = { 'id': {'required': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, } def __init__( self, **kwargs ): super(ResourceId, self).__init__(**kwargs) self.id = kwargs['id'] class ScaleSettings(msrest.serialization.Model): """At least one of manual or autoScale settings must be specified. Only one of manual or autoScale settings can be specified. If autoScale settings are specified, the system automatically scales the cluster up and down (within the supplied limits) based on the pending jobs on the cluster. :param manual: Manual scale settings for the cluster. :type manual: ~batch_ai.models.ManualScaleSettings :param auto_scale: Auto-scale settings for the cluster. :type auto_scale: ~batch_ai.models.AutoScaleSettings """ _attribute_map = { 'manual': {'key': 'manual', 'type': 'ManualScaleSettings'}, 'auto_scale': {'key': 'autoScale', 'type': 'AutoScaleSettings'}, } def __init__( self, **kwargs ): super(ScaleSettings, self).__init__(**kwargs) self.manual = kwargs.get('manual', None) self.auto_scale = kwargs.get('auto_scale', None) class SetupTask(msrest.serialization.Model): """Specifies a setup task which can be used to customize the compute nodes of the cluster. Variables are only populated by the server, and will be ignored when sending a request. All required parameters must be populated in order to send to Azure. :param command_line: Required. The command line to be executed on each cluster's node after it being allocated or rebooted. The command is executed in a bash subshell as a root. :type command_line: str :param environment_variables: A collection of user defined environment variables to be set for setup task. :type environment_variables: list[~batch_ai.models.EnvironmentVariable] :param secrets: A collection of user defined environment variables with secret values to be set for the setup task. Server will never report values of these variables back. :type secrets: list[~batch_ai.models.EnvironmentVariableWithSecretValue] :param std_out_err_path_prefix: Required. The prefix of a path where the Batch AI service will upload the stdout, stderr and execution log of the setup task. :type std_out_err_path_prefix: str :ivar std_out_err_path_suffix: A path segment appended by Batch AI to stdOutErrPathPrefix to form a path where stdout, stderr and execution log of the setup task will be uploaded. Batch AI creates the setup task output directories under an unique path to avoid conflicts between different clusters. The full path can be obtained by concatenation of stdOutErrPathPrefix and stdOutErrPathSuffix. :vartype std_out_err_path_suffix: str """ _validation = { 'command_line': {'required': True}, 'std_out_err_path_prefix': {'required': True}, 'std_out_err_path_suffix': {'readonly': True}, } _attribute_map = { 'command_line': {'key': 'commandLine', 'type': 'str'}, 'environment_variables': {'key': 'environmentVariables', 'type': '[EnvironmentVariable]'}, 'secrets': {'key': 'secrets', 'type': '[EnvironmentVariableWithSecretValue]'}, 'std_out_err_path_prefix': {'key': 'stdOutErrPathPrefix', 'type': 'str'}, 'std_out_err_path_suffix': {'key': 'stdOutErrPathSuffix', 'type': 'str'}, } def __init__( self, **kwargs ): super(SetupTask, self).__init__(**kwargs) self.command_line = kwargs['command_line'] self.environment_variables = kwargs.get('environment_variables', None) self.secrets = kwargs.get('secrets', None) self.std_out_err_path_prefix = kwargs['std_out_err_path_prefix'] self.std_out_err_path_suffix = None class SshConfiguration(msrest.serialization.Model): """SSH configuration. All required parameters must be populated in order to send to Azure. :param public_ips_to_allow: List of source IP ranges to allow SSH connection from. The default value is '*' (all source IPs are allowed). Maximum number of IP ranges that can be specified is 400. :type public_ips_to_allow: list[str] :param user_account_settings: Required. Settings for administrator user account to be created on a node. The account can be used to establish SSH connection to the node. :type user_account_settings: ~batch_ai.models.UserAccountSettings """ _validation = { 'user_account_settings': {'required': True}, } _attribute_map = { 'public_ips_to_allow': {'key': 'publicIPsToAllow', 'type': '[str]'}, 'user_account_settings': {'key': 'userAccountSettings', 'type': 'UserAccountSettings'}, } def __init__( self, **kwargs ): super(SshConfiguration, self).__init__(**kwargs) self.public_ips_to_allow = kwargs.get('public_ips_to_allow', None) self.user_account_settings = kwargs['user_account_settings'] class TensorFlowSettings(msrest.serialization.Model): """TensorFlow job settings. All required parameters must be populated in order to send to Azure. :param python_script_file_path: Required. The python script to execute. :type python_script_file_path: str :param python_interpreter_path: The path to the Python interpreter. :type python_interpreter_path: str :param master_command_line_args: Command line arguments that need to be passed to the python script for the master task. :type master_command_line_args: str :param worker_command_line_args: Command line arguments that need to be passed to the python script for the worker task. Optional for single process jobs. :type worker_command_line_args: str :param parameter_server_command_line_args: Command line arguments that need to be passed to the python script for the parameter server. Optional for single process jobs. :type parameter_server_command_line_args: str :param worker_count: The number of worker tasks. If specified, the value must be less than or equal to (nodeCount * numberOfGPUs per VM). If not specified, the default value is equal to nodeCount. This property can be specified only for distributed TensorFlow training. :type worker_count: int :param parameter_server_count: The number of parameter server tasks. If specified, the value must be less than or equal to nodeCount. If not specified, the default value is equal to 1 for distributed TensorFlow training. This property can be specified only for distributed TensorFlow training. :type parameter_server_count: int """ _validation = { 'python_script_file_path': {'required': True}, } _attribute_map = { 'python_script_file_path': {'key': 'pythonScriptFilePath', 'type': 'str'}, 'python_interpreter_path': {'key': 'pythonInterpreterPath', 'type': 'str'}, 'master_command_line_args': {'key': 'masterCommandLineArgs', 'type': 'str'}, 'worker_command_line_args': {'key': 'workerCommandLineArgs', 'type': 'str'}, 'parameter_server_command_line_args': {'key': 'parameterServerCommandLineArgs', 'type': 'str'}, 'worker_count': {'key': 'workerCount', 'type': 'int'}, 'parameter_server_count': {'key': 'parameterServerCount', 'type': 'int'}, } def __init__( self, **kwargs ): super(TensorFlowSettings, self).__init__(**kwargs) self.python_script_file_path = kwargs['python_script_file_path'] self.python_interpreter_path = kwargs.get('python_interpreter_path', None) self.master_command_line_args = kwargs.get('master_command_line_args', None) self.worker_command_line_args = kwargs.get('worker_command_line_args', None) self.parameter_server_command_line_args = kwargs.get('parameter_server_command_line_args', None) self.worker_count = kwargs.get('worker_count', None) self.parameter_server_count = kwargs.get('parameter_server_count', None) class UnmanagedFileSystemReference(msrest.serialization.Model): """Unmanaged file system mounting configuration. All required parameters must be populated in order to send to Azure. :param mount_command: Required. Mount command line. Note, Batch AI will append mount path to the command on its own. :type mount_command: str :param relative_mount_path: Required. The relative path on the compute node where the unmanaged file system will be mounted. Note that all cluster level unmanaged file systems will be mounted under $AZ_BATCHAI_MOUNT_ROOT location and all job level unmanaged file systems will be mounted under $AZ_BATCHAI_JOB_MOUNT_ROOT. :type relative_mount_path: str """ _validation = { 'mount_command': {'required': True}, 'relative_mount_path': {'required': True}, } _attribute_map = { 'mount_command': {'key': 'mountCommand', 'type': 'str'}, 'relative_mount_path': {'key': 'relativeMountPath', 'type': 'str'}, } def __init__( self, **kwargs ): super(UnmanagedFileSystemReference, self).__init__(**kwargs) self.mount_command = kwargs['mount_command'] self.relative_mount_path = kwargs['relative_mount_path'] class Usage(msrest.serialization.Model): """Describes Batch AI Resource Usage. Variables are only populated by the server, and will be ignored when sending a request. :ivar unit: An enum describing the unit of usage measurement. Possible values include: "Count". :vartype unit: str or ~batch_ai.models.UsageUnit :ivar current_value: The current usage of the resource. :vartype current_value: int :ivar limit: The maximum permitted usage of the resource. :vartype limit: long :ivar name: The name of the type of usage. :vartype name: ~batch_ai.models.UsageName """ _validation = { 'unit': {'readonly': True}, 'current_value': {'readonly': True}, 'limit': {'readonly': True}, 'name': {'readonly': True}, } _attribute_map = { 'unit': {'key': 'unit', 'type': 'str'}, 'current_value': {'key': 'currentValue', 'type': 'int'}, 'limit': {'key': 'limit', 'type': 'long'}, 'name': {'key': 'name', 'type': 'UsageName'}, } def __init__( self, **kwargs ): super(Usage, self).__init__(**kwargs) self.unit = None self.current_value = None self.limit = None self.name = None class UsageName(msrest.serialization.Model): """The Usage Names. Variables are only populated by the server, and will be ignored when sending a request. :ivar value: The name of the resource. :vartype value: str :ivar localized_value: The localized name of the resource. :vartype localized_value: str """ _validation = { 'value': {'readonly': True}, 'localized_value': {'readonly': True}, } _attribute_map = { 'value': {'key': 'value', 'type': 'str'}, 'localized_value': {'key': 'localizedValue', 'type': 'str'}, } def __init__( self, **kwargs ): super(UsageName, self).__init__(**kwargs) self.value = None self.localized_value = None class UserAccountSettings(msrest.serialization.Model): """Settings for user account that gets created on each on the nodes of a cluster. All required parameters must be populated in order to send to Azure. :param admin_user_name: Required. Name of the administrator user account which can be used to SSH to nodes. :type admin_user_name: str :param admin_user_ssh_public_key: SSH public key of the administrator user account. :type admin_user_ssh_public_key: str :param admin_user_password: Password of the administrator user account. :type admin_user_password: str """ _validation = { 'admin_user_name': {'required': True}, } _attribute_map = { 'admin_user_name': {'key': 'adminUserName', 'type': 'str'}, 'admin_user_ssh_public_key': {'key': 'adminUserSshPublicKey', 'type': 'str'}, 'admin_user_password': {'key': 'adminUserPassword', 'type': 'str'}, } def __init__( self, **kwargs ): super(UserAccountSettings, self).__init__(**kwargs) self.admin_user_name = kwargs['admin_user_name'] self.admin_user_ssh_public_key = kwargs.get('admin_user_ssh_public_key', None) self.admin_user_password = kwargs.get('admin_user_password', None) class VirtualMachineConfiguration(msrest.serialization.Model): """VM configuration. :param image_reference: OS image reference for cluster nodes. :type image_reference: ~batch_ai.models.ImageReference """ _attribute_map = { 'image_reference': {'key': 'imageReference', 'type': 'ImageReference'}, } def __init__( self, **kwargs ): super(VirtualMachineConfiguration, self).__init__(**kwargs) self.image_reference = kwargs.get('image_reference', None) class Workspace(Resource): """Batch AI Workspace information. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: The ID of the resource. :vartype id: str :ivar name: The name of the resource. :vartype name: str :ivar type: The type of the resource. :vartype type: str :ivar location: The location of the resource. :vartype location: str :ivar tags: A set of tags. The tags of the resource. :vartype tags: dict[str, str] :ivar creation_time: Time when the Workspace was created. :vartype creation_time: ~datetime.datetime :ivar provisioning_state: The provisioned state of the Workspace. Possible values include: "creating", "succeeded", "failed", "deleting". :vartype provisioning_state: str or ~batch_ai.models.ProvisioningState :ivar provisioning_state_transition_time: The time at which the workspace entered its current provisioning state. :vartype provisioning_state_transition_time: ~datetime.datetime """ _validation = { 'id': {'readonly': True}, 'name': {'readonly': True}, 'type': {'readonly': True}, 'location': {'readonly': True}, 'tags': {'readonly': True}, 'creation_time': {'readonly': True}, 'provisioning_state': {'readonly': True}, 'provisioning_state_transition_time': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'location': {'key': 'location', 'type': 'str'}, 'tags': {'key': 'tags', 'type': '{str}'}, 'creation_time': {'key': 'properties.creationTime', 'type': 'iso-8601'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'provisioning_state_transition_time': {'key': 'properties.provisioningStateTransitionTime', 'type': 'iso-8601'}, } def __init__( self, **kwargs ): super(Workspace, self).__init__(**kwargs) self.creation_time = None self.provisioning_state = None self.provisioning_state_transition_time = None class WorkspaceCreateParameters(msrest.serialization.Model): """Workspace creation parameters. All required parameters must be populated in order to send to Azure. :param location: Required. The region in which to create the Workspace. :type location: str :param tags: A set of tags. The user specified tags associated with the Workspace. :type tags: dict[str, str] """ _validation = { 'location': {'required': True}, } _attribute_map = { 'location': {'key': 'location', 'type': 'str'}, 'tags': {'key': 'tags', 'type': '{str}'}, } def __init__( self, **kwargs ): super(WorkspaceCreateParameters, self).__init__(**kwargs) self.location = kwargs['location'] self.tags = kwargs.get('tags', None) class WorkspaceListResult(msrest.serialization.Model): """Values returned by the List operation. Variables are only populated by the server, and will be ignored when sending a request. :ivar value: The collection of workspaces. :vartype value: list[~batch_ai.models.Workspace] :ivar next_link: The continuation token. :vartype next_link: str """ _validation = { 'value': {'readonly': True}, 'next_link': {'readonly': True}, } _attribute_map = { 'value': {'key': 'value', 'type': '[Workspace]'}, 'next_link': {'key': 'nextLink', 'type': 'str'}, } def __init__( self, **kwargs ): super(WorkspaceListResult, self).__init__(**kwargs) self.value = None self.next_link = None class WorkspacesListByResourceGroupOptions(msrest.serialization.Model): """Parameter group. :param max_results: The maximum number of items to return in the response. A maximum of 1000 files can be returned. :type max_results: int """ _validation = { 'max_results': {'maximum': 1000, 'minimum': 1}, } _attribute_map = { 'max_results': {'key': 'maxResults', 'type': 'int'}, } def __init__( self, **kwargs ): super(WorkspacesListByResourceGroupOptions, self).__init__(**kwargs) self.max_results = kwargs.get('max_results', 1000) class WorkspacesListOptions(msrest.serialization.Model): """Parameter group. :param max_results: The maximum number of items to return in the response. A maximum of 1000 files can be returned. :type max_results: int """ _validation = { 'max_results': {'maximum': 1000, 'minimum': 1}, } _attribute_map = { 'max_results': {'key': 'maxResults', 'type': 'int'}, } def __init__( self, **kwargs ): super(WorkspacesListOptions, self).__init__(**kwargs) self.max_results = kwargs.get('max_results', 1000) class WorkspaceUpdateParameters(msrest.serialization.Model): """Workspace update parameters. :param tags: A set of tags. The user specified tags associated with the Workspace. :type tags: dict[str, str] """ _attribute_map = { 'tags': {'key': 'tags', 'type': '{str}'}, } def __init__( self, **kwargs ): super(WorkspaceUpdateParameters, self).__init__(**kwargs) self.tags = kwargs.get('tags', None)
azure-mgmt-batchai
/azure-mgmt-batchai-7.0.0b1.zip/azure-mgmt-batchai-7.0.0b1/azure/mgmt/batchai/models/_models.py
_models.py
import msrest.serialization class AppInsightsReference(msrest.serialization.Model): """Azure Application Insights information for performance counters reporting. All required parameters must be populated in order to send to Azure. :param component: Required. Azure Application Insights component resource ID. :type component: ~batch_ai.models.ResourceId :param instrumentation_key: Value of the Azure Application Insights instrumentation key. :type instrumentation_key: str :param instrumentation_key_secret_reference: KeyVault Store and Secret which contains Azure Application Insights instrumentation key. One of instrumentationKey or instrumentationKeySecretReference must be specified. :type instrumentation_key_secret_reference: ~batch_ai.models.KeyVaultSecretReference """ _validation = { 'component': {'required': True}, } _attribute_map = { 'component': {'key': 'component', 'type': 'ResourceId'}, 'instrumentation_key': {'key': 'instrumentationKey', 'type': 'str'}, 'instrumentation_key_secret_reference': {'key': 'instrumentationKeySecretReference', 'type': 'KeyVaultSecretReference'}, } def __init__( self, **kwargs ): super(AppInsightsReference, self).__init__(**kwargs) self.component = kwargs['component'] self.instrumentation_key = kwargs.get('instrumentation_key', None) self.instrumentation_key_secret_reference = kwargs.get('instrumentation_key_secret_reference', None) class AutoScaleSettings(msrest.serialization.Model): """Auto-scale settings for the cluster. The system automatically scales the cluster up and down (within minimumNodeCount and maximumNodeCount) based on the number of queued and running jobs assigned to the cluster. All required parameters must be populated in order to send to Azure. :param minimum_node_count: Required. The minimum number of compute nodes the Batch AI service will try to allocate for the cluster. Note, the actual number of nodes can be less than the specified value if the subscription has not enough quota to fulfill the request. :type minimum_node_count: int :param maximum_node_count: Required. The maximum number of compute nodes the cluster can have. :type maximum_node_count: int :param initial_node_count: The number of compute nodes to allocate on cluster creation. Note that this value is used only during cluster creation. Default: 0. :type initial_node_count: int """ _validation = { 'minimum_node_count': {'required': True}, 'maximum_node_count': {'required': True}, } _attribute_map = { 'minimum_node_count': {'key': 'minimumNodeCount', 'type': 'int'}, 'maximum_node_count': {'key': 'maximumNodeCount', 'type': 'int'}, 'initial_node_count': {'key': 'initialNodeCount', 'type': 'int'}, } def __init__( self, **kwargs ): super(AutoScaleSettings, self).__init__(**kwargs) self.minimum_node_count = kwargs['minimum_node_count'] self.maximum_node_count = kwargs['maximum_node_count'] self.initial_node_count = kwargs.get('initial_node_count', 0) class AzureBlobFileSystemReference(msrest.serialization.Model): """Azure Blob Storage Container mounting configuration. All required parameters must be populated in order to send to Azure. :param account_name: Required. Name of the Azure storage account. :type account_name: str :param container_name: Required. Name of the Azure Blob Storage container to mount on the cluster. :type container_name: str :param credentials: Required. Information about the Azure storage credentials. :type credentials: ~batch_ai.models.AzureStorageCredentialsInfo :param relative_mount_path: Required. The relative path on the compute node where the Azure File container will be mounted. Note that all cluster level containers will be mounted under $AZ_BATCHAI_MOUNT_ROOT location and all job level containers will be mounted under $AZ_BATCHAI_JOB_MOUNT_ROOT. :type relative_mount_path: str :param mount_options: Mount options for mounting blobfuse file system. :type mount_options: str """ _validation = { 'account_name': {'required': True}, 'container_name': {'required': True}, 'credentials': {'required': True}, 'relative_mount_path': {'required': True}, } _attribute_map = { 'account_name': {'key': 'accountName', 'type': 'str'}, 'container_name': {'key': 'containerName', 'type': 'str'}, 'credentials': {'key': 'credentials', 'type': 'AzureStorageCredentialsInfo'}, 'relative_mount_path': {'key': 'relativeMountPath', 'type': 'str'}, 'mount_options': {'key': 'mountOptions', 'type': 'str'}, } def __init__( self, **kwargs ): super(AzureBlobFileSystemReference, self).__init__(**kwargs) self.account_name = kwargs['account_name'] self.container_name = kwargs['container_name'] self.credentials = kwargs['credentials'] self.relative_mount_path = kwargs['relative_mount_path'] self.mount_options = kwargs.get('mount_options', None) class AzureFileShareReference(msrest.serialization.Model): """Azure File Share mounting configuration. All required parameters must be populated in order to send to Azure. :param account_name: Required. Name of the Azure storage account. :type account_name: str :param azure_file_url: Required. URL to access the Azure File. :type azure_file_url: str :param credentials: Required. Information about the Azure storage credentials. :type credentials: ~batch_ai.models.AzureStorageCredentialsInfo :param relative_mount_path: Required. The relative path on the compute node where the Azure File share will be mounted. Note that all cluster level file shares will be mounted under $AZ_BATCHAI_MOUNT_ROOT location and all job level file shares will be mounted under $AZ_BATCHAI_JOB_MOUNT_ROOT. :type relative_mount_path: str :param file_mode: File mode for files on the mounted file share. Default value: 0777. :type file_mode: str :param directory_mode: File mode for directories on the mounted file share. Default value: 0777. :type directory_mode: str """ _validation = { 'account_name': {'required': True}, 'azure_file_url': {'required': True}, 'credentials': {'required': True}, 'relative_mount_path': {'required': True}, } _attribute_map = { 'account_name': {'key': 'accountName', 'type': 'str'}, 'azure_file_url': {'key': 'azureFileUrl', 'type': 'str'}, 'credentials': {'key': 'credentials', 'type': 'AzureStorageCredentialsInfo'}, 'relative_mount_path': {'key': 'relativeMountPath', 'type': 'str'}, 'file_mode': {'key': 'fileMode', 'type': 'str'}, 'directory_mode': {'key': 'directoryMode', 'type': 'str'}, } def __init__( self, **kwargs ): super(AzureFileShareReference, self).__init__(**kwargs) self.account_name = kwargs['account_name'] self.azure_file_url = kwargs['azure_file_url'] self.credentials = kwargs['credentials'] self.relative_mount_path = kwargs['relative_mount_path'] self.file_mode = kwargs.get('file_mode', "0777") self.directory_mode = kwargs.get('directory_mode', "0777") class AzureStorageCredentialsInfo(msrest.serialization.Model): """Azure storage account credentials. :param account_key: Storage account key. One of accountKey or accountKeySecretReference must be specified. :type account_key: str :param account_key_secret_reference: Information about KeyVault secret storing the storage account key. One of accountKey or accountKeySecretReference must be specified. :type account_key_secret_reference: ~batch_ai.models.KeyVaultSecretReference """ _attribute_map = { 'account_key': {'key': 'accountKey', 'type': 'str'}, 'account_key_secret_reference': {'key': 'accountKeySecretReference', 'type': 'KeyVaultSecretReference'}, } def __init__( self, **kwargs ): super(AzureStorageCredentialsInfo, self).__init__(**kwargs) self.account_key = kwargs.get('account_key', None) self.account_key_secret_reference = kwargs.get('account_key_secret_reference', None) class BatchAIError(msrest.serialization.Model): """An error response from the Batch AI service. Variables are only populated by the server, and will be ignored when sending a request. :ivar code: An identifier of the error. Codes are invariant and are intended to be consumed programmatically. :vartype code: str :ivar message: A message describing the error, intended to be suitable for display in a user interface. :vartype message: str :ivar details: A list of additional details about the error. :vartype details: list[~batch_ai.models.NameValuePair] """ _validation = { 'code': {'readonly': True}, 'message': {'readonly': True}, 'details': {'readonly': True}, } _attribute_map = { 'code': {'key': 'code', 'type': 'str'}, 'message': {'key': 'message', 'type': 'str'}, 'details': {'key': 'details', 'type': '[NameValuePair]'}, } def __init__( self, **kwargs ): super(BatchAIError, self).__init__(**kwargs) self.code = None self.message = None self.details = None class Caffe2Settings(msrest.serialization.Model): """Caffe2 job settings. All required parameters must be populated in order to send to Azure. :param python_script_file_path: Required. The python script to execute. :type python_script_file_path: str :param python_interpreter_path: The path to the Python interpreter. :type python_interpreter_path: str :param command_line_args: Command line arguments that need to be passed to the python script. :type command_line_args: str """ _validation = { 'python_script_file_path': {'required': True}, } _attribute_map = { 'python_script_file_path': {'key': 'pythonScriptFilePath', 'type': 'str'}, 'python_interpreter_path': {'key': 'pythonInterpreterPath', 'type': 'str'}, 'command_line_args': {'key': 'commandLineArgs', 'type': 'str'}, } def __init__( self, **kwargs ): super(Caffe2Settings, self).__init__(**kwargs) self.python_script_file_path = kwargs['python_script_file_path'] self.python_interpreter_path = kwargs.get('python_interpreter_path', None) self.command_line_args = kwargs.get('command_line_args', None) class CaffeSettings(msrest.serialization.Model): """Caffe job settings. :param config_file_path: Path of the config file for the job. This property cannot be specified if pythonScriptFilePath is specified. :type config_file_path: str :param python_script_file_path: Python script to execute. This property cannot be specified if configFilePath is specified. :type python_script_file_path: str :param python_interpreter_path: The path to the Python interpreter. The property can be specified only if the pythonScriptFilePath is specified. :type python_interpreter_path: str :param command_line_args: Command line arguments that need to be passed to the Caffe job. :type command_line_args: str :param process_count: Number of processes to launch for the job execution. The default value for this property is equal to nodeCount property. :type process_count: int """ _attribute_map = { 'config_file_path': {'key': 'configFilePath', 'type': 'str'}, 'python_script_file_path': {'key': 'pythonScriptFilePath', 'type': 'str'}, 'python_interpreter_path': {'key': 'pythonInterpreterPath', 'type': 'str'}, 'command_line_args': {'key': 'commandLineArgs', 'type': 'str'}, 'process_count': {'key': 'processCount', 'type': 'int'}, } def __init__( self, **kwargs ): super(CaffeSettings, self).__init__(**kwargs) self.config_file_path = kwargs.get('config_file_path', None) self.python_script_file_path = kwargs.get('python_script_file_path', None) self.python_interpreter_path = kwargs.get('python_interpreter_path', None) self.command_line_args = kwargs.get('command_line_args', None) self.process_count = kwargs.get('process_count', None) class ChainerSettings(msrest.serialization.Model): """Chainer job settings. All required parameters must be populated in order to send to Azure. :param python_script_file_path: Required. The python script to execute. :type python_script_file_path: str :param python_interpreter_path: The path to the Python interpreter. :type python_interpreter_path: str :param command_line_args: Command line arguments that need to be passed to the python script. :type command_line_args: str :param process_count: Number of processes to launch for the job execution. The default value for this property is equal to nodeCount property. :type process_count: int """ _validation = { 'python_script_file_path': {'required': True}, } _attribute_map = { 'python_script_file_path': {'key': 'pythonScriptFilePath', 'type': 'str'}, 'python_interpreter_path': {'key': 'pythonInterpreterPath', 'type': 'str'}, 'command_line_args': {'key': 'commandLineArgs', 'type': 'str'}, 'process_count': {'key': 'processCount', 'type': 'int'}, } def __init__( self, **kwargs ): super(ChainerSettings, self).__init__(**kwargs) self.python_script_file_path = kwargs['python_script_file_path'] self.python_interpreter_path = kwargs.get('python_interpreter_path', None) self.command_line_args = kwargs.get('command_line_args', None) self.process_count = kwargs.get('process_count', None) class CloudErrorBody(msrest.serialization.Model): """An error response from the Batch AI service. Variables are only populated by the server, and will be ignored when sending a request. :ivar code: An identifier for the error. Codes are invariant and are intended to be consumed programmatically. :vartype code: str :ivar message: A message describing the error, intended to be suitable for display in a user interface. :vartype message: str :ivar target: The target of the particular error. For example, the name of the property in error. :vartype target: str :ivar details: A list of additional details about the error. :vartype details: list[~batch_ai.models.CloudErrorBody] """ _validation = { 'code': {'readonly': True}, 'message': {'readonly': True}, 'target': {'readonly': True}, 'details': {'readonly': True}, } _attribute_map = { 'code': {'key': 'code', 'type': 'str'}, 'message': {'key': 'message', 'type': 'str'}, 'target': {'key': 'target', 'type': 'str'}, 'details': {'key': 'details', 'type': '[CloudErrorBody]'}, } def __init__( self, **kwargs ): super(CloudErrorBody, self).__init__(**kwargs) self.code = None self.message = None self.target = None self.details = None class ProxyResource(msrest.serialization.Model): """A definition of an Azure proxy resource. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: The ID of the resource. :vartype id: str :ivar name: The name of the resource. :vartype name: str :ivar type: The type of the resource. :vartype type: str """ _validation = { 'id': {'readonly': True}, 'name': {'readonly': True}, 'type': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, } def __init__( self, **kwargs ): super(ProxyResource, self).__init__(**kwargs) self.id = None self.name = None self.type = None class Cluster(ProxyResource): """Information about a Cluster. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: The ID of the resource. :vartype id: str :ivar name: The name of the resource. :vartype name: str :ivar type: The type of the resource. :vartype type: str :param vm_size: The size of the virtual machines in the cluster. All nodes in a cluster have the same VM size. :type vm_size: str :param vm_priority: VM priority of cluster nodes. Possible values include: "dedicated", "lowpriority". :type vm_priority: str or ~batch_ai.models.VmPriority :param scale_settings: Scale settings of the cluster. :type scale_settings: ~batch_ai.models.ScaleSettings :param virtual_machine_configuration: Virtual machine configuration (OS image) of the compute nodes. All nodes in a cluster have the same OS image configuration. :type virtual_machine_configuration: ~batch_ai.models.VirtualMachineConfiguration :param node_setup: Setup (mount file systems, performance counters settings and custom setup task) to be performed on each compute node in the cluster. :type node_setup: ~batch_ai.models.NodeSetup :param user_account_settings: Administrator user account settings which can be used to SSH to compute nodes. :type user_account_settings: ~batch_ai.models.UserAccountSettings :param subnet: Virtual network subnet resource ID the cluster nodes belong to. :type subnet: ~batch_ai.models.ResourceId :ivar creation_time: The time when the cluster was created. :vartype creation_time: ~datetime.datetime :ivar provisioning_state: Provisioning state of the cluster. Possible value are: creating - Specifies that the cluster is being created. succeeded - Specifies that the cluster has been created successfully. failed - Specifies that the cluster creation has failed. deleting - Specifies that the cluster is being deleted. Possible values include: "creating", "succeeded", "failed", "deleting". :vartype provisioning_state: str or ~batch_ai.models.ProvisioningState :ivar provisioning_state_transition_time: Time when the provisioning state was changed. :vartype provisioning_state_transition_time: ~datetime.datetime :ivar allocation_state: Allocation state of the cluster. Possible values are: steady - Indicates that the cluster is not resizing. There are no changes to the number of compute nodes in the cluster in progress. A cluster enters this state when it is created and when no operations are being performed on the cluster to change the number of compute nodes. resizing - Indicates that the cluster is resizing; that is, compute nodes are being added to or removed from the cluster. Possible values include: "steady", "resizing". :vartype allocation_state: str or ~batch_ai.models.AllocationState :ivar allocation_state_transition_time: The time at which the cluster entered its current allocation state. :vartype allocation_state_transition_time: ~datetime.datetime :ivar errors: Collection of errors encountered by various compute nodes during node setup. :vartype errors: list[~batch_ai.models.BatchAIError] :ivar current_node_count: The number of compute nodes currently assigned to the cluster. :vartype current_node_count: int :ivar node_state_counts: Counts of various node states on the cluster. :vartype node_state_counts: ~batch_ai.models.NodeStateCounts """ _validation = { 'id': {'readonly': True}, 'name': {'readonly': True}, 'type': {'readonly': True}, 'creation_time': {'readonly': True}, 'provisioning_state': {'readonly': True}, 'provisioning_state_transition_time': {'readonly': True}, 'allocation_state': {'readonly': True}, 'allocation_state_transition_time': {'readonly': True}, 'errors': {'readonly': True}, 'current_node_count': {'readonly': True}, 'node_state_counts': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'vm_size': {'key': 'properties.vmSize', 'type': 'str'}, 'vm_priority': {'key': 'properties.vmPriority', 'type': 'str'}, 'scale_settings': {'key': 'properties.scaleSettings', 'type': 'ScaleSettings'}, 'virtual_machine_configuration': {'key': 'properties.virtualMachineConfiguration', 'type': 'VirtualMachineConfiguration'}, 'node_setup': {'key': 'properties.nodeSetup', 'type': 'NodeSetup'}, 'user_account_settings': {'key': 'properties.userAccountSettings', 'type': 'UserAccountSettings'}, 'subnet': {'key': 'properties.subnet', 'type': 'ResourceId'}, 'creation_time': {'key': 'properties.creationTime', 'type': 'iso-8601'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'provisioning_state_transition_time': {'key': 'properties.provisioningStateTransitionTime', 'type': 'iso-8601'}, 'allocation_state': {'key': 'properties.allocationState', 'type': 'str'}, 'allocation_state_transition_time': {'key': 'properties.allocationStateTransitionTime', 'type': 'iso-8601'}, 'errors': {'key': 'properties.errors', 'type': '[BatchAIError]'}, 'current_node_count': {'key': 'properties.currentNodeCount', 'type': 'int'}, 'node_state_counts': {'key': 'properties.nodeStateCounts', 'type': 'NodeStateCounts'}, } def __init__( self, **kwargs ): super(Cluster, self).__init__(**kwargs) self.vm_size = kwargs.get('vm_size', None) self.vm_priority = kwargs.get('vm_priority', None) self.scale_settings = kwargs.get('scale_settings', None) self.virtual_machine_configuration = kwargs.get('virtual_machine_configuration', None) self.node_setup = kwargs.get('node_setup', None) self.user_account_settings = kwargs.get('user_account_settings', None) self.subnet = kwargs.get('subnet', None) self.creation_time = None self.provisioning_state = None self.provisioning_state_transition_time = None self.allocation_state = None self.allocation_state_transition_time = None self.errors = None self.current_node_count = None self.node_state_counts = None class ClusterCreateParameters(msrest.serialization.Model): """Cluster creation operation. :param vm_size: The size of the virtual machines in the cluster. All nodes in a cluster have the same VM size. For information about available VM sizes for clusters using images from the Virtual Machines Marketplace see Sizes for Virtual Machines (Linux). Batch AI service supports all Azure VM sizes except STANDARD_A0 and those with premium storage (STANDARD_GS, STANDARD_DS, and STANDARD_DSV2 series). :type vm_size: str :param vm_priority: VM priority. Allowed values are: dedicated (default) and lowpriority. Possible values include: "dedicated", "lowpriority". :type vm_priority: str or ~batch_ai.models.VmPriority :param scale_settings: Scale settings for the cluster. Batch AI service supports manual and auto scale clusters. :type scale_settings: ~batch_ai.models.ScaleSettings :param virtual_machine_configuration: OS image configuration for cluster nodes. All nodes in a cluster have the same OS image. :type virtual_machine_configuration: ~batch_ai.models.VirtualMachineConfiguration :param node_setup: Setup to be performed on each compute node in the cluster. :type node_setup: ~batch_ai.models.NodeSetup :param user_account_settings: Settings for an administrator user account that will be created on each compute node in the cluster. :type user_account_settings: ~batch_ai.models.UserAccountSettings :param subnet: Existing virtual network subnet to put the cluster nodes in. Note, if a File Server mount configured in node setup, the File Server's subnet will be used automatically. :type subnet: ~batch_ai.models.ResourceId """ _attribute_map = { 'vm_size': {'key': 'properties.vmSize', 'type': 'str'}, 'vm_priority': {'key': 'properties.vmPriority', 'type': 'str'}, 'scale_settings': {'key': 'properties.scaleSettings', 'type': 'ScaleSettings'}, 'virtual_machine_configuration': {'key': 'properties.virtualMachineConfiguration', 'type': 'VirtualMachineConfiguration'}, 'node_setup': {'key': 'properties.nodeSetup', 'type': 'NodeSetup'}, 'user_account_settings': {'key': 'properties.userAccountSettings', 'type': 'UserAccountSettings'}, 'subnet': {'key': 'properties.subnet', 'type': 'ResourceId'}, } def __init__( self, **kwargs ): super(ClusterCreateParameters, self).__init__(**kwargs) self.vm_size = kwargs.get('vm_size', None) self.vm_priority = kwargs.get('vm_priority', None) self.scale_settings = kwargs.get('scale_settings', None) self.virtual_machine_configuration = kwargs.get('virtual_machine_configuration', None) self.node_setup = kwargs.get('node_setup', None) self.user_account_settings = kwargs.get('user_account_settings', None) self.subnet = kwargs.get('subnet', None) class ClusterListResult(msrest.serialization.Model): """Values returned by the List Clusters operation. Variables are only populated by the server, and will be ignored when sending a request. :ivar value: The collection of returned Clusters. :vartype value: list[~batch_ai.models.Cluster] :ivar next_link: The continuation token. :vartype next_link: str """ _validation = { 'value': {'readonly': True}, 'next_link': {'readonly': True}, } _attribute_map = { 'value': {'key': 'value', 'type': '[Cluster]'}, 'next_link': {'key': 'nextLink', 'type': 'str'}, } def __init__( self, **kwargs ): super(ClusterListResult, self).__init__(**kwargs) self.value = None self.next_link = None class ClustersListByWorkspaceOptions(msrest.serialization.Model): """Parameter group. :param max_results: The maximum number of items to return in the response. A maximum of 1000 files can be returned. :type max_results: int """ _validation = { 'max_results': {'maximum': 1000, 'minimum': 1}, } _attribute_map = { 'max_results': {'key': 'maxResults', 'type': 'int'}, } def __init__( self, **kwargs ): super(ClustersListByWorkspaceOptions, self).__init__(**kwargs) self.max_results = kwargs.get('max_results', 1000) class ClusterUpdateParameters(msrest.serialization.Model): """Cluster update parameters. :param scale_settings: Desired scale settings for the cluster. Batch AI service supports manual and auto scale clusters. :type scale_settings: ~batch_ai.models.ScaleSettings """ _attribute_map = { 'scale_settings': {'key': 'properties.scaleSettings', 'type': 'ScaleSettings'}, } def __init__( self, **kwargs ): super(ClusterUpdateParameters, self).__init__(**kwargs) self.scale_settings = kwargs.get('scale_settings', None) class CNTKsettings(msrest.serialization.Model): """CNTK (aka Microsoft Cognitive Toolkit) job settings. :param language_type: The language to use for launching CNTK (aka Microsoft Cognitive Toolkit) job. Valid values are 'BrainScript' or 'Python'. :type language_type: str :param config_file_path: Specifies the path of the BrainScript config file. This property can be specified only if the languageType is 'BrainScript'. :type config_file_path: str :param python_script_file_path: Python script to execute. This property can be specified only if the languageType is 'Python'. :type python_script_file_path: str :param python_interpreter_path: The path to the Python interpreter. This property can be specified only if the languageType is 'Python'. :type python_interpreter_path: str :param command_line_args: Command line arguments that need to be passed to the python script or cntk executable. :type command_line_args: str :param process_count: Number of processes to launch for the job execution. The default value for this property is equal to nodeCount property. :type process_count: int """ _attribute_map = { 'language_type': {'key': 'languageType', 'type': 'str'}, 'config_file_path': {'key': 'configFilePath', 'type': 'str'}, 'python_script_file_path': {'key': 'pythonScriptFilePath', 'type': 'str'}, 'python_interpreter_path': {'key': 'pythonInterpreterPath', 'type': 'str'}, 'command_line_args': {'key': 'commandLineArgs', 'type': 'str'}, 'process_count': {'key': 'processCount', 'type': 'int'}, } def __init__( self, **kwargs ): super(CNTKsettings, self).__init__(**kwargs) self.language_type = kwargs.get('language_type', None) self.config_file_path = kwargs.get('config_file_path', None) self.python_script_file_path = kwargs.get('python_script_file_path', None) self.python_interpreter_path = kwargs.get('python_interpreter_path', None) self.command_line_args = kwargs.get('command_line_args', None) self.process_count = kwargs.get('process_count', None) class ContainerSettings(msrest.serialization.Model): """Docker container settings. All required parameters must be populated in order to send to Azure. :param image_source_registry: Required. Information about docker image and docker registry to download the container from. :type image_source_registry: ~batch_ai.models.ImageSourceRegistry :param shm_size: Size of /dev/shm. Please refer to docker documentation for supported argument formats. :type shm_size: str """ _validation = { 'image_source_registry': {'required': True}, } _attribute_map = { 'image_source_registry': {'key': 'imageSourceRegistry', 'type': 'ImageSourceRegistry'}, 'shm_size': {'key': 'shmSize', 'type': 'str'}, } def __init__( self, **kwargs ): super(ContainerSettings, self).__init__(**kwargs) self.image_source_registry = kwargs['image_source_registry'] self.shm_size = kwargs.get('shm_size', None) class CustomMpiSettings(msrest.serialization.Model): """Custom MPI job settings. All required parameters must be populated in order to send to Azure. :param command_line: Required. The command line to be executed by mpi runtime on each compute node. :type command_line: str :param process_count: Number of processes to launch for the job execution. The default value for this property is equal to nodeCount property. :type process_count: int """ _validation = { 'command_line': {'required': True}, } _attribute_map = { 'command_line': {'key': 'commandLine', 'type': 'str'}, 'process_count': {'key': 'processCount', 'type': 'int'}, } def __init__( self, **kwargs ): super(CustomMpiSettings, self).__init__(**kwargs) self.command_line = kwargs['command_line'] self.process_count = kwargs.get('process_count', None) class CustomToolkitSettings(msrest.serialization.Model): """Custom tool kit job settings. :param command_line: The command line to execute on the master node. :type command_line: str """ _attribute_map = { 'command_line': {'key': 'commandLine', 'type': 'str'}, } def __init__( self, **kwargs ): super(CustomToolkitSettings, self).__init__(**kwargs) self.command_line = kwargs.get('command_line', None) class DataDisks(msrest.serialization.Model): """Data disks settings. All required parameters must be populated in order to send to Azure. :param disk_size_in_gb: Required. Disk size in GB for the blank data disks. :type disk_size_in_gb: int :param caching_type: Caching type for the disks. Available values are none (default), readonly, readwrite. Caching type can be set only for VM sizes supporting premium storage. Possible values include: "none", "readonly", "readwrite". Default value: "none". :type caching_type: str or ~batch_ai.models.CachingType :param disk_count: Required. Number of data disks attached to the File Server. If multiple disks attached, they will be configured in RAID level 0. :type disk_count: int :param storage_account_type: Required. Type of storage account to be used on the disk. Possible values are: Standard_LRS or Premium_LRS. Premium storage account type can only be used with VM sizes supporting premium storage. Possible values include: "Standard_LRS", "Premium_LRS". :type storage_account_type: str or ~batch_ai.models.StorageAccountType """ _validation = { 'disk_size_in_gb': {'required': True}, 'disk_count': {'required': True}, 'storage_account_type': {'required': True}, } _attribute_map = { 'disk_size_in_gb': {'key': 'diskSizeInGB', 'type': 'int'}, 'caching_type': {'key': 'cachingType', 'type': 'str'}, 'disk_count': {'key': 'diskCount', 'type': 'int'}, 'storage_account_type': {'key': 'storageAccountType', 'type': 'str'}, } def __init__( self, **kwargs ): super(DataDisks, self).__init__(**kwargs) self.disk_size_in_gb = kwargs['disk_size_in_gb'] self.caching_type = kwargs.get('caching_type', "none") self.disk_count = kwargs['disk_count'] self.storage_account_type = kwargs['storage_account_type'] class EnvironmentVariable(msrest.serialization.Model): """An environment variable definition. All required parameters must be populated in order to send to Azure. :param name: Required. The name of the environment variable. :type name: str :param value: Required. The value of the environment variable. :type value: str """ _validation = { 'name': {'required': True}, 'value': {'required': True}, } _attribute_map = { 'name': {'key': 'name', 'type': 'str'}, 'value': {'key': 'value', 'type': 'str'}, } def __init__( self, **kwargs ): super(EnvironmentVariable, self).__init__(**kwargs) self.name = kwargs['name'] self.value = kwargs['value'] class EnvironmentVariableWithSecretValue(msrest.serialization.Model): """An environment variable with secret value definition. All required parameters must be populated in order to send to Azure. :param name: Required. The name of the environment variable to store the secret value. :type name: str :param value: The value of the environment variable. This value will never be reported back by Batch AI. :type value: str :param value_secret_reference: KeyVault store and secret which contains the value for the environment variable. One of value or valueSecretReference must be provided. :type value_secret_reference: ~batch_ai.models.KeyVaultSecretReference """ _validation = { 'name': {'required': True}, } _attribute_map = { 'name': {'key': 'name', 'type': 'str'}, 'value': {'key': 'value', 'type': 'str'}, 'value_secret_reference': {'key': 'valueSecretReference', 'type': 'KeyVaultSecretReference'}, } def __init__( self, **kwargs ): super(EnvironmentVariableWithSecretValue, self).__init__(**kwargs) self.name = kwargs['name'] self.value = kwargs.get('value', None) self.value_secret_reference = kwargs.get('value_secret_reference', None) class Experiment(ProxyResource): """Experiment information. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: The ID of the resource. :vartype id: str :ivar name: The name of the resource. :vartype name: str :ivar type: The type of the resource. :vartype type: str :ivar creation_time: Time when the Experiment was created. :vartype creation_time: ~datetime.datetime :ivar provisioning_state: The provisioned state of the experiment. Possible values include: "creating", "succeeded", "failed", "deleting". :vartype provisioning_state: str or ~batch_ai.models.ProvisioningState :ivar provisioning_state_transition_time: The time at which the experiment entered its current provisioning state. :vartype provisioning_state_transition_time: ~datetime.datetime """ _validation = { 'id': {'readonly': True}, 'name': {'readonly': True}, 'type': {'readonly': True}, 'creation_time': {'readonly': True}, 'provisioning_state': {'readonly': True}, 'provisioning_state_transition_time': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'creation_time': {'key': 'properties.creationTime', 'type': 'iso-8601'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'provisioning_state_transition_time': {'key': 'properties.provisioningStateTransitionTime', 'type': 'iso-8601'}, } def __init__( self, **kwargs ): super(Experiment, self).__init__(**kwargs) self.creation_time = None self.provisioning_state = None self.provisioning_state_transition_time = None class ExperimentListResult(msrest.serialization.Model): """Values returned by the List operation. Variables are only populated by the server, and will be ignored when sending a request. :ivar value: The collection of experiments. :vartype value: list[~batch_ai.models.Experiment] :ivar next_link: The continuation token. :vartype next_link: str """ _validation = { 'value': {'readonly': True}, 'next_link': {'readonly': True}, } _attribute_map = { 'value': {'key': 'value', 'type': '[Experiment]'}, 'next_link': {'key': 'nextLink', 'type': 'str'}, } def __init__( self, **kwargs ): super(ExperimentListResult, self).__init__(**kwargs) self.value = None self.next_link = None class ExperimentsListByWorkspaceOptions(msrest.serialization.Model): """Parameter group. :param max_results: The maximum number of items to return in the response. A maximum of 1000 files can be returned. :type max_results: int """ _validation = { 'max_results': {'maximum': 1000, 'minimum': 1}, } _attribute_map = { 'max_results': {'key': 'maxResults', 'type': 'int'}, } def __init__( self, **kwargs ): super(ExperimentsListByWorkspaceOptions, self).__init__(**kwargs) self.max_results = kwargs.get('max_results', 1000) class File(msrest.serialization.Model): """Properties of the file or directory. Variables are only populated by the server, and will be ignored when sending a request. :ivar name: Name of the file. :vartype name: str :ivar file_type: Type of the file. Possible values are file and directory. Possible values include: "file", "directory". :vartype file_type: str or ~batch_ai.models.FileType :ivar download_url: URL to download the corresponding file. The downloadUrl is not returned for directories. :vartype download_url: str :ivar last_modified: The time at which the file was last modified. :vartype last_modified: ~datetime.datetime :ivar content_length: The file of the size. :vartype content_length: long """ _validation = { 'name': {'readonly': True}, 'file_type': {'readonly': True}, 'download_url': {'readonly': True}, 'last_modified': {'readonly': True}, 'content_length': {'readonly': True}, } _attribute_map = { 'name': {'key': 'name', 'type': 'str'}, 'file_type': {'key': 'fileType', 'type': 'str'}, 'download_url': {'key': 'downloadUrl', 'type': 'str'}, 'last_modified': {'key': 'properties.lastModified', 'type': 'iso-8601'}, 'content_length': {'key': 'properties.contentLength', 'type': 'long'}, } def __init__( self, **kwargs ): super(File, self).__init__(**kwargs) self.name = None self.file_type = None self.download_url = None self.last_modified = None self.content_length = None class FileListResult(msrest.serialization.Model): """Values returned by the List operation. Variables are only populated by the server, and will be ignored when sending a request. :ivar value: The collection of returned job directories and files. :vartype value: list[~batch_ai.models.File] :ivar next_link: The continuation token. :vartype next_link: str """ _validation = { 'value': {'readonly': True}, 'next_link': {'readonly': True}, } _attribute_map = { 'value': {'key': 'value', 'type': '[File]'}, 'next_link': {'key': 'nextLink', 'type': 'str'}, } def __init__( self, **kwargs ): super(FileListResult, self).__init__(**kwargs) self.value = None self.next_link = None class FileServer(ProxyResource): """File Server information. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: The ID of the resource. :vartype id: str :ivar name: The name of the resource. :vartype name: str :ivar type: The type of the resource. :vartype type: str :param vm_size: VM size of the File Server. :type vm_size: str :param ssh_configuration: SSH configuration for accessing the File Server node. :type ssh_configuration: ~batch_ai.models.SshConfiguration :param data_disks: Information about disks attached to File Server VM. :type data_disks: ~batch_ai.models.DataDisks :param subnet: File Server virtual network subnet resource ID. :type subnet: ~batch_ai.models.ResourceId :ivar mount_settings: File Server mount settings. :vartype mount_settings: ~batch_ai.models.MountSettings :ivar provisioning_state_transition_time: Time when the provisioning state was changed. :vartype provisioning_state_transition_time: ~datetime.datetime :ivar creation_time: Time when the FileServer was created. :vartype creation_time: ~datetime.datetime :ivar provisioning_state: Provisioning state of the File Server. Possible values: creating - The File Server is getting created; updating - The File Server creation has been accepted and it is getting updated; deleting - The user has requested that the File Server be deleted, and it is in the process of being deleted; failed - The File Server creation has failed with the specified error code. Details about the error code are specified in the message field; succeeded - The File Server creation has succeeded. Possible values include: "creating", "updating", "deleting", "succeeded", "failed". :vartype provisioning_state: str or ~batch_ai.models.FileServerProvisioningState """ _validation = { 'id': {'readonly': True}, 'name': {'readonly': True}, 'type': {'readonly': True}, 'mount_settings': {'readonly': True}, 'provisioning_state_transition_time': {'readonly': True}, 'creation_time': {'readonly': True}, 'provisioning_state': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'vm_size': {'key': 'properties.vmSize', 'type': 'str'}, 'ssh_configuration': {'key': 'properties.sshConfiguration', 'type': 'SshConfiguration'}, 'data_disks': {'key': 'properties.dataDisks', 'type': 'DataDisks'}, 'subnet': {'key': 'properties.subnet', 'type': 'ResourceId'}, 'mount_settings': {'key': 'properties.mountSettings', 'type': 'MountSettings'}, 'provisioning_state_transition_time': {'key': 'properties.provisioningStateTransitionTime', 'type': 'iso-8601'}, 'creation_time': {'key': 'properties.creationTime', 'type': 'iso-8601'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, } def __init__( self, **kwargs ): super(FileServer, self).__init__(**kwargs) self.vm_size = kwargs.get('vm_size', None) self.ssh_configuration = kwargs.get('ssh_configuration', None) self.data_disks = kwargs.get('data_disks', None) self.subnet = kwargs.get('subnet', None) self.mount_settings = None self.provisioning_state_transition_time = None self.creation_time = None self.provisioning_state = None class FileServerCreateParameters(msrest.serialization.Model): """File Server creation parameters. :param vm_size: The size of the virtual machine for the File Server. For information about available VM sizes from the Virtual Machines Marketplace, see Sizes for Virtual Machines (Linux). :type vm_size: str :param ssh_configuration: SSH configuration for the File Server node. :type ssh_configuration: ~batch_ai.models.SshConfiguration :param data_disks: Settings for the data disks which will be created for the File Server. :type data_disks: ~batch_ai.models.DataDisks :param subnet: Identifier of an existing virtual network subnet to put the File Server in. If not provided, a new virtual network and subnet will be created. :type subnet: ~batch_ai.models.ResourceId """ _attribute_map = { 'vm_size': {'key': 'properties.vmSize', 'type': 'str'}, 'ssh_configuration': {'key': 'properties.sshConfiguration', 'type': 'SshConfiguration'}, 'data_disks': {'key': 'properties.dataDisks', 'type': 'DataDisks'}, 'subnet': {'key': 'properties.subnet', 'type': 'ResourceId'}, } def __init__( self, **kwargs ): super(FileServerCreateParameters, self).__init__(**kwargs) self.vm_size = kwargs.get('vm_size', None) self.ssh_configuration = kwargs.get('ssh_configuration', None) self.data_disks = kwargs.get('data_disks', None) self.subnet = kwargs.get('subnet', None) class FileServerListResult(msrest.serialization.Model): """Values returned by the File Server List operation. Variables are only populated by the server, and will be ignored when sending a request. :param value: The collection of File Servers. :type value: list[~batch_ai.models.FileServer] :ivar next_link: The continuation token. :vartype next_link: str """ _validation = { 'next_link': {'readonly': True}, } _attribute_map = { 'value': {'key': 'value', 'type': '[FileServer]'}, 'next_link': {'key': 'nextLink', 'type': 'str'}, } def __init__( self, **kwargs ): super(FileServerListResult, self).__init__(**kwargs) self.value = kwargs.get('value', None) self.next_link = None class FileServerReference(msrest.serialization.Model): """File Server mounting configuration. All required parameters must be populated in order to send to Azure. :param file_server: Required. Resource ID of the existing File Server to be mounted. :type file_server: ~batch_ai.models.ResourceId :param source_directory: File Server directory that needs to be mounted. If this property is not specified, the entire File Server will be mounted. :type source_directory: str :param relative_mount_path: Required. The relative path on the compute node where the File Server will be mounted. Note that all cluster level file servers will be mounted under $AZ_BATCHAI_MOUNT_ROOT location and all job level file servers will be mounted under $AZ_BATCHAI_JOB_MOUNT_ROOT. :type relative_mount_path: str :param mount_options: Mount options to be passed to mount command. :type mount_options: str """ _validation = { 'file_server': {'required': True}, 'relative_mount_path': {'required': True}, } _attribute_map = { 'file_server': {'key': 'fileServer', 'type': 'ResourceId'}, 'source_directory': {'key': 'sourceDirectory', 'type': 'str'}, 'relative_mount_path': {'key': 'relativeMountPath', 'type': 'str'}, 'mount_options': {'key': 'mountOptions', 'type': 'str'}, } def __init__( self, **kwargs ): super(FileServerReference, self).__init__(**kwargs) self.file_server = kwargs['file_server'] self.source_directory = kwargs.get('source_directory', None) self.relative_mount_path = kwargs['relative_mount_path'] self.mount_options = kwargs.get('mount_options', None) class FileServersListByWorkspaceOptions(msrest.serialization.Model): """Parameter group. :param max_results: The maximum number of items to return in the response. A maximum of 1000 files can be returned. :type max_results: int """ _validation = { 'max_results': {'maximum': 1000, 'minimum': 1}, } _attribute_map = { 'max_results': {'key': 'maxResults', 'type': 'int'}, } def __init__( self, **kwargs ): super(FileServersListByWorkspaceOptions, self).__init__(**kwargs) self.max_results = kwargs.get('max_results', 1000) class HorovodSettings(msrest.serialization.Model): """Specifies the settings for Horovod job. All required parameters must be populated in order to send to Azure. :param python_script_file_path: Required. The python script to execute. :type python_script_file_path: str :param python_interpreter_path: The path to the Python interpreter. :type python_interpreter_path: str :param command_line_args: Command line arguments that need to be passed to the python script. :type command_line_args: str :param process_count: Number of processes to launch for the job execution. The default value for this property is equal to nodeCount property. :type process_count: int """ _validation = { 'python_script_file_path': {'required': True}, } _attribute_map = { 'python_script_file_path': {'key': 'pythonScriptFilePath', 'type': 'str'}, 'python_interpreter_path': {'key': 'pythonInterpreterPath', 'type': 'str'}, 'command_line_args': {'key': 'commandLineArgs', 'type': 'str'}, 'process_count': {'key': 'processCount', 'type': 'int'}, } def __init__( self, **kwargs ): super(HorovodSettings, self).__init__(**kwargs) self.python_script_file_path = kwargs['python_script_file_path'] self.python_interpreter_path = kwargs.get('python_interpreter_path', None) self.command_line_args = kwargs.get('command_line_args', None) self.process_count = kwargs.get('process_count', None) class ImageReference(msrest.serialization.Model): """The OS image reference. All required parameters must be populated in order to send to Azure. :param publisher: Required. Publisher of the image. :type publisher: str :param offer: Required. Offer of the image. :type offer: str :param sku: Required. SKU of the image. :type sku: str :param version: Version of the image. :type version: str :param virtual_machine_image_id: The ARM resource identifier of the virtual machine image for the compute nodes. This is of the form /subscriptions/{subscriptionId}/resourceGroups/{resourceGroup}/providers/Microsoft.Compute/images/{imageName}. The virtual machine image must be in the same region and subscription as the cluster. For information about the firewall settings for the Batch node agent to communicate with the Batch service see https://docs.microsoft.com/en-us/azure/batch/batch-api-basics#virtual-network-vnet-and-firewall-configuration. Note, you need to provide publisher, offer and sku of the base OS image of which the custom image has been derived from. :type virtual_machine_image_id: str """ _validation = { 'publisher': {'required': True}, 'offer': {'required': True}, 'sku': {'required': True}, } _attribute_map = { 'publisher': {'key': 'publisher', 'type': 'str'}, 'offer': {'key': 'offer', 'type': 'str'}, 'sku': {'key': 'sku', 'type': 'str'}, 'version': {'key': 'version', 'type': 'str'}, 'virtual_machine_image_id': {'key': 'virtualMachineImageId', 'type': 'str'}, } def __init__( self, **kwargs ): super(ImageReference, self).__init__(**kwargs) self.publisher = kwargs['publisher'] self.offer = kwargs['offer'] self.sku = kwargs['sku'] self.version = kwargs.get('version', None) self.virtual_machine_image_id = kwargs.get('virtual_machine_image_id', None) class ImageSourceRegistry(msrest.serialization.Model): """Information about docker image for the job. All required parameters must be populated in order to send to Azure. :param server_url: URL for image repository. :type server_url: str :param image: Required. The name of the image in the image repository. :type image: str :param credentials: Credentials to access the private docker repository. :type credentials: ~batch_ai.models.PrivateRegistryCredentials """ _validation = { 'image': {'required': True}, } _attribute_map = { 'server_url': {'key': 'serverUrl', 'type': 'str'}, 'image': {'key': 'image', 'type': 'str'}, 'credentials': {'key': 'credentials', 'type': 'PrivateRegistryCredentials'}, } def __init__( self, **kwargs ): super(ImageSourceRegistry, self).__init__(**kwargs) self.server_url = kwargs.get('server_url', None) self.image = kwargs['image'] self.credentials = kwargs.get('credentials', None) class InputDirectory(msrest.serialization.Model): """Input directory for the job. All required parameters must be populated in order to send to Azure. :param id: Required. The ID for the input directory. The job can use AZ_BATCHAI\ *INPUT*\ :code:`<id>` environment variable to find the directory path, where :code:`<id>` is the value of id attribute. :type id: str :param path: Required. The path to the input directory. :type path: str """ _validation = { 'id': {'required': True}, 'path': {'required': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'path': {'key': 'path', 'type': 'str'}, } def __init__( self, **kwargs ): super(InputDirectory, self).__init__(**kwargs) self.id = kwargs['id'] self.path = kwargs['path'] class Job(ProxyResource): """Information about a Job. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: The ID of the resource. :vartype id: str :ivar name: The name of the resource. :vartype name: str :ivar type: The type of the resource. :vartype type: str :param scheduling_priority: Scheduling priority associated with the job. Possible values include: "low", "normal", "high". :type scheduling_priority: str or ~batch_ai.models.JobPriority :param cluster: Resource ID of the cluster associated with the job. :type cluster: ~batch_ai.models.ResourceId :param mount_volumes: Collection of mount volumes available to the job during execution. These volumes are mounted before the job execution and unmounted after the job completion. The volumes are mounted at location specified by $AZ_BATCHAI_JOB_MOUNT_ROOT environment variable. :type mount_volumes: ~batch_ai.models.MountVolumes :param node_count: The job will be gang scheduled on that many compute nodes. :type node_count: int :param container_settings: If the container was downloaded as part of cluster setup then the same container image will be used. If not provided, the job will run on the VM. :type container_settings: ~batch_ai.models.ContainerSettings :param tool_type: Possible values are: cntk, tensorflow, caffe, caffe2, chainer, pytorch, custom, custommpi, horovod. Possible values include: "cntk", "tensorflow", "caffe", "caffe2", "chainer", "horovod", "custommpi", "custom". :type tool_type: str or ~batch_ai.models.ToolType :param cntk_settings: CNTK (aka Microsoft Cognitive Toolkit) job settings. :type cntk_settings: ~batch_ai.models.CNTKsettings :param py_torch_settings: pyTorch job settings. :type py_torch_settings: ~batch_ai.models.PyTorchSettings :param tensor_flow_settings: TensorFlow job settings. :type tensor_flow_settings: ~batch_ai.models.TensorFlowSettings :param caffe_settings: Caffe job settings. :type caffe_settings: ~batch_ai.models.CaffeSettings :param caffe2_settings: Caffe2 job settings. :type caffe2_settings: ~batch_ai.models.Caffe2Settings :param chainer_settings: Chainer job settings. :type chainer_settings: ~batch_ai.models.ChainerSettings :param custom_toolkit_settings: Custom tool kit job settings. :type custom_toolkit_settings: ~batch_ai.models.CustomToolkitSettings :param custom_mpi_settings: Custom MPI job settings. :type custom_mpi_settings: ~batch_ai.models.CustomMpiSettings :param horovod_settings: Specifies the settings for Horovod job. :type horovod_settings: ~batch_ai.models.HorovodSettings :param job_preparation: The specified actions will run on all the nodes that are part of the job. :type job_preparation: ~batch_ai.models.JobPreparation :ivar job_output_directory_path_segment: A segment of job's output directories path created by Batch AI. Batch AI creates job's output directories under an unique path to avoid conflicts between jobs. This value contains a path segment generated by Batch AI to make the path unique and can be used to find the output directory on the node or mounted filesystem. :vartype job_output_directory_path_segment: str :param std_out_err_path_prefix: The path where the Batch AI service stores stdout, stderror and execution log of the job. :type std_out_err_path_prefix: str :param input_directories: A list of input directories for the job. :type input_directories: list[~batch_ai.models.InputDirectory] :param output_directories: A list of output directories for the job. :type output_directories: list[~batch_ai.models.OutputDirectory] :param environment_variables: A collection of user defined environment variables to be setup for the job. :type environment_variables: list[~batch_ai.models.EnvironmentVariable] :param secrets: A collection of user defined environment variables with secret values to be setup for the job. Server will never report values of these variables back. :type secrets: list[~batch_ai.models.EnvironmentVariableWithSecretValue] :param constraints: Constraints associated with the Job. :type constraints: ~batch_ai.models.JobPropertiesConstraints :ivar creation_time: The creation time of the job. :vartype creation_time: ~datetime.datetime :ivar provisioning_state: The provisioned state of the Batch AI job. Possible values include: "creating", "succeeded", "failed", "deleting". :vartype provisioning_state: str or ~batch_ai.models.ProvisioningState :ivar provisioning_state_transition_time: The time at which the job entered its current provisioning state. :vartype provisioning_state_transition_time: ~datetime.datetime :ivar execution_state: The current state of the job. Possible values are: queued - The job is queued and able to run. A job enters this state when it is created, or when it is awaiting a retry after a failed run. running - The job is running on a compute cluster. This includes job-level preparation such as downloading resource files or set up container specified on the job - it does not necessarily mean that the job command line has started executing. terminating - The job is terminated by the user, the terminate operation is in progress. succeeded - The job has completed running successfully and exited with exit code 0. failed - The job has finished unsuccessfully (failed with a non-zero exit code) and has exhausted its retry limit. A job is also marked as failed if an error occurred launching the job. Possible values include: "queued", "running", "terminating", "succeeded", "failed". :vartype execution_state: str or ~batch_ai.models.ExecutionState :ivar execution_state_transition_time: The time at which the job entered its current execution state. :vartype execution_state_transition_time: ~datetime.datetime :param execution_info: Information about the execution of a job. :type execution_info: ~batch_ai.models.JobPropertiesExecutionInfo """ _validation = { 'id': {'readonly': True}, 'name': {'readonly': True}, 'type': {'readonly': True}, 'job_output_directory_path_segment': {'readonly': True}, 'creation_time': {'readonly': True}, 'provisioning_state': {'readonly': True}, 'provisioning_state_transition_time': {'readonly': True}, 'execution_state': {'readonly': True}, 'execution_state_transition_time': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'scheduling_priority': {'key': 'properties.schedulingPriority', 'type': 'str'}, 'cluster': {'key': 'properties.cluster', 'type': 'ResourceId'}, 'mount_volumes': {'key': 'properties.mountVolumes', 'type': 'MountVolumes'}, 'node_count': {'key': 'properties.nodeCount', 'type': 'int'}, 'container_settings': {'key': 'properties.containerSettings', 'type': 'ContainerSettings'}, 'tool_type': {'key': 'properties.toolType', 'type': 'str'}, 'cntk_settings': {'key': 'properties.cntkSettings', 'type': 'CNTKsettings'}, 'py_torch_settings': {'key': 'properties.pyTorchSettings', 'type': 'PyTorchSettings'}, 'tensor_flow_settings': {'key': 'properties.tensorFlowSettings', 'type': 'TensorFlowSettings'}, 'caffe_settings': {'key': 'properties.caffeSettings', 'type': 'CaffeSettings'}, 'caffe2_settings': {'key': 'properties.caffe2Settings', 'type': 'Caffe2Settings'}, 'chainer_settings': {'key': 'properties.chainerSettings', 'type': 'ChainerSettings'}, 'custom_toolkit_settings': {'key': 'properties.customToolkitSettings', 'type': 'CustomToolkitSettings'}, 'custom_mpi_settings': {'key': 'properties.customMpiSettings', 'type': 'CustomMpiSettings'}, 'horovod_settings': {'key': 'properties.horovodSettings', 'type': 'HorovodSettings'}, 'job_preparation': {'key': 'properties.jobPreparation', 'type': 'JobPreparation'}, 'job_output_directory_path_segment': {'key': 'properties.jobOutputDirectoryPathSegment', 'type': 'str'}, 'std_out_err_path_prefix': {'key': 'properties.stdOutErrPathPrefix', 'type': 'str'}, 'input_directories': {'key': 'properties.inputDirectories', 'type': '[InputDirectory]'}, 'output_directories': {'key': 'properties.outputDirectories', 'type': '[OutputDirectory]'}, 'environment_variables': {'key': 'properties.environmentVariables', 'type': '[EnvironmentVariable]'}, 'secrets': {'key': 'properties.secrets', 'type': '[EnvironmentVariableWithSecretValue]'}, 'constraints': {'key': 'properties.constraints', 'type': 'JobPropertiesConstraints'}, 'creation_time': {'key': 'properties.creationTime', 'type': 'iso-8601'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'provisioning_state_transition_time': {'key': 'properties.provisioningStateTransitionTime', 'type': 'iso-8601'}, 'execution_state': {'key': 'properties.executionState', 'type': 'str'}, 'execution_state_transition_time': {'key': 'properties.executionStateTransitionTime', 'type': 'iso-8601'}, 'execution_info': {'key': 'properties.executionInfo', 'type': 'JobPropertiesExecutionInfo'}, } def __init__( self, **kwargs ): super(Job, self).__init__(**kwargs) self.scheduling_priority = kwargs.get('scheduling_priority', None) self.cluster = kwargs.get('cluster', None) self.mount_volumes = kwargs.get('mount_volumes', None) self.node_count = kwargs.get('node_count', None) self.container_settings = kwargs.get('container_settings', None) self.tool_type = kwargs.get('tool_type', None) self.cntk_settings = kwargs.get('cntk_settings', None) self.py_torch_settings = kwargs.get('py_torch_settings', None) self.tensor_flow_settings = kwargs.get('tensor_flow_settings', None) self.caffe_settings = kwargs.get('caffe_settings', None) self.caffe2_settings = kwargs.get('caffe2_settings', None) self.chainer_settings = kwargs.get('chainer_settings', None) self.custom_toolkit_settings = kwargs.get('custom_toolkit_settings', None) self.custom_mpi_settings = kwargs.get('custom_mpi_settings', None) self.horovod_settings = kwargs.get('horovod_settings', None) self.job_preparation = kwargs.get('job_preparation', None) self.job_output_directory_path_segment = None self.std_out_err_path_prefix = kwargs.get('std_out_err_path_prefix', None) self.input_directories = kwargs.get('input_directories', None) self.output_directories = kwargs.get('output_directories', None) self.environment_variables = kwargs.get('environment_variables', None) self.secrets = kwargs.get('secrets', None) self.constraints = kwargs.get('constraints', None) self.creation_time = None self.provisioning_state = None self.provisioning_state_transition_time = None self.execution_state = None self.execution_state_transition_time = None self.execution_info = kwargs.get('execution_info', None) class JobBasePropertiesConstraints(msrest.serialization.Model): """Constraints associated with the Job. :param max_wall_clock_time: Max time the job can run. Default value: 1 week. :type max_wall_clock_time: ~datetime.timedelta """ _attribute_map = { 'max_wall_clock_time': {'key': 'maxWallClockTime', 'type': 'duration'}, } def __init__( self, **kwargs ): super(JobBasePropertiesConstraints, self).__init__(**kwargs) self.max_wall_clock_time = kwargs.get('max_wall_clock_time', "7.00:00:00") class JobCreateParameters(msrest.serialization.Model): """Job creation parameters. :param scheduling_priority: Scheduling priority associated with the job. Possible values: low, normal, high. Possible values include: "low", "normal", "high". :type scheduling_priority: str or ~batch_ai.models.JobPriority :param cluster: Resource ID of the cluster on which this job will run. :type cluster: ~batch_ai.models.ResourceId :param mount_volumes: Information on mount volumes to be used by the job. These volumes will be mounted before the job execution and will be unmounted after the job completion. The volumes will be mounted at location specified by $AZ_BATCHAI_JOB_MOUNT_ROOT environment variable. :type mount_volumes: ~batch_ai.models.MountVolumes :param node_count: Number of compute nodes to run the job on. The job will be gang scheduled on that many compute nodes. :type node_count: int :param container_settings: Docker container settings for the job. If not provided, the job will run directly on the node. :type container_settings: ~batch_ai.models.ContainerSettings :param cntk_settings: Settings for CNTK (aka Microsoft Cognitive Toolkit) job. :type cntk_settings: ~batch_ai.models.CNTKsettings :param py_torch_settings: Settings for pyTorch job. :type py_torch_settings: ~batch_ai.models.PyTorchSettings :param tensor_flow_settings: Settings for Tensor Flow job. :type tensor_flow_settings: ~batch_ai.models.TensorFlowSettings :param caffe_settings: Settings for Caffe job. :type caffe_settings: ~batch_ai.models.CaffeSettings :param caffe2_settings: Settings for Caffe2 job. :type caffe2_settings: ~batch_ai.models.Caffe2Settings :param chainer_settings: Settings for Chainer job. :type chainer_settings: ~batch_ai.models.ChainerSettings :param custom_toolkit_settings: Settings for custom tool kit job. :type custom_toolkit_settings: ~batch_ai.models.CustomToolkitSettings :param custom_mpi_settings: Settings for custom MPI job. :type custom_mpi_settings: ~batch_ai.models.CustomMpiSettings :param horovod_settings: Settings for Horovod job. :type horovod_settings: ~batch_ai.models.HorovodSettings :param job_preparation: A command line to be executed on each node allocated for the job before tool kit is launched. :type job_preparation: ~batch_ai.models.JobPreparation :param std_out_err_path_prefix: The path where the Batch AI service will store stdout, stderror and execution log of the job. :type std_out_err_path_prefix: str :param input_directories: A list of input directories for the job. :type input_directories: list[~batch_ai.models.InputDirectory] :param output_directories: A list of output directories for the job. :type output_directories: list[~batch_ai.models.OutputDirectory] :param environment_variables: A list of user defined environment variables which will be setup for the job. :type environment_variables: list[~batch_ai.models.EnvironmentVariable] :param secrets: A list of user defined environment variables with secret values which will be setup for the job. Server will never report values of these variables back. :type secrets: list[~batch_ai.models.EnvironmentVariableWithSecretValue] :param constraints: Constraints associated with the Job. :type constraints: ~batch_ai.models.JobBasePropertiesConstraints """ _attribute_map = { 'scheduling_priority': {'key': 'properties.schedulingPriority', 'type': 'str'}, 'cluster': {'key': 'properties.cluster', 'type': 'ResourceId'}, 'mount_volumes': {'key': 'properties.mountVolumes', 'type': 'MountVolumes'}, 'node_count': {'key': 'properties.nodeCount', 'type': 'int'}, 'container_settings': {'key': 'properties.containerSettings', 'type': 'ContainerSettings'}, 'cntk_settings': {'key': 'properties.cntkSettings', 'type': 'CNTKsettings'}, 'py_torch_settings': {'key': 'properties.pyTorchSettings', 'type': 'PyTorchSettings'}, 'tensor_flow_settings': {'key': 'properties.tensorFlowSettings', 'type': 'TensorFlowSettings'}, 'caffe_settings': {'key': 'properties.caffeSettings', 'type': 'CaffeSettings'}, 'caffe2_settings': {'key': 'properties.caffe2Settings', 'type': 'Caffe2Settings'}, 'chainer_settings': {'key': 'properties.chainerSettings', 'type': 'ChainerSettings'}, 'custom_toolkit_settings': {'key': 'properties.customToolkitSettings', 'type': 'CustomToolkitSettings'}, 'custom_mpi_settings': {'key': 'properties.customMpiSettings', 'type': 'CustomMpiSettings'}, 'horovod_settings': {'key': 'properties.horovodSettings', 'type': 'HorovodSettings'}, 'job_preparation': {'key': 'properties.jobPreparation', 'type': 'JobPreparation'}, 'std_out_err_path_prefix': {'key': 'properties.stdOutErrPathPrefix', 'type': 'str'}, 'input_directories': {'key': 'properties.inputDirectories', 'type': '[InputDirectory]'}, 'output_directories': {'key': 'properties.outputDirectories', 'type': '[OutputDirectory]'}, 'environment_variables': {'key': 'properties.environmentVariables', 'type': '[EnvironmentVariable]'}, 'secrets': {'key': 'properties.secrets', 'type': '[EnvironmentVariableWithSecretValue]'}, 'constraints': {'key': 'properties.constraints', 'type': 'JobBasePropertiesConstraints'}, } def __init__( self, **kwargs ): super(JobCreateParameters, self).__init__(**kwargs) self.scheduling_priority = kwargs.get('scheduling_priority', None) self.cluster = kwargs.get('cluster', None) self.mount_volumes = kwargs.get('mount_volumes', None) self.node_count = kwargs.get('node_count', None) self.container_settings = kwargs.get('container_settings', None) self.cntk_settings = kwargs.get('cntk_settings', None) self.py_torch_settings = kwargs.get('py_torch_settings', None) self.tensor_flow_settings = kwargs.get('tensor_flow_settings', None) self.caffe_settings = kwargs.get('caffe_settings', None) self.caffe2_settings = kwargs.get('caffe2_settings', None) self.chainer_settings = kwargs.get('chainer_settings', None) self.custom_toolkit_settings = kwargs.get('custom_toolkit_settings', None) self.custom_mpi_settings = kwargs.get('custom_mpi_settings', None) self.horovod_settings = kwargs.get('horovod_settings', None) self.job_preparation = kwargs.get('job_preparation', None) self.std_out_err_path_prefix = kwargs.get('std_out_err_path_prefix', None) self.input_directories = kwargs.get('input_directories', None) self.output_directories = kwargs.get('output_directories', None) self.environment_variables = kwargs.get('environment_variables', None) self.secrets = kwargs.get('secrets', None) self.constraints = kwargs.get('constraints', None) class JobListResult(msrest.serialization.Model): """Values returned by the List operation. Variables are only populated by the server, and will be ignored when sending a request. :ivar value: The collection of jobs. :vartype value: list[~batch_ai.models.Job] :ivar next_link: The continuation token. :vartype next_link: str """ _validation = { 'value': {'readonly': True}, 'next_link': {'readonly': True}, } _attribute_map = { 'value': {'key': 'value', 'type': '[Job]'}, 'next_link': {'key': 'nextLink', 'type': 'str'}, } def __init__( self, **kwargs ): super(JobListResult, self).__init__(**kwargs) self.value = None self.next_link = None class JobPreparation(msrest.serialization.Model): """Job preparation settings. All required parameters must be populated in order to send to Azure. :param command_line: Required. The command line to execute. If containerSettings is specified on the job, this commandLine will be executed in the same container as job. Otherwise it will be executed on the node. :type command_line: str """ _validation = { 'command_line': {'required': True}, } _attribute_map = { 'command_line': {'key': 'commandLine', 'type': 'str'}, } def __init__( self, **kwargs ): super(JobPreparation, self).__init__(**kwargs) self.command_line = kwargs['command_line'] class JobPropertiesConstraints(msrest.serialization.Model): """Constraints associated with the Job. :param max_wall_clock_time: Max time the job can run. Default value: 1 week. :type max_wall_clock_time: ~datetime.timedelta """ _attribute_map = { 'max_wall_clock_time': {'key': 'maxWallClockTime', 'type': 'duration'}, } def __init__( self, **kwargs ): super(JobPropertiesConstraints, self).__init__(**kwargs) self.max_wall_clock_time = kwargs.get('max_wall_clock_time', "7.00:00:00") class JobPropertiesExecutionInfo(msrest.serialization.Model): """Information about the execution of a job. Variables are only populated by the server, and will be ignored when sending a request. :ivar start_time: The time at which the job started running. 'Running' corresponds to the running state. If the job has been restarted or retried, this is the most recent time at which the job started running. This property is present only for job that are in the running or completed state. :vartype start_time: ~datetime.datetime :ivar end_time: The time at which the job completed. This property is only returned if the job is in completed state. :vartype end_time: ~datetime.datetime :ivar exit_code: The exit code of the job. This property is only returned if the job is in completed state. :vartype exit_code: int :ivar errors: A collection of errors encountered by the service during job execution. :vartype errors: list[~batch_ai.models.BatchAIError] """ _validation = { 'start_time': {'readonly': True}, 'end_time': {'readonly': True}, 'exit_code': {'readonly': True}, 'errors': {'readonly': True}, } _attribute_map = { 'start_time': {'key': 'startTime', 'type': 'iso-8601'}, 'end_time': {'key': 'endTime', 'type': 'iso-8601'}, 'exit_code': {'key': 'exitCode', 'type': 'int'}, 'errors': {'key': 'errors', 'type': '[BatchAIError]'}, } def __init__( self, **kwargs ): super(JobPropertiesExecutionInfo, self).__init__(**kwargs) self.start_time = None self.end_time = None self.exit_code = None self.errors = None class JobsListByExperimentOptions(msrest.serialization.Model): """Parameter group. :param max_results: The maximum number of items to return in the response. A maximum of 1000 files can be returned. :type max_results: int """ _validation = { 'max_results': {'maximum': 1000, 'minimum': 1}, } _attribute_map = { 'max_results': {'key': 'maxResults', 'type': 'int'}, } def __init__( self, **kwargs ): super(JobsListByExperimentOptions, self).__init__(**kwargs) self.max_results = kwargs.get('max_results', 1000) class JobsListOutputFilesOptions(msrest.serialization.Model): """Parameter group. All required parameters must be populated in order to send to Azure. :param outputdirectoryid: Required. Id of the job output directory. This is the OutputDirectory-->id parameter that is given by the user during Create Job. :type outputdirectoryid: str :param directory: The path to the directory. :type directory: str :param linkexpiryinminutes: The number of minutes after which the download link will expire. :type linkexpiryinminutes: int :param max_results: The maximum number of items to return in the response. A maximum of 1000 files can be returned. :type max_results: int """ _validation = { 'outputdirectoryid': {'required': True}, 'linkexpiryinminutes': {'maximum': 600, 'minimum': 5}, 'max_results': {'maximum': 1000, 'minimum': 1}, } _attribute_map = { 'outputdirectoryid': {'key': 'outputdirectoryid', 'type': 'str'}, 'directory': {'key': 'directory', 'type': 'str'}, 'linkexpiryinminutes': {'key': 'linkexpiryinminutes', 'type': 'int'}, 'max_results': {'key': 'maxResults', 'type': 'int'}, } def __init__( self, **kwargs ): super(JobsListOutputFilesOptions, self).__init__(**kwargs) self.outputdirectoryid = kwargs['outputdirectoryid'] self.directory = kwargs.get('directory', ".") self.linkexpiryinminutes = kwargs.get('linkexpiryinminutes', 60) self.max_results = kwargs.get('max_results', 1000) class KeyVaultSecretReference(msrest.serialization.Model): """Key Vault Secret reference. All required parameters must be populated in order to send to Azure. :param source_vault: Required. Fully qualified resource identifier of the Key Vault. :type source_vault: ~batch_ai.models.ResourceId :param secret_url: Required. The URL referencing a secret in the Key Vault. :type secret_url: str """ _validation = { 'source_vault': {'required': True}, 'secret_url': {'required': True}, } _attribute_map = { 'source_vault': {'key': 'sourceVault', 'type': 'ResourceId'}, 'secret_url': {'key': 'secretUrl', 'type': 'str'}, } def __init__( self, **kwargs ): super(KeyVaultSecretReference, self).__init__(**kwargs) self.source_vault = kwargs['source_vault'] self.secret_url = kwargs['secret_url'] class ListUsagesResult(msrest.serialization.Model): """The List Usages operation response. Variables are only populated by the server, and will be ignored when sending a request. :ivar value: The list of compute resource usages. :vartype value: list[~batch_ai.models.Usage] :ivar next_link: The URI to fetch the next page of compute resource usage information. Call ListNext() with this to fetch the next page of compute resource usage information. :vartype next_link: str """ _validation = { 'value': {'readonly': True}, 'next_link': {'readonly': True}, } _attribute_map = { 'value': {'key': 'value', 'type': '[Usage]'}, 'next_link': {'key': 'nextLink', 'type': 'str'}, } def __init__( self, **kwargs ): super(ListUsagesResult, self).__init__(**kwargs) self.value = None self.next_link = None class ManualScaleSettings(msrest.serialization.Model): """Manual scale settings for the cluster. All required parameters must be populated in order to send to Azure. :param target_node_count: Required. The desired number of compute nodes in the Cluster. Default is 0. :type target_node_count: int :param node_deallocation_option: An action to be performed when the cluster size is decreasing. The default value is requeue. Possible values include: "requeue", "terminate", "waitforjobcompletion". Default value: "requeue". :type node_deallocation_option: str or ~batch_ai.models.DeallocationOption """ _validation = { 'target_node_count': {'required': True}, } _attribute_map = { 'target_node_count': {'key': 'targetNodeCount', 'type': 'int'}, 'node_deallocation_option': {'key': 'nodeDeallocationOption', 'type': 'str'}, } def __init__( self, **kwargs ): super(ManualScaleSettings, self).__init__(**kwargs) self.target_node_count = kwargs['target_node_count'] self.node_deallocation_option = kwargs.get('node_deallocation_option', "requeue") class MountSettings(msrest.serialization.Model): """File Server mount Information. :param mount_point: Path where the data disks are mounted on the File Server. :type mount_point: str :param file_server_public_ip: Public IP address of the File Server which can be used to SSH to the node from outside of the subnet. :type file_server_public_ip: str :param file_server_internal_ip: Internal IP address of the File Server which can be used to access the File Server from within the subnet. :type file_server_internal_ip: str """ _attribute_map = { 'mount_point': {'key': 'mountPoint', 'type': 'str'}, 'file_server_public_ip': {'key': 'fileServerPublicIP', 'type': 'str'}, 'file_server_internal_ip': {'key': 'fileServerInternalIP', 'type': 'str'}, } def __init__( self, **kwargs ): super(MountSettings, self).__init__(**kwargs) self.mount_point = kwargs.get('mount_point', None) self.file_server_public_ip = kwargs.get('file_server_public_ip', None) self.file_server_internal_ip = kwargs.get('file_server_internal_ip', None) class MountVolumes(msrest.serialization.Model): """Details of volumes to mount on the cluster. :param azure_file_shares: A collection of Azure File Shares that are to be mounted to the cluster nodes. :type azure_file_shares: list[~batch_ai.models.AzureFileShareReference] :param azure_blob_file_systems: A collection of Azure Blob Containers that are to be mounted to the cluster nodes. :type azure_blob_file_systems: list[~batch_ai.models.AzureBlobFileSystemReference] :param file_servers: A collection of Batch AI File Servers that are to be mounted to the cluster nodes. :type file_servers: list[~batch_ai.models.FileServerReference] :param unmanaged_file_systems: A collection of unmanaged file systems that are to be mounted to the cluster nodes. :type unmanaged_file_systems: list[~batch_ai.models.UnmanagedFileSystemReference] """ _attribute_map = { 'azure_file_shares': {'key': 'azureFileShares', 'type': '[AzureFileShareReference]'}, 'azure_blob_file_systems': {'key': 'azureBlobFileSystems', 'type': '[AzureBlobFileSystemReference]'}, 'file_servers': {'key': 'fileServers', 'type': '[FileServerReference]'}, 'unmanaged_file_systems': {'key': 'unmanagedFileSystems', 'type': '[UnmanagedFileSystemReference]'}, } def __init__( self, **kwargs ): super(MountVolumes, self).__init__(**kwargs) self.azure_file_shares = kwargs.get('azure_file_shares', None) self.azure_blob_file_systems = kwargs.get('azure_blob_file_systems', None) self.file_servers = kwargs.get('file_servers', None) self.unmanaged_file_systems = kwargs.get('unmanaged_file_systems', None) class NameValuePair(msrest.serialization.Model): """Name-value pair. :param name: The name in the name-value pair. :type name: str :param value: The value in the name-value pair. :type value: str """ _attribute_map = { 'name': {'key': 'name', 'type': 'str'}, 'value': {'key': 'value', 'type': 'str'}, } def __init__( self, **kwargs ): super(NameValuePair, self).__init__(**kwargs) self.name = kwargs.get('name', None) self.value = kwargs.get('value', None) class NodeSetup(msrest.serialization.Model): """Node setup settings. :param setup_task: Setup task to run on cluster nodes when nodes got created or rebooted. The setup task code needs to be idempotent. Generally the setup task is used to download static data that is required for all jobs that run on the cluster VMs and/or to download/install software. :type setup_task: ~batch_ai.models.SetupTask :param mount_volumes: Mount volumes to be available to setup task and all jobs executing on the cluster. The volumes will be mounted at location specified by $AZ_BATCHAI_MOUNT_ROOT environment variable. :type mount_volumes: ~batch_ai.models.MountVolumes :param performance_counters_settings: Settings for performance counters collecting and uploading. :type performance_counters_settings: ~batch_ai.models.PerformanceCountersSettings """ _attribute_map = { 'setup_task': {'key': 'setupTask', 'type': 'SetupTask'}, 'mount_volumes': {'key': 'mountVolumes', 'type': 'MountVolumes'}, 'performance_counters_settings': {'key': 'performanceCountersSettings', 'type': 'PerformanceCountersSettings'}, } def __init__( self, **kwargs ): super(NodeSetup, self).__init__(**kwargs) self.setup_task = kwargs.get('setup_task', None) self.mount_volumes = kwargs.get('mount_volumes', None) self.performance_counters_settings = kwargs.get('performance_counters_settings', None) class NodeStateCounts(msrest.serialization.Model): """Counts of various compute node states on the cluster. Variables are only populated by the server, and will be ignored when sending a request. :ivar idle_node_count: Number of compute nodes in idle state. :vartype idle_node_count: int :ivar running_node_count: Number of compute nodes which are running jobs. :vartype running_node_count: int :ivar preparing_node_count: Number of compute nodes which are being prepared. :vartype preparing_node_count: int :ivar unusable_node_count: Number of compute nodes which are in unusable state. :vartype unusable_node_count: int :ivar leaving_node_count: Number of compute nodes which are leaving the cluster. :vartype leaving_node_count: int """ _validation = { 'idle_node_count': {'readonly': True}, 'running_node_count': {'readonly': True}, 'preparing_node_count': {'readonly': True}, 'unusable_node_count': {'readonly': True}, 'leaving_node_count': {'readonly': True}, } _attribute_map = { 'idle_node_count': {'key': 'idleNodeCount', 'type': 'int'}, 'running_node_count': {'key': 'runningNodeCount', 'type': 'int'}, 'preparing_node_count': {'key': 'preparingNodeCount', 'type': 'int'}, 'unusable_node_count': {'key': 'unusableNodeCount', 'type': 'int'}, 'leaving_node_count': {'key': 'leavingNodeCount', 'type': 'int'}, } def __init__( self, **kwargs ): super(NodeStateCounts, self).__init__(**kwargs) self.idle_node_count = None self.running_node_count = None self.preparing_node_count = None self.unusable_node_count = None self.leaving_node_count = None class Operation(msrest.serialization.Model): """Details of a REST API operation. Variables are only populated by the server, and will be ignored when sending a request. :ivar name: This is of the format {provider}/{resource}/{operation}. :vartype name: str :param display: The object that describes the operation. :type display: ~batch_ai.models.OperationDisplay :ivar origin: The intended executor of the operation. :vartype origin: str :param properties: Any object. :type properties: any """ _validation = { 'name': {'readonly': True}, 'origin': {'readonly': True}, } _attribute_map = { 'name': {'key': 'name', 'type': 'str'}, 'display': {'key': 'display', 'type': 'OperationDisplay'}, 'origin': {'key': 'origin', 'type': 'str'}, 'properties': {'key': 'properties', 'type': 'object'}, } def __init__( self, **kwargs ): super(Operation, self).__init__(**kwargs) self.name = None self.display = kwargs.get('display', None) self.origin = None self.properties = kwargs.get('properties', None) class OperationDisplay(msrest.serialization.Model): """The object that describes the operation. Variables are only populated by the server, and will be ignored when sending a request. :ivar provider: Friendly name of the resource provider. :vartype provider: str :ivar operation: For example: read, write, delete, or listKeys/action. :vartype operation: str :ivar resource: The resource type on which the operation is performed. :vartype resource: str :ivar description: The friendly name of the operation. :vartype description: str """ _validation = { 'provider': {'readonly': True}, 'operation': {'readonly': True}, 'resource': {'readonly': True}, 'description': {'readonly': True}, } _attribute_map = { 'provider': {'key': 'provider', 'type': 'str'}, 'operation': {'key': 'operation', 'type': 'str'}, 'resource': {'key': 'resource', 'type': 'str'}, 'description': {'key': 'description', 'type': 'str'}, } def __init__( self, **kwargs ): super(OperationDisplay, self).__init__(**kwargs) self.provider = None self.operation = None self.resource = None self.description = None class OperationListResult(msrest.serialization.Model): """Contains the list of all operations supported by BatchAI resource provider. Variables are only populated by the server, and will be ignored when sending a request. :ivar value: The list of operations supported by the resource provider. :vartype value: list[~batch_ai.models.Operation] :ivar next_link: The URL to get the next set of operation list results if there are any. :vartype next_link: str """ _validation = { 'value': {'readonly': True}, 'next_link': {'readonly': True}, } _attribute_map = { 'value': {'key': 'value', 'type': '[Operation]'}, 'next_link': {'key': 'nextLink', 'type': 'str'}, } def __init__( self, **kwargs ): super(OperationListResult, self).__init__(**kwargs) self.value = None self.next_link = None class OutputDirectory(msrest.serialization.Model): """Output directory for the job. All required parameters must be populated in order to send to Azure. :param id: Required. The ID of the output directory. The job can use AZ_BATCHAI\ *OUTPUT*\ :code:`<id>` environment variable to find the directory path, where :code:`<id>` is the value of id attribute. :type id: str :param path_prefix: Required. The prefix path where the output directory will be created. Note, this is an absolute path to prefix. E.g. $AZ_BATCHAI_MOUNT_ROOT/MyNFS/MyLogs. The full path to the output directory by combining pathPrefix, jobOutputDirectoryPathSegment (reported by get job) and pathSuffix. :type path_prefix: str :param path_suffix: The suffix path where the output directory will be created. E.g. models. You can find the full path to the output directory by combining pathPrefix, jobOutputDirectoryPathSegment (reported by get job) and pathSuffix. :type path_suffix: str """ _validation = { 'id': {'required': True}, 'path_prefix': {'required': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'path_prefix': {'key': 'pathPrefix', 'type': 'str'}, 'path_suffix': {'key': 'pathSuffix', 'type': 'str'}, } def __init__( self, **kwargs ): super(OutputDirectory, self).__init__(**kwargs) self.id = kwargs['id'] self.path_prefix = kwargs['path_prefix'] self.path_suffix = kwargs.get('path_suffix', None) class PerformanceCountersSettings(msrest.serialization.Model): """Performance counters reporting settings. All required parameters must be populated in order to send to Azure. :param app_insights_reference: Required. Azure Application Insights information for performance counters reporting. If provided, Batch AI will upload node performance counters to the corresponding Azure Application Insights account. :type app_insights_reference: ~batch_ai.models.AppInsightsReference """ _validation = { 'app_insights_reference': {'required': True}, } _attribute_map = { 'app_insights_reference': {'key': 'appInsightsReference', 'type': 'AppInsightsReference'}, } def __init__( self, **kwargs ): super(PerformanceCountersSettings, self).__init__(**kwargs) self.app_insights_reference = kwargs['app_insights_reference'] class PrivateRegistryCredentials(msrest.serialization.Model): """Credentials to access a container image in a private repository. All required parameters must be populated in order to send to Azure. :param username: Required. User name to login to the repository. :type username: str :param password: User password to login to the docker repository. One of password or passwordSecretReference must be specified. :type password: str :param password_secret_reference: KeyVault Secret storing the password. Users can store their secrets in Azure KeyVault and pass it to the Batch AI service to integrate with KeyVault. One of password or passwordSecretReference must be specified. :type password_secret_reference: ~batch_ai.models.KeyVaultSecretReference """ _validation = { 'username': {'required': True}, } _attribute_map = { 'username': {'key': 'username', 'type': 'str'}, 'password': {'key': 'password', 'type': 'str'}, 'password_secret_reference': {'key': 'passwordSecretReference', 'type': 'KeyVaultSecretReference'}, } def __init__( self, **kwargs ): super(PrivateRegistryCredentials, self).__init__(**kwargs) self.username = kwargs['username'] self.password = kwargs.get('password', None) self.password_secret_reference = kwargs.get('password_secret_reference', None) class PyTorchSettings(msrest.serialization.Model): """pyTorch job settings. All required parameters must be populated in order to send to Azure. :param python_script_file_path: Required. The python script to execute. :type python_script_file_path: str :param python_interpreter_path: The path to the Python interpreter. :type python_interpreter_path: str :param command_line_args: Command line arguments that need to be passed to the python script. :type command_line_args: str :param process_count: Number of processes to launch for the job execution. The default value for this property is equal to nodeCount property. :type process_count: int :param communication_backend: Type of the communication backend for distributed jobs. Valid values are 'TCP', 'Gloo' or 'MPI'. Not required for non-distributed jobs. :type communication_backend: str """ _validation = { 'python_script_file_path': {'required': True}, } _attribute_map = { 'python_script_file_path': {'key': 'pythonScriptFilePath', 'type': 'str'}, 'python_interpreter_path': {'key': 'pythonInterpreterPath', 'type': 'str'}, 'command_line_args': {'key': 'commandLineArgs', 'type': 'str'}, 'process_count': {'key': 'processCount', 'type': 'int'}, 'communication_backend': {'key': 'communicationBackend', 'type': 'str'}, } def __init__( self, **kwargs ): super(PyTorchSettings, self).__init__(**kwargs) self.python_script_file_path = kwargs['python_script_file_path'] self.python_interpreter_path = kwargs.get('python_interpreter_path', None) self.command_line_args = kwargs.get('command_line_args', None) self.process_count = kwargs.get('process_count', None) self.communication_backend = kwargs.get('communication_backend', None) class RemoteLoginInformation(msrest.serialization.Model): """Login details to SSH to a compute node in cluster. Variables are only populated by the server, and will be ignored when sending a request. :ivar node_id: ID of the compute node. :vartype node_id: str :ivar ip_address: Public IP address of the compute node. :vartype ip_address: str :ivar port: SSH port number of the node. :vartype port: int """ _validation = { 'node_id': {'readonly': True}, 'ip_address': {'readonly': True}, 'port': {'readonly': True}, } _attribute_map = { 'node_id': {'key': 'nodeId', 'type': 'str'}, 'ip_address': {'key': 'ipAddress', 'type': 'str'}, 'port': {'key': 'port', 'type': 'int'}, } def __init__( self, **kwargs ): super(RemoteLoginInformation, self).__init__(**kwargs) self.node_id = None self.ip_address = None self.port = None class RemoteLoginInformationListResult(msrest.serialization.Model): """Values returned by the List operation. Variables are only populated by the server, and will be ignored when sending a request. :ivar value: The collection of returned remote login details. :vartype value: list[~batch_ai.models.RemoteLoginInformation] :ivar next_link: The continuation token. :vartype next_link: str """ _validation = { 'value': {'readonly': True}, 'next_link': {'readonly': True}, } _attribute_map = { 'value': {'key': 'value', 'type': '[RemoteLoginInformation]'}, 'next_link': {'key': 'nextLink', 'type': 'str'}, } def __init__( self, **kwargs ): super(RemoteLoginInformationListResult, self).__init__(**kwargs) self.value = None self.next_link = None class Resource(msrest.serialization.Model): """A definition of an Azure resource. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: The ID of the resource. :vartype id: str :ivar name: The name of the resource. :vartype name: str :ivar type: The type of the resource. :vartype type: str :ivar location: The location of the resource. :vartype location: str :ivar tags: A set of tags. The tags of the resource. :vartype tags: dict[str, str] """ _validation = { 'id': {'readonly': True}, 'name': {'readonly': True}, 'type': {'readonly': True}, 'location': {'readonly': True}, 'tags': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'location': {'key': 'location', 'type': 'str'}, 'tags': {'key': 'tags', 'type': '{str}'}, } def __init__( self, **kwargs ): super(Resource, self).__init__(**kwargs) self.id = None self.name = None self.type = None self.location = None self.tags = None class ResourceId(msrest.serialization.Model): """Represents a resource ID. For example, for a subnet, it is the resource URL for the subnet. All required parameters must be populated in order to send to Azure. :param id: Required. The ID of the resource. :type id: str """ _validation = { 'id': {'required': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, } def __init__( self, **kwargs ): super(ResourceId, self).__init__(**kwargs) self.id = kwargs['id'] class ScaleSettings(msrest.serialization.Model): """At least one of manual or autoScale settings must be specified. Only one of manual or autoScale settings can be specified. If autoScale settings are specified, the system automatically scales the cluster up and down (within the supplied limits) based on the pending jobs on the cluster. :param manual: Manual scale settings for the cluster. :type manual: ~batch_ai.models.ManualScaleSettings :param auto_scale: Auto-scale settings for the cluster. :type auto_scale: ~batch_ai.models.AutoScaleSettings """ _attribute_map = { 'manual': {'key': 'manual', 'type': 'ManualScaleSettings'}, 'auto_scale': {'key': 'autoScale', 'type': 'AutoScaleSettings'}, } def __init__( self, **kwargs ): super(ScaleSettings, self).__init__(**kwargs) self.manual = kwargs.get('manual', None) self.auto_scale = kwargs.get('auto_scale', None) class SetupTask(msrest.serialization.Model): """Specifies a setup task which can be used to customize the compute nodes of the cluster. Variables are only populated by the server, and will be ignored when sending a request. All required parameters must be populated in order to send to Azure. :param command_line: Required. The command line to be executed on each cluster's node after it being allocated or rebooted. The command is executed in a bash subshell as a root. :type command_line: str :param environment_variables: A collection of user defined environment variables to be set for setup task. :type environment_variables: list[~batch_ai.models.EnvironmentVariable] :param secrets: A collection of user defined environment variables with secret values to be set for the setup task. Server will never report values of these variables back. :type secrets: list[~batch_ai.models.EnvironmentVariableWithSecretValue] :param std_out_err_path_prefix: Required. The prefix of a path where the Batch AI service will upload the stdout, stderr and execution log of the setup task. :type std_out_err_path_prefix: str :ivar std_out_err_path_suffix: A path segment appended by Batch AI to stdOutErrPathPrefix to form a path where stdout, stderr and execution log of the setup task will be uploaded. Batch AI creates the setup task output directories under an unique path to avoid conflicts between different clusters. The full path can be obtained by concatenation of stdOutErrPathPrefix and stdOutErrPathSuffix. :vartype std_out_err_path_suffix: str """ _validation = { 'command_line': {'required': True}, 'std_out_err_path_prefix': {'required': True}, 'std_out_err_path_suffix': {'readonly': True}, } _attribute_map = { 'command_line': {'key': 'commandLine', 'type': 'str'}, 'environment_variables': {'key': 'environmentVariables', 'type': '[EnvironmentVariable]'}, 'secrets': {'key': 'secrets', 'type': '[EnvironmentVariableWithSecretValue]'}, 'std_out_err_path_prefix': {'key': 'stdOutErrPathPrefix', 'type': 'str'}, 'std_out_err_path_suffix': {'key': 'stdOutErrPathSuffix', 'type': 'str'}, } def __init__( self, **kwargs ): super(SetupTask, self).__init__(**kwargs) self.command_line = kwargs['command_line'] self.environment_variables = kwargs.get('environment_variables', None) self.secrets = kwargs.get('secrets', None) self.std_out_err_path_prefix = kwargs['std_out_err_path_prefix'] self.std_out_err_path_suffix = None class SshConfiguration(msrest.serialization.Model): """SSH configuration. All required parameters must be populated in order to send to Azure. :param public_ips_to_allow: List of source IP ranges to allow SSH connection from. The default value is '*' (all source IPs are allowed). Maximum number of IP ranges that can be specified is 400. :type public_ips_to_allow: list[str] :param user_account_settings: Required. Settings for administrator user account to be created on a node. The account can be used to establish SSH connection to the node. :type user_account_settings: ~batch_ai.models.UserAccountSettings """ _validation = { 'user_account_settings': {'required': True}, } _attribute_map = { 'public_ips_to_allow': {'key': 'publicIPsToAllow', 'type': '[str]'}, 'user_account_settings': {'key': 'userAccountSettings', 'type': 'UserAccountSettings'}, } def __init__( self, **kwargs ): super(SshConfiguration, self).__init__(**kwargs) self.public_ips_to_allow = kwargs.get('public_ips_to_allow', None) self.user_account_settings = kwargs['user_account_settings'] class TensorFlowSettings(msrest.serialization.Model): """TensorFlow job settings. All required parameters must be populated in order to send to Azure. :param python_script_file_path: Required. The python script to execute. :type python_script_file_path: str :param python_interpreter_path: The path to the Python interpreter. :type python_interpreter_path: str :param master_command_line_args: Command line arguments that need to be passed to the python script for the master task. :type master_command_line_args: str :param worker_command_line_args: Command line arguments that need to be passed to the python script for the worker task. Optional for single process jobs. :type worker_command_line_args: str :param parameter_server_command_line_args: Command line arguments that need to be passed to the python script for the parameter server. Optional for single process jobs. :type parameter_server_command_line_args: str :param worker_count: The number of worker tasks. If specified, the value must be less than or equal to (nodeCount * numberOfGPUs per VM). If not specified, the default value is equal to nodeCount. This property can be specified only for distributed TensorFlow training. :type worker_count: int :param parameter_server_count: The number of parameter server tasks. If specified, the value must be less than or equal to nodeCount. If not specified, the default value is equal to 1 for distributed TensorFlow training. This property can be specified only for distributed TensorFlow training. :type parameter_server_count: int """ _validation = { 'python_script_file_path': {'required': True}, } _attribute_map = { 'python_script_file_path': {'key': 'pythonScriptFilePath', 'type': 'str'}, 'python_interpreter_path': {'key': 'pythonInterpreterPath', 'type': 'str'}, 'master_command_line_args': {'key': 'masterCommandLineArgs', 'type': 'str'}, 'worker_command_line_args': {'key': 'workerCommandLineArgs', 'type': 'str'}, 'parameter_server_command_line_args': {'key': 'parameterServerCommandLineArgs', 'type': 'str'}, 'worker_count': {'key': 'workerCount', 'type': 'int'}, 'parameter_server_count': {'key': 'parameterServerCount', 'type': 'int'}, } def __init__( self, **kwargs ): super(TensorFlowSettings, self).__init__(**kwargs) self.python_script_file_path = kwargs['python_script_file_path'] self.python_interpreter_path = kwargs.get('python_interpreter_path', None) self.master_command_line_args = kwargs.get('master_command_line_args', None) self.worker_command_line_args = kwargs.get('worker_command_line_args', None) self.parameter_server_command_line_args = kwargs.get('parameter_server_command_line_args', None) self.worker_count = kwargs.get('worker_count', None) self.parameter_server_count = kwargs.get('parameter_server_count', None) class UnmanagedFileSystemReference(msrest.serialization.Model): """Unmanaged file system mounting configuration. All required parameters must be populated in order to send to Azure. :param mount_command: Required. Mount command line. Note, Batch AI will append mount path to the command on its own. :type mount_command: str :param relative_mount_path: Required. The relative path on the compute node where the unmanaged file system will be mounted. Note that all cluster level unmanaged file systems will be mounted under $AZ_BATCHAI_MOUNT_ROOT location and all job level unmanaged file systems will be mounted under $AZ_BATCHAI_JOB_MOUNT_ROOT. :type relative_mount_path: str """ _validation = { 'mount_command': {'required': True}, 'relative_mount_path': {'required': True}, } _attribute_map = { 'mount_command': {'key': 'mountCommand', 'type': 'str'}, 'relative_mount_path': {'key': 'relativeMountPath', 'type': 'str'}, } def __init__( self, **kwargs ): super(UnmanagedFileSystemReference, self).__init__(**kwargs) self.mount_command = kwargs['mount_command'] self.relative_mount_path = kwargs['relative_mount_path'] class Usage(msrest.serialization.Model): """Describes Batch AI Resource Usage. Variables are only populated by the server, and will be ignored when sending a request. :ivar unit: An enum describing the unit of usage measurement. Possible values include: "Count". :vartype unit: str or ~batch_ai.models.UsageUnit :ivar current_value: The current usage of the resource. :vartype current_value: int :ivar limit: The maximum permitted usage of the resource. :vartype limit: long :ivar name: The name of the type of usage. :vartype name: ~batch_ai.models.UsageName """ _validation = { 'unit': {'readonly': True}, 'current_value': {'readonly': True}, 'limit': {'readonly': True}, 'name': {'readonly': True}, } _attribute_map = { 'unit': {'key': 'unit', 'type': 'str'}, 'current_value': {'key': 'currentValue', 'type': 'int'}, 'limit': {'key': 'limit', 'type': 'long'}, 'name': {'key': 'name', 'type': 'UsageName'}, } def __init__( self, **kwargs ): super(Usage, self).__init__(**kwargs) self.unit = None self.current_value = None self.limit = None self.name = None class UsageName(msrest.serialization.Model): """The Usage Names. Variables are only populated by the server, and will be ignored when sending a request. :ivar value: The name of the resource. :vartype value: str :ivar localized_value: The localized name of the resource. :vartype localized_value: str """ _validation = { 'value': {'readonly': True}, 'localized_value': {'readonly': True}, } _attribute_map = { 'value': {'key': 'value', 'type': 'str'}, 'localized_value': {'key': 'localizedValue', 'type': 'str'}, } def __init__( self, **kwargs ): super(UsageName, self).__init__(**kwargs) self.value = None self.localized_value = None class UserAccountSettings(msrest.serialization.Model): """Settings for user account that gets created on each on the nodes of a cluster. All required parameters must be populated in order to send to Azure. :param admin_user_name: Required. Name of the administrator user account which can be used to SSH to nodes. :type admin_user_name: str :param admin_user_ssh_public_key: SSH public key of the administrator user account. :type admin_user_ssh_public_key: str :param admin_user_password: Password of the administrator user account. :type admin_user_password: str """ _validation = { 'admin_user_name': {'required': True}, } _attribute_map = { 'admin_user_name': {'key': 'adminUserName', 'type': 'str'}, 'admin_user_ssh_public_key': {'key': 'adminUserSshPublicKey', 'type': 'str'}, 'admin_user_password': {'key': 'adminUserPassword', 'type': 'str'}, } def __init__( self, **kwargs ): super(UserAccountSettings, self).__init__(**kwargs) self.admin_user_name = kwargs['admin_user_name'] self.admin_user_ssh_public_key = kwargs.get('admin_user_ssh_public_key', None) self.admin_user_password = kwargs.get('admin_user_password', None) class VirtualMachineConfiguration(msrest.serialization.Model): """VM configuration. :param image_reference: OS image reference for cluster nodes. :type image_reference: ~batch_ai.models.ImageReference """ _attribute_map = { 'image_reference': {'key': 'imageReference', 'type': 'ImageReference'}, } def __init__( self, **kwargs ): super(VirtualMachineConfiguration, self).__init__(**kwargs) self.image_reference = kwargs.get('image_reference', None) class Workspace(Resource): """Batch AI Workspace information. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: The ID of the resource. :vartype id: str :ivar name: The name of the resource. :vartype name: str :ivar type: The type of the resource. :vartype type: str :ivar location: The location of the resource. :vartype location: str :ivar tags: A set of tags. The tags of the resource. :vartype tags: dict[str, str] :ivar creation_time: Time when the Workspace was created. :vartype creation_time: ~datetime.datetime :ivar provisioning_state: The provisioned state of the Workspace. Possible values include: "creating", "succeeded", "failed", "deleting". :vartype provisioning_state: str or ~batch_ai.models.ProvisioningState :ivar provisioning_state_transition_time: The time at which the workspace entered its current provisioning state. :vartype provisioning_state_transition_time: ~datetime.datetime """ _validation = { 'id': {'readonly': True}, 'name': {'readonly': True}, 'type': {'readonly': True}, 'location': {'readonly': True}, 'tags': {'readonly': True}, 'creation_time': {'readonly': True}, 'provisioning_state': {'readonly': True}, 'provisioning_state_transition_time': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'location': {'key': 'location', 'type': 'str'}, 'tags': {'key': 'tags', 'type': '{str}'}, 'creation_time': {'key': 'properties.creationTime', 'type': 'iso-8601'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'provisioning_state_transition_time': {'key': 'properties.provisioningStateTransitionTime', 'type': 'iso-8601'}, } def __init__( self, **kwargs ): super(Workspace, self).__init__(**kwargs) self.creation_time = None self.provisioning_state = None self.provisioning_state_transition_time = None class WorkspaceCreateParameters(msrest.serialization.Model): """Workspace creation parameters. All required parameters must be populated in order to send to Azure. :param location: Required. The region in which to create the Workspace. :type location: str :param tags: A set of tags. The user specified tags associated with the Workspace. :type tags: dict[str, str] """ _validation = { 'location': {'required': True}, } _attribute_map = { 'location': {'key': 'location', 'type': 'str'}, 'tags': {'key': 'tags', 'type': '{str}'}, } def __init__( self, **kwargs ): super(WorkspaceCreateParameters, self).__init__(**kwargs) self.location = kwargs['location'] self.tags = kwargs.get('tags', None) class WorkspaceListResult(msrest.serialization.Model): """Values returned by the List operation. Variables are only populated by the server, and will be ignored when sending a request. :ivar value: The collection of workspaces. :vartype value: list[~batch_ai.models.Workspace] :ivar next_link: The continuation token. :vartype next_link: str """ _validation = { 'value': {'readonly': True}, 'next_link': {'readonly': True}, } _attribute_map = { 'value': {'key': 'value', 'type': '[Workspace]'}, 'next_link': {'key': 'nextLink', 'type': 'str'}, } def __init__( self, **kwargs ): super(WorkspaceListResult, self).__init__(**kwargs) self.value = None self.next_link = None class WorkspacesListByResourceGroupOptions(msrest.serialization.Model): """Parameter group. :param max_results: The maximum number of items to return in the response. A maximum of 1000 files can be returned. :type max_results: int """ _validation = { 'max_results': {'maximum': 1000, 'minimum': 1}, } _attribute_map = { 'max_results': {'key': 'maxResults', 'type': 'int'}, } def __init__( self, **kwargs ): super(WorkspacesListByResourceGroupOptions, self).__init__(**kwargs) self.max_results = kwargs.get('max_results', 1000) class WorkspacesListOptions(msrest.serialization.Model): """Parameter group. :param max_results: The maximum number of items to return in the response. A maximum of 1000 files can be returned. :type max_results: int """ _validation = { 'max_results': {'maximum': 1000, 'minimum': 1}, } _attribute_map = { 'max_results': {'key': 'maxResults', 'type': 'int'}, } def __init__( self, **kwargs ): super(WorkspacesListOptions, self).__init__(**kwargs) self.max_results = kwargs.get('max_results', 1000) class WorkspaceUpdateParameters(msrest.serialization.Model): """Workspace update parameters. :param tags: A set of tags. The user specified tags associated with the Workspace. :type tags: dict[str, str] """ _attribute_map = { 'tags': {'key': 'tags', 'type': '{str}'}, } def __init__( self, **kwargs ): super(WorkspaceUpdateParameters, self).__init__(**kwargs) self.tags = kwargs.get('tags', None)
0.89085
0.409486
import datetime from typing import Any, Dict, List, Optional, Union import msrest.serialization from ._batch_ai_enums import * class AppInsightsReference(msrest.serialization.Model): """Azure Application Insights information for performance counters reporting. All required parameters must be populated in order to send to Azure. :param component: Required. Azure Application Insights component resource ID. :type component: ~batch_ai.models.ResourceId :param instrumentation_key: Value of the Azure Application Insights instrumentation key. :type instrumentation_key: str :param instrumentation_key_secret_reference: KeyVault Store and Secret which contains Azure Application Insights instrumentation key. One of instrumentationKey or instrumentationKeySecretReference must be specified. :type instrumentation_key_secret_reference: ~batch_ai.models.KeyVaultSecretReference """ _validation = { 'component': {'required': True}, } _attribute_map = { 'component': {'key': 'component', 'type': 'ResourceId'}, 'instrumentation_key': {'key': 'instrumentationKey', 'type': 'str'}, 'instrumentation_key_secret_reference': {'key': 'instrumentationKeySecretReference', 'type': 'KeyVaultSecretReference'}, } def __init__( self, *, component: "ResourceId", instrumentation_key: Optional[str] = None, instrumentation_key_secret_reference: Optional["KeyVaultSecretReference"] = None, **kwargs ): super(AppInsightsReference, self).__init__(**kwargs) self.component = component self.instrumentation_key = instrumentation_key self.instrumentation_key_secret_reference = instrumentation_key_secret_reference class AutoScaleSettings(msrest.serialization.Model): """Auto-scale settings for the cluster. The system automatically scales the cluster up and down (within minimumNodeCount and maximumNodeCount) based on the number of queued and running jobs assigned to the cluster. All required parameters must be populated in order to send to Azure. :param minimum_node_count: Required. The minimum number of compute nodes the Batch AI service will try to allocate for the cluster. Note, the actual number of nodes can be less than the specified value if the subscription has not enough quota to fulfill the request. :type minimum_node_count: int :param maximum_node_count: Required. The maximum number of compute nodes the cluster can have. :type maximum_node_count: int :param initial_node_count: The number of compute nodes to allocate on cluster creation. Note that this value is used only during cluster creation. Default: 0. :type initial_node_count: int """ _validation = { 'minimum_node_count': {'required': True}, 'maximum_node_count': {'required': True}, } _attribute_map = { 'minimum_node_count': {'key': 'minimumNodeCount', 'type': 'int'}, 'maximum_node_count': {'key': 'maximumNodeCount', 'type': 'int'}, 'initial_node_count': {'key': 'initialNodeCount', 'type': 'int'}, } def __init__( self, *, minimum_node_count: int, maximum_node_count: int, initial_node_count: Optional[int] = 0, **kwargs ): super(AutoScaleSettings, self).__init__(**kwargs) self.minimum_node_count = minimum_node_count self.maximum_node_count = maximum_node_count self.initial_node_count = initial_node_count class AzureBlobFileSystemReference(msrest.serialization.Model): """Azure Blob Storage Container mounting configuration. All required parameters must be populated in order to send to Azure. :param account_name: Required. Name of the Azure storage account. :type account_name: str :param container_name: Required. Name of the Azure Blob Storage container to mount on the cluster. :type container_name: str :param credentials: Required. Information about the Azure storage credentials. :type credentials: ~batch_ai.models.AzureStorageCredentialsInfo :param relative_mount_path: Required. The relative path on the compute node where the Azure File container will be mounted. Note that all cluster level containers will be mounted under $AZ_BATCHAI_MOUNT_ROOT location and all job level containers will be mounted under $AZ_BATCHAI_JOB_MOUNT_ROOT. :type relative_mount_path: str :param mount_options: Mount options for mounting blobfuse file system. :type mount_options: str """ _validation = { 'account_name': {'required': True}, 'container_name': {'required': True}, 'credentials': {'required': True}, 'relative_mount_path': {'required': True}, } _attribute_map = { 'account_name': {'key': 'accountName', 'type': 'str'}, 'container_name': {'key': 'containerName', 'type': 'str'}, 'credentials': {'key': 'credentials', 'type': 'AzureStorageCredentialsInfo'}, 'relative_mount_path': {'key': 'relativeMountPath', 'type': 'str'}, 'mount_options': {'key': 'mountOptions', 'type': 'str'}, } def __init__( self, *, account_name: str, container_name: str, credentials: "AzureStorageCredentialsInfo", relative_mount_path: str, mount_options: Optional[str] = None, **kwargs ): super(AzureBlobFileSystemReference, self).__init__(**kwargs) self.account_name = account_name self.container_name = container_name self.credentials = credentials self.relative_mount_path = relative_mount_path self.mount_options = mount_options class AzureFileShareReference(msrest.serialization.Model): """Azure File Share mounting configuration. All required parameters must be populated in order to send to Azure. :param account_name: Required. Name of the Azure storage account. :type account_name: str :param azure_file_url: Required. URL to access the Azure File. :type azure_file_url: str :param credentials: Required. Information about the Azure storage credentials. :type credentials: ~batch_ai.models.AzureStorageCredentialsInfo :param relative_mount_path: Required. The relative path on the compute node where the Azure File share will be mounted. Note that all cluster level file shares will be mounted under $AZ_BATCHAI_MOUNT_ROOT location and all job level file shares will be mounted under $AZ_BATCHAI_JOB_MOUNT_ROOT. :type relative_mount_path: str :param file_mode: File mode for files on the mounted file share. Default value: 0777. :type file_mode: str :param directory_mode: File mode for directories on the mounted file share. Default value: 0777. :type directory_mode: str """ _validation = { 'account_name': {'required': True}, 'azure_file_url': {'required': True}, 'credentials': {'required': True}, 'relative_mount_path': {'required': True}, } _attribute_map = { 'account_name': {'key': 'accountName', 'type': 'str'}, 'azure_file_url': {'key': 'azureFileUrl', 'type': 'str'}, 'credentials': {'key': 'credentials', 'type': 'AzureStorageCredentialsInfo'}, 'relative_mount_path': {'key': 'relativeMountPath', 'type': 'str'}, 'file_mode': {'key': 'fileMode', 'type': 'str'}, 'directory_mode': {'key': 'directoryMode', 'type': 'str'}, } def __init__( self, *, account_name: str, azure_file_url: str, credentials: "AzureStorageCredentialsInfo", relative_mount_path: str, file_mode: Optional[str] = "0777", directory_mode: Optional[str] = "0777", **kwargs ): super(AzureFileShareReference, self).__init__(**kwargs) self.account_name = account_name self.azure_file_url = azure_file_url self.credentials = credentials self.relative_mount_path = relative_mount_path self.file_mode = file_mode self.directory_mode = directory_mode class AzureStorageCredentialsInfo(msrest.serialization.Model): """Azure storage account credentials. :param account_key: Storage account key. One of accountKey or accountKeySecretReference must be specified. :type account_key: str :param account_key_secret_reference: Information about KeyVault secret storing the storage account key. One of accountKey or accountKeySecretReference must be specified. :type account_key_secret_reference: ~batch_ai.models.KeyVaultSecretReference """ _attribute_map = { 'account_key': {'key': 'accountKey', 'type': 'str'}, 'account_key_secret_reference': {'key': 'accountKeySecretReference', 'type': 'KeyVaultSecretReference'}, } def __init__( self, *, account_key: Optional[str] = None, account_key_secret_reference: Optional["KeyVaultSecretReference"] = None, **kwargs ): super(AzureStorageCredentialsInfo, self).__init__(**kwargs) self.account_key = account_key self.account_key_secret_reference = account_key_secret_reference class BatchAIError(msrest.serialization.Model): """An error response from the Batch AI service. Variables are only populated by the server, and will be ignored when sending a request. :ivar code: An identifier of the error. Codes are invariant and are intended to be consumed programmatically. :vartype code: str :ivar message: A message describing the error, intended to be suitable for display in a user interface. :vartype message: str :ivar details: A list of additional details about the error. :vartype details: list[~batch_ai.models.NameValuePair] """ _validation = { 'code': {'readonly': True}, 'message': {'readonly': True}, 'details': {'readonly': True}, } _attribute_map = { 'code': {'key': 'code', 'type': 'str'}, 'message': {'key': 'message', 'type': 'str'}, 'details': {'key': 'details', 'type': '[NameValuePair]'}, } def __init__( self, **kwargs ): super(BatchAIError, self).__init__(**kwargs) self.code = None self.message = None self.details = None class Caffe2Settings(msrest.serialization.Model): """Caffe2 job settings. All required parameters must be populated in order to send to Azure. :param python_script_file_path: Required. The python script to execute. :type python_script_file_path: str :param python_interpreter_path: The path to the Python interpreter. :type python_interpreter_path: str :param command_line_args: Command line arguments that need to be passed to the python script. :type command_line_args: str """ _validation = { 'python_script_file_path': {'required': True}, } _attribute_map = { 'python_script_file_path': {'key': 'pythonScriptFilePath', 'type': 'str'}, 'python_interpreter_path': {'key': 'pythonInterpreterPath', 'type': 'str'}, 'command_line_args': {'key': 'commandLineArgs', 'type': 'str'}, } def __init__( self, *, python_script_file_path: str, python_interpreter_path: Optional[str] = None, command_line_args: Optional[str] = None, **kwargs ): super(Caffe2Settings, self).__init__(**kwargs) self.python_script_file_path = python_script_file_path self.python_interpreter_path = python_interpreter_path self.command_line_args = command_line_args class CaffeSettings(msrest.serialization.Model): """Caffe job settings. :param config_file_path: Path of the config file for the job. This property cannot be specified if pythonScriptFilePath is specified. :type config_file_path: str :param python_script_file_path: Python script to execute. This property cannot be specified if configFilePath is specified. :type python_script_file_path: str :param python_interpreter_path: The path to the Python interpreter. The property can be specified only if the pythonScriptFilePath is specified. :type python_interpreter_path: str :param command_line_args: Command line arguments that need to be passed to the Caffe job. :type command_line_args: str :param process_count: Number of processes to launch for the job execution. The default value for this property is equal to nodeCount property. :type process_count: int """ _attribute_map = { 'config_file_path': {'key': 'configFilePath', 'type': 'str'}, 'python_script_file_path': {'key': 'pythonScriptFilePath', 'type': 'str'}, 'python_interpreter_path': {'key': 'pythonInterpreterPath', 'type': 'str'}, 'command_line_args': {'key': 'commandLineArgs', 'type': 'str'}, 'process_count': {'key': 'processCount', 'type': 'int'}, } def __init__( self, *, config_file_path: Optional[str] = None, python_script_file_path: Optional[str] = None, python_interpreter_path: Optional[str] = None, command_line_args: Optional[str] = None, process_count: Optional[int] = None, **kwargs ): super(CaffeSettings, self).__init__(**kwargs) self.config_file_path = config_file_path self.python_script_file_path = python_script_file_path self.python_interpreter_path = python_interpreter_path self.command_line_args = command_line_args self.process_count = process_count class ChainerSettings(msrest.serialization.Model): """Chainer job settings. All required parameters must be populated in order to send to Azure. :param python_script_file_path: Required. The python script to execute. :type python_script_file_path: str :param python_interpreter_path: The path to the Python interpreter. :type python_interpreter_path: str :param command_line_args: Command line arguments that need to be passed to the python script. :type command_line_args: str :param process_count: Number of processes to launch for the job execution. The default value for this property is equal to nodeCount property. :type process_count: int """ _validation = { 'python_script_file_path': {'required': True}, } _attribute_map = { 'python_script_file_path': {'key': 'pythonScriptFilePath', 'type': 'str'}, 'python_interpreter_path': {'key': 'pythonInterpreterPath', 'type': 'str'}, 'command_line_args': {'key': 'commandLineArgs', 'type': 'str'}, 'process_count': {'key': 'processCount', 'type': 'int'}, } def __init__( self, *, python_script_file_path: str, python_interpreter_path: Optional[str] = None, command_line_args: Optional[str] = None, process_count: Optional[int] = None, **kwargs ): super(ChainerSettings, self).__init__(**kwargs) self.python_script_file_path = python_script_file_path self.python_interpreter_path = python_interpreter_path self.command_line_args = command_line_args self.process_count = process_count class CloudErrorBody(msrest.serialization.Model): """An error response from the Batch AI service. Variables are only populated by the server, and will be ignored when sending a request. :ivar code: An identifier for the error. Codes are invariant and are intended to be consumed programmatically. :vartype code: str :ivar message: A message describing the error, intended to be suitable for display in a user interface. :vartype message: str :ivar target: The target of the particular error. For example, the name of the property in error. :vartype target: str :ivar details: A list of additional details about the error. :vartype details: list[~batch_ai.models.CloudErrorBody] """ _validation = { 'code': {'readonly': True}, 'message': {'readonly': True}, 'target': {'readonly': True}, 'details': {'readonly': True}, } _attribute_map = { 'code': {'key': 'code', 'type': 'str'}, 'message': {'key': 'message', 'type': 'str'}, 'target': {'key': 'target', 'type': 'str'}, 'details': {'key': 'details', 'type': '[CloudErrorBody]'}, } def __init__( self, **kwargs ): super(CloudErrorBody, self).__init__(**kwargs) self.code = None self.message = None self.target = None self.details = None class ProxyResource(msrest.serialization.Model): """A definition of an Azure proxy resource. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: The ID of the resource. :vartype id: str :ivar name: The name of the resource. :vartype name: str :ivar type: The type of the resource. :vartype type: str """ _validation = { 'id': {'readonly': True}, 'name': {'readonly': True}, 'type': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, } def __init__( self, **kwargs ): super(ProxyResource, self).__init__(**kwargs) self.id = None self.name = None self.type = None class Cluster(ProxyResource): """Information about a Cluster. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: The ID of the resource. :vartype id: str :ivar name: The name of the resource. :vartype name: str :ivar type: The type of the resource. :vartype type: str :param vm_size: The size of the virtual machines in the cluster. All nodes in a cluster have the same VM size. :type vm_size: str :param vm_priority: VM priority of cluster nodes. Possible values include: "dedicated", "lowpriority". :type vm_priority: str or ~batch_ai.models.VmPriority :param scale_settings: Scale settings of the cluster. :type scale_settings: ~batch_ai.models.ScaleSettings :param virtual_machine_configuration: Virtual machine configuration (OS image) of the compute nodes. All nodes in a cluster have the same OS image configuration. :type virtual_machine_configuration: ~batch_ai.models.VirtualMachineConfiguration :param node_setup: Setup (mount file systems, performance counters settings and custom setup task) to be performed on each compute node in the cluster. :type node_setup: ~batch_ai.models.NodeSetup :param user_account_settings: Administrator user account settings which can be used to SSH to compute nodes. :type user_account_settings: ~batch_ai.models.UserAccountSettings :param subnet: Virtual network subnet resource ID the cluster nodes belong to. :type subnet: ~batch_ai.models.ResourceId :ivar creation_time: The time when the cluster was created. :vartype creation_time: ~datetime.datetime :ivar provisioning_state: Provisioning state of the cluster. Possible value are: creating - Specifies that the cluster is being created. succeeded - Specifies that the cluster has been created successfully. failed - Specifies that the cluster creation has failed. deleting - Specifies that the cluster is being deleted. Possible values include: "creating", "succeeded", "failed", "deleting". :vartype provisioning_state: str or ~batch_ai.models.ProvisioningState :ivar provisioning_state_transition_time: Time when the provisioning state was changed. :vartype provisioning_state_transition_time: ~datetime.datetime :ivar allocation_state: Allocation state of the cluster. Possible values are: steady - Indicates that the cluster is not resizing. There are no changes to the number of compute nodes in the cluster in progress. A cluster enters this state when it is created and when no operations are being performed on the cluster to change the number of compute nodes. resizing - Indicates that the cluster is resizing; that is, compute nodes are being added to or removed from the cluster. Possible values include: "steady", "resizing". :vartype allocation_state: str or ~batch_ai.models.AllocationState :ivar allocation_state_transition_time: The time at which the cluster entered its current allocation state. :vartype allocation_state_transition_time: ~datetime.datetime :ivar errors: Collection of errors encountered by various compute nodes during node setup. :vartype errors: list[~batch_ai.models.BatchAIError] :ivar current_node_count: The number of compute nodes currently assigned to the cluster. :vartype current_node_count: int :ivar node_state_counts: Counts of various node states on the cluster. :vartype node_state_counts: ~batch_ai.models.NodeStateCounts """ _validation = { 'id': {'readonly': True}, 'name': {'readonly': True}, 'type': {'readonly': True}, 'creation_time': {'readonly': True}, 'provisioning_state': {'readonly': True}, 'provisioning_state_transition_time': {'readonly': True}, 'allocation_state': {'readonly': True}, 'allocation_state_transition_time': {'readonly': True}, 'errors': {'readonly': True}, 'current_node_count': {'readonly': True}, 'node_state_counts': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'vm_size': {'key': 'properties.vmSize', 'type': 'str'}, 'vm_priority': {'key': 'properties.vmPriority', 'type': 'str'}, 'scale_settings': {'key': 'properties.scaleSettings', 'type': 'ScaleSettings'}, 'virtual_machine_configuration': {'key': 'properties.virtualMachineConfiguration', 'type': 'VirtualMachineConfiguration'}, 'node_setup': {'key': 'properties.nodeSetup', 'type': 'NodeSetup'}, 'user_account_settings': {'key': 'properties.userAccountSettings', 'type': 'UserAccountSettings'}, 'subnet': {'key': 'properties.subnet', 'type': 'ResourceId'}, 'creation_time': {'key': 'properties.creationTime', 'type': 'iso-8601'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'provisioning_state_transition_time': {'key': 'properties.provisioningStateTransitionTime', 'type': 'iso-8601'}, 'allocation_state': {'key': 'properties.allocationState', 'type': 'str'}, 'allocation_state_transition_time': {'key': 'properties.allocationStateTransitionTime', 'type': 'iso-8601'}, 'errors': {'key': 'properties.errors', 'type': '[BatchAIError]'}, 'current_node_count': {'key': 'properties.currentNodeCount', 'type': 'int'}, 'node_state_counts': {'key': 'properties.nodeStateCounts', 'type': 'NodeStateCounts'}, } def __init__( self, *, vm_size: Optional[str] = None, vm_priority: Optional[Union[str, "VmPriority"]] = None, scale_settings: Optional["ScaleSettings"] = None, virtual_machine_configuration: Optional["VirtualMachineConfiguration"] = None, node_setup: Optional["NodeSetup"] = None, user_account_settings: Optional["UserAccountSettings"] = None, subnet: Optional["ResourceId"] = None, **kwargs ): super(Cluster, self).__init__(**kwargs) self.vm_size = vm_size self.vm_priority = vm_priority self.scale_settings = scale_settings self.virtual_machine_configuration = virtual_machine_configuration self.node_setup = node_setup self.user_account_settings = user_account_settings self.subnet = subnet self.creation_time = None self.provisioning_state = None self.provisioning_state_transition_time = None self.allocation_state = None self.allocation_state_transition_time = None self.errors = None self.current_node_count = None self.node_state_counts = None class ClusterCreateParameters(msrest.serialization.Model): """Cluster creation operation. :param vm_size: The size of the virtual machines in the cluster. All nodes in a cluster have the same VM size. For information about available VM sizes for clusters using images from the Virtual Machines Marketplace see Sizes for Virtual Machines (Linux). Batch AI service supports all Azure VM sizes except STANDARD_A0 and those with premium storage (STANDARD_GS, STANDARD_DS, and STANDARD_DSV2 series). :type vm_size: str :param vm_priority: VM priority. Allowed values are: dedicated (default) and lowpriority. Possible values include: "dedicated", "lowpriority". :type vm_priority: str or ~batch_ai.models.VmPriority :param scale_settings: Scale settings for the cluster. Batch AI service supports manual and auto scale clusters. :type scale_settings: ~batch_ai.models.ScaleSettings :param virtual_machine_configuration: OS image configuration for cluster nodes. All nodes in a cluster have the same OS image. :type virtual_machine_configuration: ~batch_ai.models.VirtualMachineConfiguration :param node_setup: Setup to be performed on each compute node in the cluster. :type node_setup: ~batch_ai.models.NodeSetup :param user_account_settings: Settings for an administrator user account that will be created on each compute node in the cluster. :type user_account_settings: ~batch_ai.models.UserAccountSettings :param subnet: Existing virtual network subnet to put the cluster nodes in. Note, if a File Server mount configured in node setup, the File Server's subnet will be used automatically. :type subnet: ~batch_ai.models.ResourceId """ _attribute_map = { 'vm_size': {'key': 'properties.vmSize', 'type': 'str'}, 'vm_priority': {'key': 'properties.vmPriority', 'type': 'str'}, 'scale_settings': {'key': 'properties.scaleSettings', 'type': 'ScaleSettings'}, 'virtual_machine_configuration': {'key': 'properties.virtualMachineConfiguration', 'type': 'VirtualMachineConfiguration'}, 'node_setup': {'key': 'properties.nodeSetup', 'type': 'NodeSetup'}, 'user_account_settings': {'key': 'properties.userAccountSettings', 'type': 'UserAccountSettings'}, 'subnet': {'key': 'properties.subnet', 'type': 'ResourceId'}, } def __init__( self, *, vm_size: Optional[str] = None, vm_priority: Optional[Union[str, "VmPriority"]] = None, scale_settings: Optional["ScaleSettings"] = None, virtual_machine_configuration: Optional["VirtualMachineConfiguration"] = None, node_setup: Optional["NodeSetup"] = None, user_account_settings: Optional["UserAccountSettings"] = None, subnet: Optional["ResourceId"] = None, **kwargs ): super(ClusterCreateParameters, self).__init__(**kwargs) self.vm_size = vm_size self.vm_priority = vm_priority self.scale_settings = scale_settings self.virtual_machine_configuration = virtual_machine_configuration self.node_setup = node_setup self.user_account_settings = user_account_settings self.subnet = subnet class ClusterListResult(msrest.serialization.Model): """Values returned by the List Clusters operation. Variables are only populated by the server, and will be ignored when sending a request. :ivar value: The collection of returned Clusters. :vartype value: list[~batch_ai.models.Cluster] :ivar next_link: The continuation token. :vartype next_link: str """ _validation = { 'value': {'readonly': True}, 'next_link': {'readonly': True}, } _attribute_map = { 'value': {'key': 'value', 'type': '[Cluster]'}, 'next_link': {'key': 'nextLink', 'type': 'str'}, } def __init__( self, **kwargs ): super(ClusterListResult, self).__init__(**kwargs) self.value = None self.next_link = None class ClustersListByWorkspaceOptions(msrest.serialization.Model): """Parameter group. :param max_results: The maximum number of items to return in the response. A maximum of 1000 files can be returned. :type max_results: int """ _validation = { 'max_results': {'maximum': 1000, 'minimum': 1}, } _attribute_map = { 'max_results': {'key': 'maxResults', 'type': 'int'}, } def __init__( self, *, max_results: Optional[int] = 1000, **kwargs ): super(ClustersListByWorkspaceOptions, self).__init__(**kwargs) self.max_results = max_results class ClusterUpdateParameters(msrest.serialization.Model): """Cluster update parameters. :param scale_settings: Desired scale settings for the cluster. Batch AI service supports manual and auto scale clusters. :type scale_settings: ~batch_ai.models.ScaleSettings """ _attribute_map = { 'scale_settings': {'key': 'properties.scaleSettings', 'type': 'ScaleSettings'}, } def __init__( self, *, scale_settings: Optional["ScaleSettings"] = None, **kwargs ): super(ClusterUpdateParameters, self).__init__(**kwargs) self.scale_settings = scale_settings class CNTKsettings(msrest.serialization.Model): """CNTK (aka Microsoft Cognitive Toolkit) job settings. :param language_type: The language to use for launching CNTK (aka Microsoft Cognitive Toolkit) job. Valid values are 'BrainScript' or 'Python'. :type language_type: str :param config_file_path: Specifies the path of the BrainScript config file. This property can be specified only if the languageType is 'BrainScript'. :type config_file_path: str :param python_script_file_path: Python script to execute. This property can be specified only if the languageType is 'Python'. :type python_script_file_path: str :param python_interpreter_path: The path to the Python interpreter. This property can be specified only if the languageType is 'Python'. :type python_interpreter_path: str :param command_line_args: Command line arguments that need to be passed to the python script or cntk executable. :type command_line_args: str :param process_count: Number of processes to launch for the job execution. The default value for this property is equal to nodeCount property. :type process_count: int """ _attribute_map = { 'language_type': {'key': 'languageType', 'type': 'str'}, 'config_file_path': {'key': 'configFilePath', 'type': 'str'}, 'python_script_file_path': {'key': 'pythonScriptFilePath', 'type': 'str'}, 'python_interpreter_path': {'key': 'pythonInterpreterPath', 'type': 'str'}, 'command_line_args': {'key': 'commandLineArgs', 'type': 'str'}, 'process_count': {'key': 'processCount', 'type': 'int'}, } def __init__( self, *, language_type: Optional[str] = None, config_file_path: Optional[str] = None, python_script_file_path: Optional[str] = None, python_interpreter_path: Optional[str] = None, command_line_args: Optional[str] = None, process_count: Optional[int] = None, **kwargs ): super(CNTKsettings, self).__init__(**kwargs) self.language_type = language_type self.config_file_path = config_file_path self.python_script_file_path = python_script_file_path self.python_interpreter_path = python_interpreter_path self.command_line_args = command_line_args self.process_count = process_count class ContainerSettings(msrest.serialization.Model): """Docker container settings. All required parameters must be populated in order to send to Azure. :param image_source_registry: Required. Information about docker image and docker registry to download the container from. :type image_source_registry: ~batch_ai.models.ImageSourceRegistry :param shm_size: Size of /dev/shm. Please refer to docker documentation for supported argument formats. :type shm_size: str """ _validation = { 'image_source_registry': {'required': True}, } _attribute_map = { 'image_source_registry': {'key': 'imageSourceRegistry', 'type': 'ImageSourceRegistry'}, 'shm_size': {'key': 'shmSize', 'type': 'str'}, } def __init__( self, *, image_source_registry: "ImageSourceRegistry", shm_size: Optional[str] = None, **kwargs ): super(ContainerSettings, self).__init__(**kwargs) self.image_source_registry = image_source_registry self.shm_size = shm_size class CustomMpiSettings(msrest.serialization.Model): """Custom MPI job settings. All required parameters must be populated in order to send to Azure. :param command_line: Required. The command line to be executed by mpi runtime on each compute node. :type command_line: str :param process_count: Number of processes to launch for the job execution. The default value for this property is equal to nodeCount property. :type process_count: int """ _validation = { 'command_line': {'required': True}, } _attribute_map = { 'command_line': {'key': 'commandLine', 'type': 'str'}, 'process_count': {'key': 'processCount', 'type': 'int'}, } def __init__( self, *, command_line: str, process_count: Optional[int] = None, **kwargs ): super(CustomMpiSettings, self).__init__(**kwargs) self.command_line = command_line self.process_count = process_count class CustomToolkitSettings(msrest.serialization.Model): """Custom tool kit job settings. :param command_line: The command line to execute on the master node. :type command_line: str """ _attribute_map = { 'command_line': {'key': 'commandLine', 'type': 'str'}, } def __init__( self, *, command_line: Optional[str] = None, **kwargs ): super(CustomToolkitSettings, self).__init__(**kwargs) self.command_line = command_line class DataDisks(msrest.serialization.Model): """Data disks settings. All required parameters must be populated in order to send to Azure. :param disk_size_in_gb: Required. Disk size in GB for the blank data disks. :type disk_size_in_gb: int :param caching_type: Caching type for the disks. Available values are none (default), readonly, readwrite. Caching type can be set only for VM sizes supporting premium storage. Possible values include: "none", "readonly", "readwrite". Default value: "none". :type caching_type: str or ~batch_ai.models.CachingType :param disk_count: Required. Number of data disks attached to the File Server. If multiple disks attached, they will be configured in RAID level 0. :type disk_count: int :param storage_account_type: Required. Type of storage account to be used on the disk. Possible values are: Standard_LRS or Premium_LRS. Premium storage account type can only be used with VM sizes supporting premium storage. Possible values include: "Standard_LRS", "Premium_LRS". :type storage_account_type: str or ~batch_ai.models.StorageAccountType """ _validation = { 'disk_size_in_gb': {'required': True}, 'disk_count': {'required': True}, 'storage_account_type': {'required': True}, } _attribute_map = { 'disk_size_in_gb': {'key': 'diskSizeInGB', 'type': 'int'}, 'caching_type': {'key': 'cachingType', 'type': 'str'}, 'disk_count': {'key': 'diskCount', 'type': 'int'}, 'storage_account_type': {'key': 'storageAccountType', 'type': 'str'}, } def __init__( self, *, disk_size_in_gb: int, disk_count: int, storage_account_type: Union[str, "StorageAccountType"], caching_type: Optional[Union[str, "CachingType"]] = "none", **kwargs ): super(DataDisks, self).__init__(**kwargs) self.disk_size_in_gb = disk_size_in_gb self.caching_type = caching_type self.disk_count = disk_count self.storage_account_type = storage_account_type class EnvironmentVariable(msrest.serialization.Model): """An environment variable definition. All required parameters must be populated in order to send to Azure. :param name: Required. The name of the environment variable. :type name: str :param value: Required. The value of the environment variable. :type value: str """ _validation = { 'name': {'required': True}, 'value': {'required': True}, } _attribute_map = { 'name': {'key': 'name', 'type': 'str'}, 'value': {'key': 'value', 'type': 'str'}, } def __init__( self, *, name: str, value: str, **kwargs ): super(EnvironmentVariable, self).__init__(**kwargs) self.name = name self.value = value class EnvironmentVariableWithSecretValue(msrest.serialization.Model): """An environment variable with secret value definition. All required parameters must be populated in order to send to Azure. :param name: Required. The name of the environment variable to store the secret value. :type name: str :param value: The value of the environment variable. This value will never be reported back by Batch AI. :type value: str :param value_secret_reference: KeyVault store and secret which contains the value for the environment variable. One of value or valueSecretReference must be provided. :type value_secret_reference: ~batch_ai.models.KeyVaultSecretReference """ _validation = { 'name': {'required': True}, } _attribute_map = { 'name': {'key': 'name', 'type': 'str'}, 'value': {'key': 'value', 'type': 'str'}, 'value_secret_reference': {'key': 'valueSecretReference', 'type': 'KeyVaultSecretReference'}, } def __init__( self, *, name: str, value: Optional[str] = None, value_secret_reference: Optional["KeyVaultSecretReference"] = None, **kwargs ): super(EnvironmentVariableWithSecretValue, self).__init__(**kwargs) self.name = name self.value = value self.value_secret_reference = value_secret_reference class Experiment(ProxyResource): """Experiment information. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: The ID of the resource. :vartype id: str :ivar name: The name of the resource. :vartype name: str :ivar type: The type of the resource. :vartype type: str :ivar creation_time: Time when the Experiment was created. :vartype creation_time: ~datetime.datetime :ivar provisioning_state: The provisioned state of the experiment. Possible values include: "creating", "succeeded", "failed", "deleting". :vartype provisioning_state: str or ~batch_ai.models.ProvisioningState :ivar provisioning_state_transition_time: The time at which the experiment entered its current provisioning state. :vartype provisioning_state_transition_time: ~datetime.datetime """ _validation = { 'id': {'readonly': True}, 'name': {'readonly': True}, 'type': {'readonly': True}, 'creation_time': {'readonly': True}, 'provisioning_state': {'readonly': True}, 'provisioning_state_transition_time': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'creation_time': {'key': 'properties.creationTime', 'type': 'iso-8601'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'provisioning_state_transition_time': {'key': 'properties.provisioningStateTransitionTime', 'type': 'iso-8601'}, } def __init__( self, **kwargs ): super(Experiment, self).__init__(**kwargs) self.creation_time = None self.provisioning_state = None self.provisioning_state_transition_time = None class ExperimentListResult(msrest.serialization.Model): """Values returned by the List operation. Variables are only populated by the server, and will be ignored when sending a request. :ivar value: The collection of experiments. :vartype value: list[~batch_ai.models.Experiment] :ivar next_link: The continuation token. :vartype next_link: str """ _validation = { 'value': {'readonly': True}, 'next_link': {'readonly': True}, } _attribute_map = { 'value': {'key': 'value', 'type': '[Experiment]'}, 'next_link': {'key': 'nextLink', 'type': 'str'}, } def __init__( self, **kwargs ): super(ExperimentListResult, self).__init__(**kwargs) self.value = None self.next_link = None class ExperimentsListByWorkspaceOptions(msrest.serialization.Model): """Parameter group. :param max_results: The maximum number of items to return in the response. A maximum of 1000 files can be returned. :type max_results: int """ _validation = { 'max_results': {'maximum': 1000, 'minimum': 1}, } _attribute_map = { 'max_results': {'key': 'maxResults', 'type': 'int'}, } def __init__( self, *, max_results: Optional[int] = 1000, **kwargs ): super(ExperimentsListByWorkspaceOptions, self).__init__(**kwargs) self.max_results = max_results class File(msrest.serialization.Model): """Properties of the file or directory. Variables are only populated by the server, and will be ignored when sending a request. :ivar name: Name of the file. :vartype name: str :ivar file_type: Type of the file. Possible values are file and directory. Possible values include: "file", "directory". :vartype file_type: str or ~batch_ai.models.FileType :ivar download_url: URL to download the corresponding file. The downloadUrl is not returned for directories. :vartype download_url: str :ivar last_modified: The time at which the file was last modified. :vartype last_modified: ~datetime.datetime :ivar content_length: The file of the size. :vartype content_length: long """ _validation = { 'name': {'readonly': True}, 'file_type': {'readonly': True}, 'download_url': {'readonly': True}, 'last_modified': {'readonly': True}, 'content_length': {'readonly': True}, } _attribute_map = { 'name': {'key': 'name', 'type': 'str'}, 'file_type': {'key': 'fileType', 'type': 'str'}, 'download_url': {'key': 'downloadUrl', 'type': 'str'}, 'last_modified': {'key': 'properties.lastModified', 'type': 'iso-8601'}, 'content_length': {'key': 'properties.contentLength', 'type': 'long'}, } def __init__( self, **kwargs ): super(File, self).__init__(**kwargs) self.name = None self.file_type = None self.download_url = None self.last_modified = None self.content_length = None class FileListResult(msrest.serialization.Model): """Values returned by the List operation. Variables are only populated by the server, and will be ignored when sending a request. :ivar value: The collection of returned job directories and files. :vartype value: list[~batch_ai.models.File] :ivar next_link: The continuation token. :vartype next_link: str """ _validation = { 'value': {'readonly': True}, 'next_link': {'readonly': True}, } _attribute_map = { 'value': {'key': 'value', 'type': '[File]'}, 'next_link': {'key': 'nextLink', 'type': 'str'}, } def __init__( self, **kwargs ): super(FileListResult, self).__init__(**kwargs) self.value = None self.next_link = None class FileServer(ProxyResource): """File Server information. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: The ID of the resource. :vartype id: str :ivar name: The name of the resource. :vartype name: str :ivar type: The type of the resource. :vartype type: str :param vm_size: VM size of the File Server. :type vm_size: str :param ssh_configuration: SSH configuration for accessing the File Server node. :type ssh_configuration: ~batch_ai.models.SshConfiguration :param data_disks: Information about disks attached to File Server VM. :type data_disks: ~batch_ai.models.DataDisks :param subnet: File Server virtual network subnet resource ID. :type subnet: ~batch_ai.models.ResourceId :ivar mount_settings: File Server mount settings. :vartype mount_settings: ~batch_ai.models.MountSettings :ivar provisioning_state_transition_time: Time when the provisioning state was changed. :vartype provisioning_state_transition_time: ~datetime.datetime :ivar creation_time: Time when the FileServer was created. :vartype creation_time: ~datetime.datetime :ivar provisioning_state: Provisioning state of the File Server. Possible values: creating - The File Server is getting created; updating - The File Server creation has been accepted and it is getting updated; deleting - The user has requested that the File Server be deleted, and it is in the process of being deleted; failed - The File Server creation has failed with the specified error code. Details about the error code are specified in the message field; succeeded - The File Server creation has succeeded. Possible values include: "creating", "updating", "deleting", "succeeded", "failed". :vartype provisioning_state: str or ~batch_ai.models.FileServerProvisioningState """ _validation = { 'id': {'readonly': True}, 'name': {'readonly': True}, 'type': {'readonly': True}, 'mount_settings': {'readonly': True}, 'provisioning_state_transition_time': {'readonly': True}, 'creation_time': {'readonly': True}, 'provisioning_state': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'vm_size': {'key': 'properties.vmSize', 'type': 'str'}, 'ssh_configuration': {'key': 'properties.sshConfiguration', 'type': 'SshConfiguration'}, 'data_disks': {'key': 'properties.dataDisks', 'type': 'DataDisks'}, 'subnet': {'key': 'properties.subnet', 'type': 'ResourceId'}, 'mount_settings': {'key': 'properties.mountSettings', 'type': 'MountSettings'}, 'provisioning_state_transition_time': {'key': 'properties.provisioningStateTransitionTime', 'type': 'iso-8601'}, 'creation_time': {'key': 'properties.creationTime', 'type': 'iso-8601'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, } def __init__( self, *, vm_size: Optional[str] = None, ssh_configuration: Optional["SshConfiguration"] = None, data_disks: Optional["DataDisks"] = None, subnet: Optional["ResourceId"] = None, **kwargs ): super(FileServer, self).__init__(**kwargs) self.vm_size = vm_size self.ssh_configuration = ssh_configuration self.data_disks = data_disks self.subnet = subnet self.mount_settings = None self.provisioning_state_transition_time = None self.creation_time = None self.provisioning_state = None class FileServerCreateParameters(msrest.serialization.Model): """File Server creation parameters. :param vm_size: The size of the virtual machine for the File Server. For information about available VM sizes from the Virtual Machines Marketplace, see Sizes for Virtual Machines (Linux). :type vm_size: str :param ssh_configuration: SSH configuration for the File Server node. :type ssh_configuration: ~batch_ai.models.SshConfiguration :param data_disks: Settings for the data disks which will be created for the File Server. :type data_disks: ~batch_ai.models.DataDisks :param subnet: Identifier of an existing virtual network subnet to put the File Server in. If not provided, a new virtual network and subnet will be created. :type subnet: ~batch_ai.models.ResourceId """ _attribute_map = { 'vm_size': {'key': 'properties.vmSize', 'type': 'str'}, 'ssh_configuration': {'key': 'properties.sshConfiguration', 'type': 'SshConfiguration'}, 'data_disks': {'key': 'properties.dataDisks', 'type': 'DataDisks'}, 'subnet': {'key': 'properties.subnet', 'type': 'ResourceId'}, } def __init__( self, *, vm_size: Optional[str] = None, ssh_configuration: Optional["SshConfiguration"] = None, data_disks: Optional["DataDisks"] = None, subnet: Optional["ResourceId"] = None, **kwargs ): super(FileServerCreateParameters, self).__init__(**kwargs) self.vm_size = vm_size self.ssh_configuration = ssh_configuration self.data_disks = data_disks self.subnet = subnet class FileServerListResult(msrest.serialization.Model): """Values returned by the File Server List operation. Variables are only populated by the server, and will be ignored when sending a request. :param value: The collection of File Servers. :type value: list[~batch_ai.models.FileServer] :ivar next_link: The continuation token. :vartype next_link: str """ _validation = { 'next_link': {'readonly': True}, } _attribute_map = { 'value': {'key': 'value', 'type': '[FileServer]'}, 'next_link': {'key': 'nextLink', 'type': 'str'}, } def __init__( self, *, value: Optional[List["FileServer"]] = None, **kwargs ): super(FileServerListResult, self).__init__(**kwargs) self.value = value self.next_link = None class FileServerReference(msrest.serialization.Model): """File Server mounting configuration. All required parameters must be populated in order to send to Azure. :param file_server: Required. Resource ID of the existing File Server to be mounted. :type file_server: ~batch_ai.models.ResourceId :param source_directory: File Server directory that needs to be mounted. If this property is not specified, the entire File Server will be mounted. :type source_directory: str :param relative_mount_path: Required. The relative path on the compute node where the File Server will be mounted. Note that all cluster level file servers will be mounted under $AZ_BATCHAI_MOUNT_ROOT location and all job level file servers will be mounted under $AZ_BATCHAI_JOB_MOUNT_ROOT. :type relative_mount_path: str :param mount_options: Mount options to be passed to mount command. :type mount_options: str """ _validation = { 'file_server': {'required': True}, 'relative_mount_path': {'required': True}, } _attribute_map = { 'file_server': {'key': 'fileServer', 'type': 'ResourceId'}, 'source_directory': {'key': 'sourceDirectory', 'type': 'str'}, 'relative_mount_path': {'key': 'relativeMountPath', 'type': 'str'}, 'mount_options': {'key': 'mountOptions', 'type': 'str'}, } def __init__( self, *, file_server: "ResourceId", relative_mount_path: str, source_directory: Optional[str] = None, mount_options: Optional[str] = None, **kwargs ): super(FileServerReference, self).__init__(**kwargs) self.file_server = file_server self.source_directory = source_directory self.relative_mount_path = relative_mount_path self.mount_options = mount_options class FileServersListByWorkspaceOptions(msrest.serialization.Model): """Parameter group. :param max_results: The maximum number of items to return in the response. A maximum of 1000 files can be returned. :type max_results: int """ _validation = { 'max_results': {'maximum': 1000, 'minimum': 1}, } _attribute_map = { 'max_results': {'key': 'maxResults', 'type': 'int'}, } def __init__( self, *, max_results: Optional[int] = 1000, **kwargs ): super(FileServersListByWorkspaceOptions, self).__init__(**kwargs) self.max_results = max_results class HorovodSettings(msrest.serialization.Model): """Specifies the settings for Horovod job. All required parameters must be populated in order to send to Azure. :param python_script_file_path: Required. The python script to execute. :type python_script_file_path: str :param python_interpreter_path: The path to the Python interpreter. :type python_interpreter_path: str :param command_line_args: Command line arguments that need to be passed to the python script. :type command_line_args: str :param process_count: Number of processes to launch for the job execution. The default value for this property is equal to nodeCount property. :type process_count: int """ _validation = { 'python_script_file_path': {'required': True}, } _attribute_map = { 'python_script_file_path': {'key': 'pythonScriptFilePath', 'type': 'str'}, 'python_interpreter_path': {'key': 'pythonInterpreterPath', 'type': 'str'}, 'command_line_args': {'key': 'commandLineArgs', 'type': 'str'}, 'process_count': {'key': 'processCount', 'type': 'int'}, } def __init__( self, *, python_script_file_path: str, python_interpreter_path: Optional[str] = None, command_line_args: Optional[str] = None, process_count: Optional[int] = None, **kwargs ): super(HorovodSettings, self).__init__(**kwargs) self.python_script_file_path = python_script_file_path self.python_interpreter_path = python_interpreter_path self.command_line_args = command_line_args self.process_count = process_count class ImageReference(msrest.serialization.Model): """The OS image reference. All required parameters must be populated in order to send to Azure. :param publisher: Required. Publisher of the image. :type publisher: str :param offer: Required. Offer of the image. :type offer: str :param sku: Required. SKU of the image. :type sku: str :param version: Version of the image. :type version: str :param virtual_machine_image_id: The ARM resource identifier of the virtual machine image for the compute nodes. This is of the form /subscriptions/{subscriptionId}/resourceGroups/{resourceGroup}/providers/Microsoft.Compute/images/{imageName}. The virtual machine image must be in the same region and subscription as the cluster. For information about the firewall settings for the Batch node agent to communicate with the Batch service see https://docs.microsoft.com/en-us/azure/batch/batch-api-basics#virtual-network-vnet-and-firewall-configuration. Note, you need to provide publisher, offer and sku of the base OS image of which the custom image has been derived from. :type virtual_machine_image_id: str """ _validation = { 'publisher': {'required': True}, 'offer': {'required': True}, 'sku': {'required': True}, } _attribute_map = { 'publisher': {'key': 'publisher', 'type': 'str'}, 'offer': {'key': 'offer', 'type': 'str'}, 'sku': {'key': 'sku', 'type': 'str'}, 'version': {'key': 'version', 'type': 'str'}, 'virtual_machine_image_id': {'key': 'virtualMachineImageId', 'type': 'str'}, } def __init__( self, *, publisher: str, offer: str, sku: str, version: Optional[str] = None, virtual_machine_image_id: Optional[str] = None, **kwargs ): super(ImageReference, self).__init__(**kwargs) self.publisher = publisher self.offer = offer self.sku = sku self.version = version self.virtual_machine_image_id = virtual_machine_image_id class ImageSourceRegistry(msrest.serialization.Model): """Information about docker image for the job. All required parameters must be populated in order to send to Azure. :param server_url: URL for image repository. :type server_url: str :param image: Required. The name of the image in the image repository. :type image: str :param credentials: Credentials to access the private docker repository. :type credentials: ~batch_ai.models.PrivateRegistryCredentials """ _validation = { 'image': {'required': True}, } _attribute_map = { 'server_url': {'key': 'serverUrl', 'type': 'str'}, 'image': {'key': 'image', 'type': 'str'}, 'credentials': {'key': 'credentials', 'type': 'PrivateRegistryCredentials'}, } def __init__( self, *, image: str, server_url: Optional[str] = None, credentials: Optional["PrivateRegistryCredentials"] = None, **kwargs ): super(ImageSourceRegistry, self).__init__(**kwargs) self.server_url = server_url self.image = image self.credentials = credentials class InputDirectory(msrest.serialization.Model): """Input directory for the job. All required parameters must be populated in order to send to Azure. :param id: Required. The ID for the input directory. The job can use AZ_BATCHAI\ *INPUT*\ :code:`<id>` environment variable to find the directory path, where :code:`<id>` is the value of id attribute. :type id: str :param path: Required. The path to the input directory. :type path: str """ _validation = { 'id': {'required': True}, 'path': {'required': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'path': {'key': 'path', 'type': 'str'}, } def __init__( self, *, id: str, path: str, **kwargs ): super(InputDirectory, self).__init__(**kwargs) self.id = id self.path = path class Job(ProxyResource): """Information about a Job. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: The ID of the resource. :vartype id: str :ivar name: The name of the resource. :vartype name: str :ivar type: The type of the resource. :vartype type: str :param scheduling_priority: Scheduling priority associated with the job. Possible values include: "low", "normal", "high". :type scheduling_priority: str or ~batch_ai.models.JobPriority :param cluster: Resource ID of the cluster associated with the job. :type cluster: ~batch_ai.models.ResourceId :param mount_volumes: Collection of mount volumes available to the job during execution. These volumes are mounted before the job execution and unmounted after the job completion. The volumes are mounted at location specified by $AZ_BATCHAI_JOB_MOUNT_ROOT environment variable. :type mount_volumes: ~batch_ai.models.MountVolumes :param node_count: The job will be gang scheduled on that many compute nodes. :type node_count: int :param container_settings: If the container was downloaded as part of cluster setup then the same container image will be used. If not provided, the job will run on the VM. :type container_settings: ~batch_ai.models.ContainerSettings :param tool_type: Possible values are: cntk, tensorflow, caffe, caffe2, chainer, pytorch, custom, custommpi, horovod. Possible values include: "cntk", "tensorflow", "caffe", "caffe2", "chainer", "horovod", "custommpi", "custom". :type tool_type: str or ~batch_ai.models.ToolType :param cntk_settings: CNTK (aka Microsoft Cognitive Toolkit) job settings. :type cntk_settings: ~batch_ai.models.CNTKsettings :param py_torch_settings: pyTorch job settings. :type py_torch_settings: ~batch_ai.models.PyTorchSettings :param tensor_flow_settings: TensorFlow job settings. :type tensor_flow_settings: ~batch_ai.models.TensorFlowSettings :param caffe_settings: Caffe job settings. :type caffe_settings: ~batch_ai.models.CaffeSettings :param caffe2_settings: Caffe2 job settings. :type caffe2_settings: ~batch_ai.models.Caffe2Settings :param chainer_settings: Chainer job settings. :type chainer_settings: ~batch_ai.models.ChainerSettings :param custom_toolkit_settings: Custom tool kit job settings. :type custom_toolkit_settings: ~batch_ai.models.CustomToolkitSettings :param custom_mpi_settings: Custom MPI job settings. :type custom_mpi_settings: ~batch_ai.models.CustomMpiSettings :param horovod_settings: Specifies the settings for Horovod job. :type horovod_settings: ~batch_ai.models.HorovodSettings :param job_preparation: The specified actions will run on all the nodes that are part of the job. :type job_preparation: ~batch_ai.models.JobPreparation :ivar job_output_directory_path_segment: A segment of job's output directories path created by Batch AI. Batch AI creates job's output directories under an unique path to avoid conflicts between jobs. This value contains a path segment generated by Batch AI to make the path unique and can be used to find the output directory on the node or mounted filesystem. :vartype job_output_directory_path_segment: str :param std_out_err_path_prefix: The path where the Batch AI service stores stdout, stderror and execution log of the job. :type std_out_err_path_prefix: str :param input_directories: A list of input directories for the job. :type input_directories: list[~batch_ai.models.InputDirectory] :param output_directories: A list of output directories for the job. :type output_directories: list[~batch_ai.models.OutputDirectory] :param environment_variables: A collection of user defined environment variables to be setup for the job. :type environment_variables: list[~batch_ai.models.EnvironmentVariable] :param secrets: A collection of user defined environment variables with secret values to be setup for the job. Server will never report values of these variables back. :type secrets: list[~batch_ai.models.EnvironmentVariableWithSecretValue] :param constraints: Constraints associated with the Job. :type constraints: ~batch_ai.models.JobPropertiesConstraints :ivar creation_time: The creation time of the job. :vartype creation_time: ~datetime.datetime :ivar provisioning_state: The provisioned state of the Batch AI job. Possible values include: "creating", "succeeded", "failed", "deleting". :vartype provisioning_state: str or ~batch_ai.models.ProvisioningState :ivar provisioning_state_transition_time: The time at which the job entered its current provisioning state. :vartype provisioning_state_transition_time: ~datetime.datetime :ivar execution_state: The current state of the job. Possible values are: queued - The job is queued and able to run. A job enters this state when it is created, or when it is awaiting a retry after a failed run. running - The job is running on a compute cluster. This includes job-level preparation such as downloading resource files or set up container specified on the job - it does not necessarily mean that the job command line has started executing. terminating - The job is terminated by the user, the terminate operation is in progress. succeeded - The job has completed running successfully and exited with exit code 0. failed - The job has finished unsuccessfully (failed with a non-zero exit code) and has exhausted its retry limit. A job is also marked as failed if an error occurred launching the job. Possible values include: "queued", "running", "terminating", "succeeded", "failed". :vartype execution_state: str or ~batch_ai.models.ExecutionState :ivar execution_state_transition_time: The time at which the job entered its current execution state. :vartype execution_state_transition_time: ~datetime.datetime :param execution_info: Information about the execution of a job. :type execution_info: ~batch_ai.models.JobPropertiesExecutionInfo """ _validation = { 'id': {'readonly': True}, 'name': {'readonly': True}, 'type': {'readonly': True}, 'job_output_directory_path_segment': {'readonly': True}, 'creation_time': {'readonly': True}, 'provisioning_state': {'readonly': True}, 'provisioning_state_transition_time': {'readonly': True}, 'execution_state': {'readonly': True}, 'execution_state_transition_time': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'scheduling_priority': {'key': 'properties.schedulingPriority', 'type': 'str'}, 'cluster': {'key': 'properties.cluster', 'type': 'ResourceId'}, 'mount_volumes': {'key': 'properties.mountVolumes', 'type': 'MountVolumes'}, 'node_count': {'key': 'properties.nodeCount', 'type': 'int'}, 'container_settings': {'key': 'properties.containerSettings', 'type': 'ContainerSettings'}, 'tool_type': {'key': 'properties.toolType', 'type': 'str'}, 'cntk_settings': {'key': 'properties.cntkSettings', 'type': 'CNTKsettings'}, 'py_torch_settings': {'key': 'properties.pyTorchSettings', 'type': 'PyTorchSettings'}, 'tensor_flow_settings': {'key': 'properties.tensorFlowSettings', 'type': 'TensorFlowSettings'}, 'caffe_settings': {'key': 'properties.caffeSettings', 'type': 'CaffeSettings'}, 'caffe2_settings': {'key': 'properties.caffe2Settings', 'type': 'Caffe2Settings'}, 'chainer_settings': {'key': 'properties.chainerSettings', 'type': 'ChainerSettings'}, 'custom_toolkit_settings': {'key': 'properties.customToolkitSettings', 'type': 'CustomToolkitSettings'}, 'custom_mpi_settings': {'key': 'properties.customMpiSettings', 'type': 'CustomMpiSettings'}, 'horovod_settings': {'key': 'properties.horovodSettings', 'type': 'HorovodSettings'}, 'job_preparation': {'key': 'properties.jobPreparation', 'type': 'JobPreparation'}, 'job_output_directory_path_segment': {'key': 'properties.jobOutputDirectoryPathSegment', 'type': 'str'}, 'std_out_err_path_prefix': {'key': 'properties.stdOutErrPathPrefix', 'type': 'str'}, 'input_directories': {'key': 'properties.inputDirectories', 'type': '[InputDirectory]'}, 'output_directories': {'key': 'properties.outputDirectories', 'type': '[OutputDirectory]'}, 'environment_variables': {'key': 'properties.environmentVariables', 'type': '[EnvironmentVariable]'}, 'secrets': {'key': 'properties.secrets', 'type': '[EnvironmentVariableWithSecretValue]'}, 'constraints': {'key': 'properties.constraints', 'type': 'JobPropertiesConstraints'}, 'creation_time': {'key': 'properties.creationTime', 'type': 'iso-8601'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'provisioning_state_transition_time': {'key': 'properties.provisioningStateTransitionTime', 'type': 'iso-8601'}, 'execution_state': {'key': 'properties.executionState', 'type': 'str'}, 'execution_state_transition_time': {'key': 'properties.executionStateTransitionTime', 'type': 'iso-8601'}, 'execution_info': {'key': 'properties.executionInfo', 'type': 'JobPropertiesExecutionInfo'}, } def __init__( self, *, scheduling_priority: Optional[Union[str, "JobPriority"]] = None, cluster: Optional["ResourceId"] = None, mount_volumes: Optional["MountVolumes"] = None, node_count: Optional[int] = None, container_settings: Optional["ContainerSettings"] = None, tool_type: Optional[Union[str, "ToolType"]] = None, cntk_settings: Optional["CNTKsettings"] = None, py_torch_settings: Optional["PyTorchSettings"] = None, tensor_flow_settings: Optional["TensorFlowSettings"] = None, caffe_settings: Optional["CaffeSettings"] = None, caffe2_settings: Optional["Caffe2Settings"] = None, chainer_settings: Optional["ChainerSettings"] = None, custom_toolkit_settings: Optional["CustomToolkitSettings"] = None, custom_mpi_settings: Optional["CustomMpiSettings"] = None, horovod_settings: Optional["HorovodSettings"] = None, job_preparation: Optional["JobPreparation"] = None, std_out_err_path_prefix: Optional[str] = None, input_directories: Optional[List["InputDirectory"]] = None, output_directories: Optional[List["OutputDirectory"]] = None, environment_variables: Optional[List["EnvironmentVariable"]] = None, secrets: Optional[List["EnvironmentVariableWithSecretValue"]] = None, constraints: Optional["JobPropertiesConstraints"] = None, execution_info: Optional["JobPropertiesExecutionInfo"] = None, **kwargs ): super(Job, self).__init__(**kwargs) self.scheduling_priority = scheduling_priority self.cluster = cluster self.mount_volumes = mount_volumes self.node_count = node_count self.container_settings = container_settings self.tool_type = tool_type self.cntk_settings = cntk_settings self.py_torch_settings = py_torch_settings self.tensor_flow_settings = tensor_flow_settings self.caffe_settings = caffe_settings self.caffe2_settings = caffe2_settings self.chainer_settings = chainer_settings self.custom_toolkit_settings = custom_toolkit_settings self.custom_mpi_settings = custom_mpi_settings self.horovod_settings = horovod_settings self.job_preparation = job_preparation self.job_output_directory_path_segment = None self.std_out_err_path_prefix = std_out_err_path_prefix self.input_directories = input_directories self.output_directories = output_directories self.environment_variables = environment_variables self.secrets = secrets self.constraints = constraints self.creation_time = None self.provisioning_state = None self.provisioning_state_transition_time = None self.execution_state = None self.execution_state_transition_time = None self.execution_info = execution_info class JobBasePropertiesConstraints(msrest.serialization.Model): """Constraints associated with the Job. :param max_wall_clock_time: Max time the job can run. Default value: 1 week. :type max_wall_clock_time: ~datetime.timedelta """ _attribute_map = { 'max_wall_clock_time': {'key': 'maxWallClockTime', 'type': 'duration'}, } def __init__( self, *, max_wall_clock_time: Optional[datetime.timedelta] = "7.00:00:00", **kwargs ): super(JobBasePropertiesConstraints, self).__init__(**kwargs) self.max_wall_clock_time = max_wall_clock_time class JobCreateParameters(msrest.serialization.Model): """Job creation parameters. :param scheduling_priority: Scheduling priority associated with the job. Possible values: low, normal, high. Possible values include: "low", "normal", "high". :type scheduling_priority: str or ~batch_ai.models.JobPriority :param cluster: Resource ID of the cluster on which this job will run. :type cluster: ~batch_ai.models.ResourceId :param mount_volumes: Information on mount volumes to be used by the job. These volumes will be mounted before the job execution and will be unmounted after the job completion. The volumes will be mounted at location specified by $AZ_BATCHAI_JOB_MOUNT_ROOT environment variable. :type mount_volumes: ~batch_ai.models.MountVolumes :param node_count: Number of compute nodes to run the job on. The job will be gang scheduled on that many compute nodes. :type node_count: int :param container_settings: Docker container settings for the job. If not provided, the job will run directly on the node. :type container_settings: ~batch_ai.models.ContainerSettings :param cntk_settings: Settings for CNTK (aka Microsoft Cognitive Toolkit) job. :type cntk_settings: ~batch_ai.models.CNTKsettings :param py_torch_settings: Settings for pyTorch job. :type py_torch_settings: ~batch_ai.models.PyTorchSettings :param tensor_flow_settings: Settings for Tensor Flow job. :type tensor_flow_settings: ~batch_ai.models.TensorFlowSettings :param caffe_settings: Settings for Caffe job. :type caffe_settings: ~batch_ai.models.CaffeSettings :param caffe2_settings: Settings for Caffe2 job. :type caffe2_settings: ~batch_ai.models.Caffe2Settings :param chainer_settings: Settings for Chainer job. :type chainer_settings: ~batch_ai.models.ChainerSettings :param custom_toolkit_settings: Settings for custom tool kit job. :type custom_toolkit_settings: ~batch_ai.models.CustomToolkitSettings :param custom_mpi_settings: Settings for custom MPI job. :type custom_mpi_settings: ~batch_ai.models.CustomMpiSettings :param horovod_settings: Settings for Horovod job. :type horovod_settings: ~batch_ai.models.HorovodSettings :param job_preparation: A command line to be executed on each node allocated for the job before tool kit is launched. :type job_preparation: ~batch_ai.models.JobPreparation :param std_out_err_path_prefix: The path where the Batch AI service will store stdout, stderror and execution log of the job. :type std_out_err_path_prefix: str :param input_directories: A list of input directories for the job. :type input_directories: list[~batch_ai.models.InputDirectory] :param output_directories: A list of output directories for the job. :type output_directories: list[~batch_ai.models.OutputDirectory] :param environment_variables: A list of user defined environment variables which will be setup for the job. :type environment_variables: list[~batch_ai.models.EnvironmentVariable] :param secrets: A list of user defined environment variables with secret values which will be setup for the job. Server will never report values of these variables back. :type secrets: list[~batch_ai.models.EnvironmentVariableWithSecretValue] :param constraints: Constraints associated with the Job. :type constraints: ~batch_ai.models.JobBasePropertiesConstraints """ _attribute_map = { 'scheduling_priority': {'key': 'properties.schedulingPriority', 'type': 'str'}, 'cluster': {'key': 'properties.cluster', 'type': 'ResourceId'}, 'mount_volumes': {'key': 'properties.mountVolumes', 'type': 'MountVolumes'}, 'node_count': {'key': 'properties.nodeCount', 'type': 'int'}, 'container_settings': {'key': 'properties.containerSettings', 'type': 'ContainerSettings'}, 'cntk_settings': {'key': 'properties.cntkSettings', 'type': 'CNTKsettings'}, 'py_torch_settings': {'key': 'properties.pyTorchSettings', 'type': 'PyTorchSettings'}, 'tensor_flow_settings': {'key': 'properties.tensorFlowSettings', 'type': 'TensorFlowSettings'}, 'caffe_settings': {'key': 'properties.caffeSettings', 'type': 'CaffeSettings'}, 'caffe2_settings': {'key': 'properties.caffe2Settings', 'type': 'Caffe2Settings'}, 'chainer_settings': {'key': 'properties.chainerSettings', 'type': 'ChainerSettings'}, 'custom_toolkit_settings': {'key': 'properties.customToolkitSettings', 'type': 'CustomToolkitSettings'}, 'custom_mpi_settings': {'key': 'properties.customMpiSettings', 'type': 'CustomMpiSettings'}, 'horovod_settings': {'key': 'properties.horovodSettings', 'type': 'HorovodSettings'}, 'job_preparation': {'key': 'properties.jobPreparation', 'type': 'JobPreparation'}, 'std_out_err_path_prefix': {'key': 'properties.stdOutErrPathPrefix', 'type': 'str'}, 'input_directories': {'key': 'properties.inputDirectories', 'type': '[InputDirectory]'}, 'output_directories': {'key': 'properties.outputDirectories', 'type': '[OutputDirectory]'}, 'environment_variables': {'key': 'properties.environmentVariables', 'type': '[EnvironmentVariable]'}, 'secrets': {'key': 'properties.secrets', 'type': '[EnvironmentVariableWithSecretValue]'}, 'constraints': {'key': 'properties.constraints', 'type': 'JobBasePropertiesConstraints'}, } def __init__( self, *, scheduling_priority: Optional[Union[str, "JobPriority"]] = None, cluster: Optional["ResourceId"] = None, mount_volumes: Optional["MountVolumes"] = None, node_count: Optional[int] = None, container_settings: Optional["ContainerSettings"] = None, cntk_settings: Optional["CNTKsettings"] = None, py_torch_settings: Optional["PyTorchSettings"] = None, tensor_flow_settings: Optional["TensorFlowSettings"] = None, caffe_settings: Optional["CaffeSettings"] = None, caffe2_settings: Optional["Caffe2Settings"] = None, chainer_settings: Optional["ChainerSettings"] = None, custom_toolkit_settings: Optional["CustomToolkitSettings"] = None, custom_mpi_settings: Optional["CustomMpiSettings"] = None, horovod_settings: Optional["HorovodSettings"] = None, job_preparation: Optional["JobPreparation"] = None, std_out_err_path_prefix: Optional[str] = None, input_directories: Optional[List["InputDirectory"]] = None, output_directories: Optional[List["OutputDirectory"]] = None, environment_variables: Optional[List["EnvironmentVariable"]] = None, secrets: Optional[List["EnvironmentVariableWithSecretValue"]] = None, constraints: Optional["JobBasePropertiesConstraints"] = None, **kwargs ): super(JobCreateParameters, self).__init__(**kwargs) self.scheduling_priority = scheduling_priority self.cluster = cluster self.mount_volumes = mount_volumes self.node_count = node_count self.container_settings = container_settings self.cntk_settings = cntk_settings self.py_torch_settings = py_torch_settings self.tensor_flow_settings = tensor_flow_settings self.caffe_settings = caffe_settings self.caffe2_settings = caffe2_settings self.chainer_settings = chainer_settings self.custom_toolkit_settings = custom_toolkit_settings self.custom_mpi_settings = custom_mpi_settings self.horovod_settings = horovod_settings self.job_preparation = job_preparation self.std_out_err_path_prefix = std_out_err_path_prefix self.input_directories = input_directories self.output_directories = output_directories self.environment_variables = environment_variables self.secrets = secrets self.constraints = constraints class JobListResult(msrest.serialization.Model): """Values returned by the List operation. Variables are only populated by the server, and will be ignored when sending a request. :ivar value: The collection of jobs. :vartype value: list[~batch_ai.models.Job] :ivar next_link: The continuation token. :vartype next_link: str """ _validation = { 'value': {'readonly': True}, 'next_link': {'readonly': True}, } _attribute_map = { 'value': {'key': 'value', 'type': '[Job]'}, 'next_link': {'key': 'nextLink', 'type': 'str'}, } def __init__( self, **kwargs ): super(JobListResult, self).__init__(**kwargs) self.value = None self.next_link = None class JobPreparation(msrest.serialization.Model): """Job preparation settings. All required parameters must be populated in order to send to Azure. :param command_line: Required. The command line to execute. If containerSettings is specified on the job, this commandLine will be executed in the same container as job. Otherwise it will be executed on the node. :type command_line: str """ _validation = { 'command_line': {'required': True}, } _attribute_map = { 'command_line': {'key': 'commandLine', 'type': 'str'}, } def __init__( self, *, command_line: str, **kwargs ): super(JobPreparation, self).__init__(**kwargs) self.command_line = command_line class JobPropertiesConstraints(msrest.serialization.Model): """Constraints associated with the Job. :param max_wall_clock_time: Max time the job can run. Default value: 1 week. :type max_wall_clock_time: ~datetime.timedelta """ _attribute_map = { 'max_wall_clock_time': {'key': 'maxWallClockTime', 'type': 'duration'}, } def __init__( self, *, max_wall_clock_time: Optional[datetime.timedelta] = "7.00:00:00", **kwargs ): super(JobPropertiesConstraints, self).__init__(**kwargs) self.max_wall_clock_time = max_wall_clock_time class JobPropertiesExecutionInfo(msrest.serialization.Model): """Information about the execution of a job. Variables are only populated by the server, and will be ignored when sending a request. :ivar start_time: The time at which the job started running. 'Running' corresponds to the running state. If the job has been restarted or retried, this is the most recent time at which the job started running. This property is present only for job that are in the running or completed state. :vartype start_time: ~datetime.datetime :ivar end_time: The time at which the job completed. This property is only returned if the job is in completed state. :vartype end_time: ~datetime.datetime :ivar exit_code: The exit code of the job. This property is only returned if the job is in completed state. :vartype exit_code: int :ivar errors: A collection of errors encountered by the service during job execution. :vartype errors: list[~batch_ai.models.BatchAIError] """ _validation = { 'start_time': {'readonly': True}, 'end_time': {'readonly': True}, 'exit_code': {'readonly': True}, 'errors': {'readonly': True}, } _attribute_map = { 'start_time': {'key': 'startTime', 'type': 'iso-8601'}, 'end_time': {'key': 'endTime', 'type': 'iso-8601'}, 'exit_code': {'key': 'exitCode', 'type': 'int'}, 'errors': {'key': 'errors', 'type': '[BatchAIError]'}, } def __init__( self, **kwargs ): super(JobPropertiesExecutionInfo, self).__init__(**kwargs) self.start_time = None self.end_time = None self.exit_code = None self.errors = None class JobsListByExperimentOptions(msrest.serialization.Model): """Parameter group. :param max_results: The maximum number of items to return in the response. A maximum of 1000 files can be returned. :type max_results: int """ _validation = { 'max_results': {'maximum': 1000, 'minimum': 1}, } _attribute_map = { 'max_results': {'key': 'maxResults', 'type': 'int'}, } def __init__( self, *, max_results: Optional[int] = 1000, **kwargs ): super(JobsListByExperimentOptions, self).__init__(**kwargs) self.max_results = max_results class JobsListOutputFilesOptions(msrest.serialization.Model): """Parameter group. All required parameters must be populated in order to send to Azure. :param outputdirectoryid: Required. Id of the job output directory. This is the OutputDirectory-->id parameter that is given by the user during Create Job. :type outputdirectoryid: str :param directory: The path to the directory. :type directory: str :param linkexpiryinminutes: The number of minutes after which the download link will expire. :type linkexpiryinminutes: int :param max_results: The maximum number of items to return in the response. A maximum of 1000 files can be returned. :type max_results: int """ _validation = { 'outputdirectoryid': {'required': True}, 'linkexpiryinminutes': {'maximum': 600, 'minimum': 5}, 'max_results': {'maximum': 1000, 'minimum': 1}, } _attribute_map = { 'outputdirectoryid': {'key': 'outputdirectoryid', 'type': 'str'}, 'directory': {'key': 'directory', 'type': 'str'}, 'linkexpiryinminutes': {'key': 'linkexpiryinminutes', 'type': 'int'}, 'max_results': {'key': 'maxResults', 'type': 'int'}, } def __init__( self, *, outputdirectoryid: str, directory: Optional[str] = ".", linkexpiryinminutes: Optional[int] = 60, max_results: Optional[int] = 1000, **kwargs ): super(JobsListOutputFilesOptions, self).__init__(**kwargs) self.outputdirectoryid = outputdirectoryid self.directory = directory self.linkexpiryinminutes = linkexpiryinminutes self.max_results = max_results class KeyVaultSecretReference(msrest.serialization.Model): """Key Vault Secret reference. All required parameters must be populated in order to send to Azure. :param source_vault: Required. Fully qualified resource identifier of the Key Vault. :type source_vault: ~batch_ai.models.ResourceId :param secret_url: Required. The URL referencing a secret in the Key Vault. :type secret_url: str """ _validation = { 'source_vault': {'required': True}, 'secret_url': {'required': True}, } _attribute_map = { 'source_vault': {'key': 'sourceVault', 'type': 'ResourceId'}, 'secret_url': {'key': 'secretUrl', 'type': 'str'}, } def __init__( self, *, source_vault: "ResourceId", secret_url: str, **kwargs ): super(KeyVaultSecretReference, self).__init__(**kwargs) self.source_vault = source_vault self.secret_url = secret_url class ListUsagesResult(msrest.serialization.Model): """The List Usages operation response. Variables are only populated by the server, and will be ignored when sending a request. :ivar value: The list of compute resource usages. :vartype value: list[~batch_ai.models.Usage] :ivar next_link: The URI to fetch the next page of compute resource usage information. Call ListNext() with this to fetch the next page of compute resource usage information. :vartype next_link: str """ _validation = { 'value': {'readonly': True}, 'next_link': {'readonly': True}, } _attribute_map = { 'value': {'key': 'value', 'type': '[Usage]'}, 'next_link': {'key': 'nextLink', 'type': 'str'}, } def __init__( self, **kwargs ): super(ListUsagesResult, self).__init__(**kwargs) self.value = None self.next_link = None class ManualScaleSettings(msrest.serialization.Model): """Manual scale settings for the cluster. All required parameters must be populated in order to send to Azure. :param target_node_count: Required. The desired number of compute nodes in the Cluster. Default is 0. :type target_node_count: int :param node_deallocation_option: An action to be performed when the cluster size is decreasing. The default value is requeue. Possible values include: "requeue", "terminate", "waitforjobcompletion". Default value: "requeue". :type node_deallocation_option: str or ~batch_ai.models.DeallocationOption """ _validation = { 'target_node_count': {'required': True}, } _attribute_map = { 'target_node_count': {'key': 'targetNodeCount', 'type': 'int'}, 'node_deallocation_option': {'key': 'nodeDeallocationOption', 'type': 'str'}, } def __init__( self, *, target_node_count: int, node_deallocation_option: Optional[Union[str, "DeallocationOption"]] = "requeue", **kwargs ): super(ManualScaleSettings, self).__init__(**kwargs) self.target_node_count = target_node_count self.node_deallocation_option = node_deallocation_option class MountSettings(msrest.serialization.Model): """File Server mount Information. :param mount_point: Path where the data disks are mounted on the File Server. :type mount_point: str :param file_server_public_ip: Public IP address of the File Server which can be used to SSH to the node from outside of the subnet. :type file_server_public_ip: str :param file_server_internal_ip: Internal IP address of the File Server which can be used to access the File Server from within the subnet. :type file_server_internal_ip: str """ _attribute_map = { 'mount_point': {'key': 'mountPoint', 'type': 'str'}, 'file_server_public_ip': {'key': 'fileServerPublicIP', 'type': 'str'}, 'file_server_internal_ip': {'key': 'fileServerInternalIP', 'type': 'str'}, } def __init__( self, *, mount_point: Optional[str] = None, file_server_public_ip: Optional[str] = None, file_server_internal_ip: Optional[str] = None, **kwargs ): super(MountSettings, self).__init__(**kwargs) self.mount_point = mount_point self.file_server_public_ip = file_server_public_ip self.file_server_internal_ip = file_server_internal_ip class MountVolumes(msrest.serialization.Model): """Details of volumes to mount on the cluster. :param azure_file_shares: A collection of Azure File Shares that are to be mounted to the cluster nodes. :type azure_file_shares: list[~batch_ai.models.AzureFileShareReference] :param azure_blob_file_systems: A collection of Azure Blob Containers that are to be mounted to the cluster nodes. :type azure_blob_file_systems: list[~batch_ai.models.AzureBlobFileSystemReference] :param file_servers: A collection of Batch AI File Servers that are to be mounted to the cluster nodes. :type file_servers: list[~batch_ai.models.FileServerReference] :param unmanaged_file_systems: A collection of unmanaged file systems that are to be mounted to the cluster nodes. :type unmanaged_file_systems: list[~batch_ai.models.UnmanagedFileSystemReference] """ _attribute_map = { 'azure_file_shares': {'key': 'azureFileShares', 'type': '[AzureFileShareReference]'}, 'azure_blob_file_systems': {'key': 'azureBlobFileSystems', 'type': '[AzureBlobFileSystemReference]'}, 'file_servers': {'key': 'fileServers', 'type': '[FileServerReference]'}, 'unmanaged_file_systems': {'key': 'unmanagedFileSystems', 'type': '[UnmanagedFileSystemReference]'}, } def __init__( self, *, azure_file_shares: Optional[List["AzureFileShareReference"]] = None, azure_blob_file_systems: Optional[List["AzureBlobFileSystemReference"]] = None, file_servers: Optional[List["FileServerReference"]] = None, unmanaged_file_systems: Optional[List["UnmanagedFileSystemReference"]] = None, **kwargs ): super(MountVolumes, self).__init__(**kwargs) self.azure_file_shares = azure_file_shares self.azure_blob_file_systems = azure_blob_file_systems self.file_servers = file_servers self.unmanaged_file_systems = unmanaged_file_systems class NameValuePair(msrest.serialization.Model): """Name-value pair. :param name: The name in the name-value pair. :type name: str :param value: The value in the name-value pair. :type value: str """ _attribute_map = { 'name': {'key': 'name', 'type': 'str'}, 'value': {'key': 'value', 'type': 'str'}, } def __init__( self, *, name: Optional[str] = None, value: Optional[str] = None, **kwargs ): super(NameValuePair, self).__init__(**kwargs) self.name = name self.value = value class NodeSetup(msrest.serialization.Model): """Node setup settings. :param setup_task: Setup task to run on cluster nodes when nodes got created or rebooted. The setup task code needs to be idempotent. Generally the setup task is used to download static data that is required for all jobs that run on the cluster VMs and/or to download/install software. :type setup_task: ~batch_ai.models.SetupTask :param mount_volumes: Mount volumes to be available to setup task and all jobs executing on the cluster. The volumes will be mounted at location specified by $AZ_BATCHAI_MOUNT_ROOT environment variable. :type mount_volumes: ~batch_ai.models.MountVolumes :param performance_counters_settings: Settings for performance counters collecting and uploading. :type performance_counters_settings: ~batch_ai.models.PerformanceCountersSettings """ _attribute_map = { 'setup_task': {'key': 'setupTask', 'type': 'SetupTask'}, 'mount_volumes': {'key': 'mountVolumes', 'type': 'MountVolumes'}, 'performance_counters_settings': {'key': 'performanceCountersSettings', 'type': 'PerformanceCountersSettings'}, } def __init__( self, *, setup_task: Optional["SetupTask"] = None, mount_volumes: Optional["MountVolumes"] = None, performance_counters_settings: Optional["PerformanceCountersSettings"] = None, **kwargs ): super(NodeSetup, self).__init__(**kwargs) self.setup_task = setup_task self.mount_volumes = mount_volumes self.performance_counters_settings = performance_counters_settings class NodeStateCounts(msrest.serialization.Model): """Counts of various compute node states on the cluster. Variables are only populated by the server, and will be ignored when sending a request. :ivar idle_node_count: Number of compute nodes in idle state. :vartype idle_node_count: int :ivar running_node_count: Number of compute nodes which are running jobs. :vartype running_node_count: int :ivar preparing_node_count: Number of compute nodes which are being prepared. :vartype preparing_node_count: int :ivar unusable_node_count: Number of compute nodes which are in unusable state. :vartype unusable_node_count: int :ivar leaving_node_count: Number of compute nodes which are leaving the cluster. :vartype leaving_node_count: int """ _validation = { 'idle_node_count': {'readonly': True}, 'running_node_count': {'readonly': True}, 'preparing_node_count': {'readonly': True}, 'unusable_node_count': {'readonly': True}, 'leaving_node_count': {'readonly': True}, } _attribute_map = { 'idle_node_count': {'key': 'idleNodeCount', 'type': 'int'}, 'running_node_count': {'key': 'runningNodeCount', 'type': 'int'}, 'preparing_node_count': {'key': 'preparingNodeCount', 'type': 'int'}, 'unusable_node_count': {'key': 'unusableNodeCount', 'type': 'int'}, 'leaving_node_count': {'key': 'leavingNodeCount', 'type': 'int'}, } def __init__( self, **kwargs ): super(NodeStateCounts, self).__init__(**kwargs) self.idle_node_count = None self.running_node_count = None self.preparing_node_count = None self.unusable_node_count = None self.leaving_node_count = None class Operation(msrest.serialization.Model): """Details of a REST API operation. Variables are only populated by the server, and will be ignored when sending a request. :ivar name: This is of the format {provider}/{resource}/{operation}. :vartype name: str :param display: The object that describes the operation. :type display: ~batch_ai.models.OperationDisplay :ivar origin: The intended executor of the operation. :vartype origin: str :param properties: Any object. :type properties: any """ _validation = { 'name': {'readonly': True}, 'origin': {'readonly': True}, } _attribute_map = { 'name': {'key': 'name', 'type': 'str'}, 'display': {'key': 'display', 'type': 'OperationDisplay'}, 'origin': {'key': 'origin', 'type': 'str'}, 'properties': {'key': 'properties', 'type': 'object'}, } def __init__( self, *, display: Optional["OperationDisplay"] = None, properties: Optional[Any] = None, **kwargs ): super(Operation, self).__init__(**kwargs) self.name = None self.display = display self.origin = None self.properties = properties class OperationDisplay(msrest.serialization.Model): """The object that describes the operation. Variables are only populated by the server, and will be ignored when sending a request. :ivar provider: Friendly name of the resource provider. :vartype provider: str :ivar operation: For example: read, write, delete, or listKeys/action. :vartype operation: str :ivar resource: The resource type on which the operation is performed. :vartype resource: str :ivar description: The friendly name of the operation. :vartype description: str """ _validation = { 'provider': {'readonly': True}, 'operation': {'readonly': True}, 'resource': {'readonly': True}, 'description': {'readonly': True}, } _attribute_map = { 'provider': {'key': 'provider', 'type': 'str'}, 'operation': {'key': 'operation', 'type': 'str'}, 'resource': {'key': 'resource', 'type': 'str'}, 'description': {'key': 'description', 'type': 'str'}, } def __init__( self, **kwargs ): super(OperationDisplay, self).__init__(**kwargs) self.provider = None self.operation = None self.resource = None self.description = None class OperationListResult(msrest.serialization.Model): """Contains the list of all operations supported by BatchAI resource provider. Variables are only populated by the server, and will be ignored when sending a request. :ivar value: The list of operations supported by the resource provider. :vartype value: list[~batch_ai.models.Operation] :ivar next_link: The URL to get the next set of operation list results if there are any. :vartype next_link: str """ _validation = { 'value': {'readonly': True}, 'next_link': {'readonly': True}, } _attribute_map = { 'value': {'key': 'value', 'type': '[Operation]'}, 'next_link': {'key': 'nextLink', 'type': 'str'}, } def __init__( self, **kwargs ): super(OperationListResult, self).__init__(**kwargs) self.value = None self.next_link = None class OutputDirectory(msrest.serialization.Model): """Output directory for the job. All required parameters must be populated in order to send to Azure. :param id: Required. The ID of the output directory. The job can use AZ_BATCHAI\ *OUTPUT*\ :code:`<id>` environment variable to find the directory path, where :code:`<id>` is the value of id attribute. :type id: str :param path_prefix: Required. The prefix path where the output directory will be created. Note, this is an absolute path to prefix. E.g. $AZ_BATCHAI_MOUNT_ROOT/MyNFS/MyLogs. The full path to the output directory by combining pathPrefix, jobOutputDirectoryPathSegment (reported by get job) and pathSuffix. :type path_prefix: str :param path_suffix: The suffix path where the output directory will be created. E.g. models. You can find the full path to the output directory by combining pathPrefix, jobOutputDirectoryPathSegment (reported by get job) and pathSuffix. :type path_suffix: str """ _validation = { 'id': {'required': True}, 'path_prefix': {'required': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'path_prefix': {'key': 'pathPrefix', 'type': 'str'}, 'path_suffix': {'key': 'pathSuffix', 'type': 'str'}, } def __init__( self, *, id: str, path_prefix: str, path_suffix: Optional[str] = None, **kwargs ): super(OutputDirectory, self).__init__(**kwargs) self.id = id self.path_prefix = path_prefix self.path_suffix = path_suffix class PerformanceCountersSettings(msrest.serialization.Model): """Performance counters reporting settings. All required parameters must be populated in order to send to Azure. :param app_insights_reference: Required. Azure Application Insights information for performance counters reporting. If provided, Batch AI will upload node performance counters to the corresponding Azure Application Insights account. :type app_insights_reference: ~batch_ai.models.AppInsightsReference """ _validation = { 'app_insights_reference': {'required': True}, } _attribute_map = { 'app_insights_reference': {'key': 'appInsightsReference', 'type': 'AppInsightsReference'}, } def __init__( self, *, app_insights_reference: "AppInsightsReference", **kwargs ): super(PerformanceCountersSettings, self).__init__(**kwargs) self.app_insights_reference = app_insights_reference class PrivateRegistryCredentials(msrest.serialization.Model): """Credentials to access a container image in a private repository. All required parameters must be populated in order to send to Azure. :param username: Required. User name to login to the repository. :type username: str :param password: User password to login to the docker repository. One of password or passwordSecretReference must be specified. :type password: str :param password_secret_reference: KeyVault Secret storing the password. Users can store their secrets in Azure KeyVault and pass it to the Batch AI service to integrate with KeyVault. One of password or passwordSecretReference must be specified. :type password_secret_reference: ~batch_ai.models.KeyVaultSecretReference """ _validation = { 'username': {'required': True}, } _attribute_map = { 'username': {'key': 'username', 'type': 'str'}, 'password': {'key': 'password', 'type': 'str'}, 'password_secret_reference': {'key': 'passwordSecretReference', 'type': 'KeyVaultSecretReference'}, } def __init__( self, *, username: str, password: Optional[str] = None, password_secret_reference: Optional["KeyVaultSecretReference"] = None, **kwargs ): super(PrivateRegistryCredentials, self).__init__(**kwargs) self.username = username self.password = password self.password_secret_reference = password_secret_reference class PyTorchSettings(msrest.serialization.Model): """pyTorch job settings. All required parameters must be populated in order to send to Azure. :param python_script_file_path: Required. The python script to execute. :type python_script_file_path: str :param python_interpreter_path: The path to the Python interpreter. :type python_interpreter_path: str :param command_line_args: Command line arguments that need to be passed to the python script. :type command_line_args: str :param process_count: Number of processes to launch for the job execution. The default value for this property is equal to nodeCount property. :type process_count: int :param communication_backend: Type of the communication backend for distributed jobs. Valid values are 'TCP', 'Gloo' or 'MPI'. Not required for non-distributed jobs. :type communication_backend: str """ _validation = { 'python_script_file_path': {'required': True}, } _attribute_map = { 'python_script_file_path': {'key': 'pythonScriptFilePath', 'type': 'str'}, 'python_interpreter_path': {'key': 'pythonInterpreterPath', 'type': 'str'}, 'command_line_args': {'key': 'commandLineArgs', 'type': 'str'}, 'process_count': {'key': 'processCount', 'type': 'int'}, 'communication_backend': {'key': 'communicationBackend', 'type': 'str'}, } def __init__( self, *, python_script_file_path: str, python_interpreter_path: Optional[str] = None, command_line_args: Optional[str] = None, process_count: Optional[int] = None, communication_backend: Optional[str] = None, **kwargs ): super(PyTorchSettings, self).__init__(**kwargs) self.python_script_file_path = python_script_file_path self.python_interpreter_path = python_interpreter_path self.command_line_args = command_line_args self.process_count = process_count self.communication_backend = communication_backend class RemoteLoginInformation(msrest.serialization.Model): """Login details to SSH to a compute node in cluster. Variables are only populated by the server, and will be ignored when sending a request. :ivar node_id: ID of the compute node. :vartype node_id: str :ivar ip_address: Public IP address of the compute node. :vartype ip_address: str :ivar port: SSH port number of the node. :vartype port: int """ _validation = { 'node_id': {'readonly': True}, 'ip_address': {'readonly': True}, 'port': {'readonly': True}, } _attribute_map = { 'node_id': {'key': 'nodeId', 'type': 'str'}, 'ip_address': {'key': 'ipAddress', 'type': 'str'}, 'port': {'key': 'port', 'type': 'int'}, } def __init__( self, **kwargs ): super(RemoteLoginInformation, self).__init__(**kwargs) self.node_id = None self.ip_address = None self.port = None class RemoteLoginInformationListResult(msrest.serialization.Model): """Values returned by the List operation. Variables are only populated by the server, and will be ignored when sending a request. :ivar value: The collection of returned remote login details. :vartype value: list[~batch_ai.models.RemoteLoginInformation] :ivar next_link: The continuation token. :vartype next_link: str """ _validation = { 'value': {'readonly': True}, 'next_link': {'readonly': True}, } _attribute_map = { 'value': {'key': 'value', 'type': '[RemoteLoginInformation]'}, 'next_link': {'key': 'nextLink', 'type': 'str'}, } def __init__( self, **kwargs ): super(RemoteLoginInformationListResult, self).__init__(**kwargs) self.value = None self.next_link = None class Resource(msrest.serialization.Model): """A definition of an Azure resource. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: The ID of the resource. :vartype id: str :ivar name: The name of the resource. :vartype name: str :ivar type: The type of the resource. :vartype type: str :ivar location: The location of the resource. :vartype location: str :ivar tags: A set of tags. The tags of the resource. :vartype tags: dict[str, str] """ _validation = { 'id': {'readonly': True}, 'name': {'readonly': True}, 'type': {'readonly': True}, 'location': {'readonly': True}, 'tags': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'location': {'key': 'location', 'type': 'str'}, 'tags': {'key': 'tags', 'type': '{str}'}, } def __init__( self, **kwargs ): super(Resource, self).__init__(**kwargs) self.id = None self.name = None self.type = None self.location = None self.tags = None class ResourceId(msrest.serialization.Model): """Represents a resource ID. For example, for a subnet, it is the resource URL for the subnet. All required parameters must be populated in order to send to Azure. :param id: Required. The ID of the resource. :type id: str """ _validation = { 'id': {'required': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, } def __init__( self, *, id: str, **kwargs ): super(ResourceId, self).__init__(**kwargs) self.id = id class ScaleSettings(msrest.serialization.Model): """At least one of manual or autoScale settings must be specified. Only one of manual or autoScale settings can be specified. If autoScale settings are specified, the system automatically scales the cluster up and down (within the supplied limits) based on the pending jobs on the cluster. :param manual: Manual scale settings for the cluster. :type manual: ~batch_ai.models.ManualScaleSettings :param auto_scale: Auto-scale settings for the cluster. :type auto_scale: ~batch_ai.models.AutoScaleSettings """ _attribute_map = { 'manual': {'key': 'manual', 'type': 'ManualScaleSettings'}, 'auto_scale': {'key': 'autoScale', 'type': 'AutoScaleSettings'}, } def __init__( self, *, manual: Optional["ManualScaleSettings"] = None, auto_scale: Optional["AutoScaleSettings"] = None, **kwargs ): super(ScaleSettings, self).__init__(**kwargs) self.manual = manual self.auto_scale = auto_scale class SetupTask(msrest.serialization.Model): """Specifies a setup task which can be used to customize the compute nodes of the cluster. Variables are only populated by the server, and will be ignored when sending a request. All required parameters must be populated in order to send to Azure. :param command_line: Required. The command line to be executed on each cluster's node after it being allocated or rebooted. The command is executed in a bash subshell as a root. :type command_line: str :param environment_variables: A collection of user defined environment variables to be set for setup task. :type environment_variables: list[~batch_ai.models.EnvironmentVariable] :param secrets: A collection of user defined environment variables with secret values to be set for the setup task. Server will never report values of these variables back. :type secrets: list[~batch_ai.models.EnvironmentVariableWithSecretValue] :param std_out_err_path_prefix: Required. The prefix of a path where the Batch AI service will upload the stdout, stderr and execution log of the setup task. :type std_out_err_path_prefix: str :ivar std_out_err_path_suffix: A path segment appended by Batch AI to stdOutErrPathPrefix to form a path where stdout, stderr and execution log of the setup task will be uploaded. Batch AI creates the setup task output directories under an unique path to avoid conflicts between different clusters. The full path can be obtained by concatenation of stdOutErrPathPrefix and stdOutErrPathSuffix. :vartype std_out_err_path_suffix: str """ _validation = { 'command_line': {'required': True}, 'std_out_err_path_prefix': {'required': True}, 'std_out_err_path_suffix': {'readonly': True}, } _attribute_map = { 'command_line': {'key': 'commandLine', 'type': 'str'}, 'environment_variables': {'key': 'environmentVariables', 'type': '[EnvironmentVariable]'}, 'secrets': {'key': 'secrets', 'type': '[EnvironmentVariableWithSecretValue]'}, 'std_out_err_path_prefix': {'key': 'stdOutErrPathPrefix', 'type': 'str'}, 'std_out_err_path_suffix': {'key': 'stdOutErrPathSuffix', 'type': 'str'}, } def __init__( self, *, command_line: str, std_out_err_path_prefix: str, environment_variables: Optional[List["EnvironmentVariable"]] = None, secrets: Optional[List["EnvironmentVariableWithSecretValue"]] = None, **kwargs ): super(SetupTask, self).__init__(**kwargs) self.command_line = command_line self.environment_variables = environment_variables self.secrets = secrets self.std_out_err_path_prefix = std_out_err_path_prefix self.std_out_err_path_suffix = None class SshConfiguration(msrest.serialization.Model): """SSH configuration. All required parameters must be populated in order to send to Azure. :param public_ips_to_allow: List of source IP ranges to allow SSH connection from. The default value is '*' (all source IPs are allowed). Maximum number of IP ranges that can be specified is 400. :type public_ips_to_allow: list[str] :param user_account_settings: Required. Settings for administrator user account to be created on a node. The account can be used to establish SSH connection to the node. :type user_account_settings: ~batch_ai.models.UserAccountSettings """ _validation = { 'user_account_settings': {'required': True}, } _attribute_map = { 'public_ips_to_allow': {'key': 'publicIPsToAllow', 'type': '[str]'}, 'user_account_settings': {'key': 'userAccountSettings', 'type': 'UserAccountSettings'}, } def __init__( self, *, user_account_settings: "UserAccountSettings", public_ips_to_allow: Optional[List[str]] = None, **kwargs ): super(SshConfiguration, self).__init__(**kwargs) self.public_ips_to_allow = public_ips_to_allow self.user_account_settings = user_account_settings class TensorFlowSettings(msrest.serialization.Model): """TensorFlow job settings. All required parameters must be populated in order to send to Azure. :param python_script_file_path: Required. The python script to execute. :type python_script_file_path: str :param python_interpreter_path: The path to the Python interpreter. :type python_interpreter_path: str :param master_command_line_args: Command line arguments that need to be passed to the python script for the master task. :type master_command_line_args: str :param worker_command_line_args: Command line arguments that need to be passed to the python script for the worker task. Optional for single process jobs. :type worker_command_line_args: str :param parameter_server_command_line_args: Command line arguments that need to be passed to the python script for the parameter server. Optional for single process jobs. :type parameter_server_command_line_args: str :param worker_count: The number of worker tasks. If specified, the value must be less than or equal to (nodeCount * numberOfGPUs per VM). If not specified, the default value is equal to nodeCount. This property can be specified only for distributed TensorFlow training. :type worker_count: int :param parameter_server_count: The number of parameter server tasks. If specified, the value must be less than or equal to nodeCount. If not specified, the default value is equal to 1 for distributed TensorFlow training. This property can be specified only for distributed TensorFlow training. :type parameter_server_count: int """ _validation = { 'python_script_file_path': {'required': True}, } _attribute_map = { 'python_script_file_path': {'key': 'pythonScriptFilePath', 'type': 'str'}, 'python_interpreter_path': {'key': 'pythonInterpreterPath', 'type': 'str'}, 'master_command_line_args': {'key': 'masterCommandLineArgs', 'type': 'str'}, 'worker_command_line_args': {'key': 'workerCommandLineArgs', 'type': 'str'}, 'parameter_server_command_line_args': {'key': 'parameterServerCommandLineArgs', 'type': 'str'}, 'worker_count': {'key': 'workerCount', 'type': 'int'}, 'parameter_server_count': {'key': 'parameterServerCount', 'type': 'int'}, } def __init__( self, *, python_script_file_path: str, python_interpreter_path: Optional[str] = None, master_command_line_args: Optional[str] = None, worker_command_line_args: Optional[str] = None, parameter_server_command_line_args: Optional[str] = None, worker_count: Optional[int] = None, parameter_server_count: Optional[int] = None, **kwargs ): super(TensorFlowSettings, self).__init__(**kwargs) self.python_script_file_path = python_script_file_path self.python_interpreter_path = python_interpreter_path self.master_command_line_args = master_command_line_args self.worker_command_line_args = worker_command_line_args self.parameter_server_command_line_args = parameter_server_command_line_args self.worker_count = worker_count self.parameter_server_count = parameter_server_count class UnmanagedFileSystemReference(msrest.serialization.Model): """Unmanaged file system mounting configuration. All required parameters must be populated in order to send to Azure. :param mount_command: Required. Mount command line. Note, Batch AI will append mount path to the command on its own. :type mount_command: str :param relative_mount_path: Required. The relative path on the compute node where the unmanaged file system will be mounted. Note that all cluster level unmanaged file systems will be mounted under $AZ_BATCHAI_MOUNT_ROOT location and all job level unmanaged file systems will be mounted under $AZ_BATCHAI_JOB_MOUNT_ROOT. :type relative_mount_path: str """ _validation = { 'mount_command': {'required': True}, 'relative_mount_path': {'required': True}, } _attribute_map = { 'mount_command': {'key': 'mountCommand', 'type': 'str'}, 'relative_mount_path': {'key': 'relativeMountPath', 'type': 'str'}, } def __init__( self, *, mount_command: str, relative_mount_path: str, **kwargs ): super(UnmanagedFileSystemReference, self).__init__(**kwargs) self.mount_command = mount_command self.relative_mount_path = relative_mount_path class Usage(msrest.serialization.Model): """Describes Batch AI Resource Usage. Variables are only populated by the server, and will be ignored when sending a request. :ivar unit: An enum describing the unit of usage measurement. Possible values include: "Count". :vartype unit: str or ~batch_ai.models.UsageUnit :ivar current_value: The current usage of the resource. :vartype current_value: int :ivar limit: The maximum permitted usage of the resource. :vartype limit: long :ivar name: The name of the type of usage. :vartype name: ~batch_ai.models.UsageName """ _validation = { 'unit': {'readonly': True}, 'current_value': {'readonly': True}, 'limit': {'readonly': True}, 'name': {'readonly': True}, } _attribute_map = { 'unit': {'key': 'unit', 'type': 'str'}, 'current_value': {'key': 'currentValue', 'type': 'int'}, 'limit': {'key': 'limit', 'type': 'long'}, 'name': {'key': 'name', 'type': 'UsageName'}, } def __init__( self, **kwargs ): super(Usage, self).__init__(**kwargs) self.unit = None self.current_value = None self.limit = None self.name = None class UsageName(msrest.serialization.Model): """The Usage Names. Variables are only populated by the server, and will be ignored when sending a request. :ivar value: The name of the resource. :vartype value: str :ivar localized_value: The localized name of the resource. :vartype localized_value: str """ _validation = { 'value': {'readonly': True}, 'localized_value': {'readonly': True}, } _attribute_map = { 'value': {'key': 'value', 'type': 'str'}, 'localized_value': {'key': 'localizedValue', 'type': 'str'}, } def __init__( self, **kwargs ): super(UsageName, self).__init__(**kwargs) self.value = None self.localized_value = None class UserAccountSettings(msrest.serialization.Model): """Settings for user account that gets created on each on the nodes of a cluster. All required parameters must be populated in order to send to Azure. :param admin_user_name: Required. Name of the administrator user account which can be used to SSH to nodes. :type admin_user_name: str :param admin_user_ssh_public_key: SSH public key of the administrator user account. :type admin_user_ssh_public_key: str :param admin_user_password: Password of the administrator user account. :type admin_user_password: str """ _validation = { 'admin_user_name': {'required': True}, } _attribute_map = { 'admin_user_name': {'key': 'adminUserName', 'type': 'str'}, 'admin_user_ssh_public_key': {'key': 'adminUserSshPublicKey', 'type': 'str'}, 'admin_user_password': {'key': 'adminUserPassword', 'type': 'str'}, } def __init__( self, *, admin_user_name: str, admin_user_ssh_public_key: Optional[str] = None, admin_user_password: Optional[str] = None, **kwargs ): super(UserAccountSettings, self).__init__(**kwargs) self.admin_user_name = admin_user_name self.admin_user_ssh_public_key = admin_user_ssh_public_key self.admin_user_password = admin_user_password class VirtualMachineConfiguration(msrest.serialization.Model): """VM configuration. :param image_reference: OS image reference for cluster nodes. :type image_reference: ~batch_ai.models.ImageReference """ _attribute_map = { 'image_reference': {'key': 'imageReference', 'type': 'ImageReference'}, } def __init__( self, *, image_reference: Optional["ImageReference"] = None, **kwargs ): super(VirtualMachineConfiguration, self).__init__(**kwargs) self.image_reference = image_reference class Workspace(Resource): """Batch AI Workspace information. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: The ID of the resource. :vartype id: str :ivar name: The name of the resource. :vartype name: str :ivar type: The type of the resource. :vartype type: str :ivar location: The location of the resource. :vartype location: str :ivar tags: A set of tags. The tags of the resource. :vartype tags: dict[str, str] :ivar creation_time: Time when the Workspace was created. :vartype creation_time: ~datetime.datetime :ivar provisioning_state: The provisioned state of the Workspace. Possible values include: "creating", "succeeded", "failed", "deleting". :vartype provisioning_state: str or ~batch_ai.models.ProvisioningState :ivar provisioning_state_transition_time: The time at which the workspace entered its current provisioning state. :vartype provisioning_state_transition_time: ~datetime.datetime """ _validation = { 'id': {'readonly': True}, 'name': {'readonly': True}, 'type': {'readonly': True}, 'location': {'readonly': True}, 'tags': {'readonly': True}, 'creation_time': {'readonly': True}, 'provisioning_state': {'readonly': True}, 'provisioning_state_transition_time': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'location': {'key': 'location', 'type': 'str'}, 'tags': {'key': 'tags', 'type': '{str}'}, 'creation_time': {'key': 'properties.creationTime', 'type': 'iso-8601'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'provisioning_state_transition_time': {'key': 'properties.provisioningStateTransitionTime', 'type': 'iso-8601'}, } def __init__( self, **kwargs ): super(Workspace, self).__init__(**kwargs) self.creation_time = None self.provisioning_state = None self.provisioning_state_transition_time = None class WorkspaceCreateParameters(msrest.serialization.Model): """Workspace creation parameters. All required parameters must be populated in order to send to Azure. :param location: Required. The region in which to create the Workspace. :type location: str :param tags: A set of tags. The user specified tags associated with the Workspace. :type tags: dict[str, str] """ _validation = { 'location': {'required': True}, } _attribute_map = { 'location': {'key': 'location', 'type': 'str'}, 'tags': {'key': 'tags', 'type': '{str}'}, } def __init__( self, *, location: str, tags: Optional[Dict[str, str]] = None, **kwargs ): super(WorkspaceCreateParameters, self).__init__(**kwargs) self.location = location self.tags = tags class WorkspaceListResult(msrest.serialization.Model): """Values returned by the List operation. Variables are only populated by the server, and will be ignored when sending a request. :ivar value: The collection of workspaces. :vartype value: list[~batch_ai.models.Workspace] :ivar next_link: The continuation token. :vartype next_link: str """ _validation = { 'value': {'readonly': True}, 'next_link': {'readonly': True}, } _attribute_map = { 'value': {'key': 'value', 'type': '[Workspace]'}, 'next_link': {'key': 'nextLink', 'type': 'str'}, } def __init__( self, **kwargs ): super(WorkspaceListResult, self).__init__(**kwargs) self.value = None self.next_link = None class WorkspacesListByResourceGroupOptions(msrest.serialization.Model): """Parameter group. :param max_results: The maximum number of items to return in the response. A maximum of 1000 files can be returned. :type max_results: int """ _validation = { 'max_results': {'maximum': 1000, 'minimum': 1}, } _attribute_map = { 'max_results': {'key': 'maxResults', 'type': 'int'}, } def __init__( self, *, max_results: Optional[int] = 1000, **kwargs ): super(WorkspacesListByResourceGroupOptions, self).__init__(**kwargs) self.max_results = max_results class WorkspacesListOptions(msrest.serialization.Model): """Parameter group. :param max_results: The maximum number of items to return in the response. A maximum of 1000 files can be returned. :type max_results: int """ _validation = { 'max_results': {'maximum': 1000, 'minimum': 1}, } _attribute_map = { 'max_results': {'key': 'maxResults', 'type': 'int'}, } def __init__( self, *, max_results: Optional[int] = 1000, **kwargs ): super(WorkspacesListOptions, self).__init__(**kwargs) self.max_results = max_results class WorkspaceUpdateParameters(msrest.serialization.Model): """Workspace update parameters. :param tags: A set of tags. The user specified tags associated with the Workspace. :type tags: dict[str, str] """ _attribute_map = { 'tags': {'key': 'tags', 'type': '{str}'}, } def __init__( self, *, tags: Optional[Dict[str, str]] = None, **kwargs ): super(WorkspaceUpdateParameters, self).__init__(**kwargs) self.tags = tags
azure-mgmt-batchai
/azure-mgmt-batchai-7.0.0b1.zip/azure-mgmt-batchai-7.0.0b1/azure/mgmt/batchai/models/_models_py3.py
_models_py3.py
import datetime from typing import Any, Dict, List, Optional, Union import msrest.serialization from ._batch_ai_enums import * class AppInsightsReference(msrest.serialization.Model): """Azure Application Insights information for performance counters reporting. All required parameters must be populated in order to send to Azure. :param component: Required. Azure Application Insights component resource ID. :type component: ~batch_ai.models.ResourceId :param instrumentation_key: Value of the Azure Application Insights instrumentation key. :type instrumentation_key: str :param instrumentation_key_secret_reference: KeyVault Store and Secret which contains Azure Application Insights instrumentation key. One of instrumentationKey or instrumentationKeySecretReference must be specified. :type instrumentation_key_secret_reference: ~batch_ai.models.KeyVaultSecretReference """ _validation = { 'component': {'required': True}, } _attribute_map = { 'component': {'key': 'component', 'type': 'ResourceId'}, 'instrumentation_key': {'key': 'instrumentationKey', 'type': 'str'}, 'instrumentation_key_secret_reference': {'key': 'instrumentationKeySecretReference', 'type': 'KeyVaultSecretReference'}, } def __init__( self, *, component: "ResourceId", instrumentation_key: Optional[str] = None, instrumentation_key_secret_reference: Optional["KeyVaultSecretReference"] = None, **kwargs ): super(AppInsightsReference, self).__init__(**kwargs) self.component = component self.instrumentation_key = instrumentation_key self.instrumentation_key_secret_reference = instrumentation_key_secret_reference class AutoScaleSettings(msrest.serialization.Model): """Auto-scale settings for the cluster. The system automatically scales the cluster up and down (within minimumNodeCount and maximumNodeCount) based on the number of queued and running jobs assigned to the cluster. All required parameters must be populated in order to send to Azure. :param minimum_node_count: Required. The minimum number of compute nodes the Batch AI service will try to allocate for the cluster. Note, the actual number of nodes can be less than the specified value if the subscription has not enough quota to fulfill the request. :type minimum_node_count: int :param maximum_node_count: Required. The maximum number of compute nodes the cluster can have. :type maximum_node_count: int :param initial_node_count: The number of compute nodes to allocate on cluster creation. Note that this value is used only during cluster creation. Default: 0. :type initial_node_count: int """ _validation = { 'minimum_node_count': {'required': True}, 'maximum_node_count': {'required': True}, } _attribute_map = { 'minimum_node_count': {'key': 'minimumNodeCount', 'type': 'int'}, 'maximum_node_count': {'key': 'maximumNodeCount', 'type': 'int'}, 'initial_node_count': {'key': 'initialNodeCount', 'type': 'int'}, } def __init__( self, *, minimum_node_count: int, maximum_node_count: int, initial_node_count: Optional[int] = 0, **kwargs ): super(AutoScaleSettings, self).__init__(**kwargs) self.minimum_node_count = minimum_node_count self.maximum_node_count = maximum_node_count self.initial_node_count = initial_node_count class AzureBlobFileSystemReference(msrest.serialization.Model): """Azure Blob Storage Container mounting configuration. All required parameters must be populated in order to send to Azure. :param account_name: Required. Name of the Azure storage account. :type account_name: str :param container_name: Required. Name of the Azure Blob Storage container to mount on the cluster. :type container_name: str :param credentials: Required. Information about the Azure storage credentials. :type credentials: ~batch_ai.models.AzureStorageCredentialsInfo :param relative_mount_path: Required. The relative path on the compute node where the Azure File container will be mounted. Note that all cluster level containers will be mounted under $AZ_BATCHAI_MOUNT_ROOT location and all job level containers will be mounted under $AZ_BATCHAI_JOB_MOUNT_ROOT. :type relative_mount_path: str :param mount_options: Mount options for mounting blobfuse file system. :type mount_options: str """ _validation = { 'account_name': {'required': True}, 'container_name': {'required': True}, 'credentials': {'required': True}, 'relative_mount_path': {'required': True}, } _attribute_map = { 'account_name': {'key': 'accountName', 'type': 'str'}, 'container_name': {'key': 'containerName', 'type': 'str'}, 'credentials': {'key': 'credentials', 'type': 'AzureStorageCredentialsInfo'}, 'relative_mount_path': {'key': 'relativeMountPath', 'type': 'str'}, 'mount_options': {'key': 'mountOptions', 'type': 'str'}, } def __init__( self, *, account_name: str, container_name: str, credentials: "AzureStorageCredentialsInfo", relative_mount_path: str, mount_options: Optional[str] = None, **kwargs ): super(AzureBlobFileSystemReference, self).__init__(**kwargs) self.account_name = account_name self.container_name = container_name self.credentials = credentials self.relative_mount_path = relative_mount_path self.mount_options = mount_options class AzureFileShareReference(msrest.serialization.Model): """Azure File Share mounting configuration. All required parameters must be populated in order to send to Azure. :param account_name: Required. Name of the Azure storage account. :type account_name: str :param azure_file_url: Required. URL to access the Azure File. :type azure_file_url: str :param credentials: Required. Information about the Azure storage credentials. :type credentials: ~batch_ai.models.AzureStorageCredentialsInfo :param relative_mount_path: Required. The relative path on the compute node where the Azure File share will be mounted. Note that all cluster level file shares will be mounted under $AZ_BATCHAI_MOUNT_ROOT location and all job level file shares will be mounted under $AZ_BATCHAI_JOB_MOUNT_ROOT. :type relative_mount_path: str :param file_mode: File mode for files on the mounted file share. Default value: 0777. :type file_mode: str :param directory_mode: File mode for directories on the mounted file share. Default value: 0777. :type directory_mode: str """ _validation = { 'account_name': {'required': True}, 'azure_file_url': {'required': True}, 'credentials': {'required': True}, 'relative_mount_path': {'required': True}, } _attribute_map = { 'account_name': {'key': 'accountName', 'type': 'str'}, 'azure_file_url': {'key': 'azureFileUrl', 'type': 'str'}, 'credentials': {'key': 'credentials', 'type': 'AzureStorageCredentialsInfo'}, 'relative_mount_path': {'key': 'relativeMountPath', 'type': 'str'}, 'file_mode': {'key': 'fileMode', 'type': 'str'}, 'directory_mode': {'key': 'directoryMode', 'type': 'str'}, } def __init__( self, *, account_name: str, azure_file_url: str, credentials: "AzureStorageCredentialsInfo", relative_mount_path: str, file_mode: Optional[str] = "0777", directory_mode: Optional[str] = "0777", **kwargs ): super(AzureFileShareReference, self).__init__(**kwargs) self.account_name = account_name self.azure_file_url = azure_file_url self.credentials = credentials self.relative_mount_path = relative_mount_path self.file_mode = file_mode self.directory_mode = directory_mode class AzureStorageCredentialsInfo(msrest.serialization.Model): """Azure storage account credentials. :param account_key: Storage account key. One of accountKey or accountKeySecretReference must be specified. :type account_key: str :param account_key_secret_reference: Information about KeyVault secret storing the storage account key. One of accountKey or accountKeySecretReference must be specified. :type account_key_secret_reference: ~batch_ai.models.KeyVaultSecretReference """ _attribute_map = { 'account_key': {'key': 'accountKey', 'type': 'str'}, 'account_key_secret_reference': {'key': 'accountKeySecretReference', 'type': 'KeyVaultSecretReference'}, } def __init__( self, *, account_key: Optional[str] = None, account_key_secret_reference: Optional["KeyVaultSecretReference"] = None, **kwargs ): super(AzureStorageCredentialsInfo, self).__init__(**kwargs) self.account_key = account_key self.account_key_secret_reference = account_key_secret_reference class BatchAIError(msrest.serialization.Model): """An error response from the Batch AI service. Variables are only populated by the server, and will be ignored when sending a request. :ivar code: An identifier of the error. Codes are invariant and are intended to be consumed programmatically. :vartype code: str :ivar message: A message describing the error, intended to be suitable for display in a user interface. :vartype message: str :ivar details: A list of additional details about the error. :vartype details: list[~batch_ai.models.NameValuePair] """ _validation = { 'code': {'readonly': True}, 'message': {'readonly': True}, 'details': {'readonly': True}, } _attribute_map = { 'code': {'key': 'code', 'type': 'str'}, 'message': {'key': 'message', 'type': 'str'}, 'details': {'key': 'details', 'type': '[NameValuePair]'}, } def __init__( self, **kwargs ): super(BatchAIError, self).__init__(**kwargs) self.code = None self.message = None self.details = None class Caffe2Settings(msrest.serialization.Model): """Caffe2 job settings. All required parameters must be populated in order to send to Azure. :param python_script_file_path: Required. The python script to execute. :type python_script_file_path: str :param python_interpreter_path: The path to the Python interpreter. :type python_interpreter_path: str :param command_line_args: Command line arguments that need to be passed to the python script. :type command_line_args: str """ _validation = { 'python_script_file_path': {'required': True}, } _attribute_map = { 'python_script_file_path': {'key': 'pythonScriptFilePath', 'type': 'str'}, 'python_interpreter_path': {'key': 'pythonInterpreterPath', 'type': 'str'}, 'command_line_args': {'key': 'commandLineArgs', 'type': 'str'}, } def __init__( self, *, python_script_file_path: str, python_interpreter_path: Optional[str] = None, command_line_args: Optional[str] = None, **kwargs ): super(Caffe2Settings, self).__init__(**kwargs) self.python_script_file_path = python_script_file_path self.python_interpreter_path = python_interpreter_path self.command_line_args = command_line_args class CaffeSettings(msrest.serialization.Model): """Caffe job settings. :param config_file_path: Path of the config file for the job. This property cannot be specified if pythonScriptFilePath is specified. :type config_file_path: str :param python_script_file_path: Python script to execute. This property cannot be specified if configFilePath is specified. :type python_script_file_path: str :param python_interpreter_path: The path to the Python interpreter. The property can be specified only if the pythonScriptFilePath is specified. :type python_interpreter_path: str :param command_line_args: Command line arguments that need to be passed to the Caffe job. :type command_line_args: str :param process_count: Number of processes to launch for the job execution. The default value for this property is equal to nodeCount property. :type process_count: int """ _attribute_map = { 'config_file_path': {'key': 'configFilePath', 'type': 'str'}, 'python_script_file_path': {'key': 'pythonScriptFilePath', 'type': 'str'}, 'python_interpreter_path': {'key': 'pythonInterpreterPath', 'type': 'str'}, 'command_line_args': {'key': 'commandLineArgs', 'type': 'str'}, 'process_count': {'key': 'processCount', 'type': 'int'}, } def __init__( self, *, config_file_path: Optional[str] = None, python_script_file_path: Optional[str] = None, python_interpreter_path: Optional[str] = None, command_line_args: Optional[str] = None, process_count: Optional[int] = None, **kwargs ): super(CaffeSettings, self).__init__(**kwargs) self.config_file_path = config_file_path self.python_script_file_path = python_script_file_path self.python_interpreter_path = python_interpreter_path self.command_line_args = command_line_args self.process_count = process_count class ChainerSettings(msrest.serialization.Model): """Chainer job settings. All required parameters must be populated in order to send to Azure. :param python_script_file_path: Required. The python script to execute. :type python_script_file_path: str :param python_interpreter_path: The path to the Python interpreter. :type python_interpreter_path: str :param command_line_args: Command line arguments that need to be passed to the python script. :type command_line_args: str :param process_count: Number of processes to launch for the job execution. The default value for this property is equal to nodeCount property. :type process_count: int """ _validation = { 'python_script_file_path': {'required': True}, } _attribute_map = { 'python_script_file_path': {'key': 'pythonScriptFilePath', 'type': 'str'}, 'python_interpreter_path': {'key': 'pythonInterpreterPath', 'type': 'str'}, 'command_line_args': {'key': 'commandLineArgs', 'type': 'str'}, 'process_count': {'key': 'processCount', 'type': 'int'}, } def __init__( self, *, python_script_file_path: str, python_interpreter_path: Optional[str] = None, command_line_args: Optional[str] = None, process_count: Optional[int] = None, **kwargs ): super(ChainerSettings, self).__init__(**kwargs) self.python_script_file_path = python_script_file_path self.python_interpreter_path = python_interpreter_path self.command_line_args = command_line_args self.process_count = process_count class CloudErrorBody(msrest.serialization.Model): """An error response from the Batch AI service. Variables are only populated by the server, and will be ignored when sending a request. :ivar code: An identifier for the error. Codes are invariant and are intended to be consumed programmatically. :vartype code: str :ivar message: A message describing the error, intended to be suitable for display in a user interface. :vartype message: str :ivar target: The target of the particular error. For example, the name of the property in error. :vartype target: str :ivar details: A list of additional details about the error. :vartype details: list[~batch_ai.models.CloudErrorBody] """ _validation = { 'code': {'readonly': True}, 'message': {'readonly': True}, 'target': {'readonly': True}, 'details': {'readonly': True}, } _attribute_map = { 'code': {'key': 'code', 'type': 'str'}, 'message': {'key': 'message', 'type': 'str'}, 'target': {'key': 'target', 'type': 'str'}, 'details': {'key': 'details', 'type': '[CloudErrorBody]'}, } def __init__( self, **kwargs ): super(CloudErrorBody, self).__init__(**kwargs) self.code = None self.message = None self.target = None self.details = None class ProxyResource(msrest.serialization.Model): """A definition of an Azure proxy resource. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: The ID of the resource. :vartype id: str :ivar name: The name of the resource. :vartype name: str :ivar type: The type of the resource. :vartype type: str """ _validation = { 'id': {'readonly': True}, 'name': {'readonly': True}, 'type': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, } def __init__( self, **kwargs ): super(ProxyResource, self).__init__(**kwargs) self.id = None self.name = None self.type = None class Cluster(ProxyResource): """Information about a Cluster. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: The ID of the resource. :vartype id: str :ivar name: The name of the resource. :vartype name: str :ivar type: The type of the resource. :vartype type: str :param vm_size: The size of the virtual machines in the cluster. All nodes in a cluster have the same VM size. :type vm_size: str :param vm_priority: VM priority of cluster nodes. Possible values include: "dedicated", "lowpriority". :type vm_priority: str or ~batch_ai.models.VmPriority :param scale_settings: Scale settings of the cluster. :type scale_settings: ~batch_ai.models.ScaleSettings :param virtual_machine_configuration: Virtual machine configuration (OS image) of the compute nodes. All nodes in a cluster have the same OS image configuration. :type virtual_machine_configuration: ~batch_ai.models.VirtualMachineConfiguration :param node_setup: Setup (mount file systems, performance counters settings and custom setup task) to be performed on each compute node in the cluster. :type node_setup: ~batch_ai.models.NodeSetup :param user_account_settings: Administrator user account settings which can be used to SSH to compute nodes. :type user_account_settings: ~batch_ai.models.UserAccountSettings :param subnet: Virtual network subnet resource ID the cluster nodes belong to. :type subnet: ~batch_ai.models.ResourceId :ivar creation_time: The time when the cluster was created. :vartype creation_time: ~datetime.datetime :ivar provisioning_state: Provisioning state of the cluster. Possible value are: creating - Specifies that the cluster is being created. succeeded - Specifies that the cluster has been created successfully. failed - Specifies that the cluster creation has failed. deleting - Specifies that the cluster is being deleted. Possible values include: "creating", "succeeded", "failed", "deleting". :vartype provisioning_state: str or ~batch_ai.models.ProvisioningState :ivar provisioning_state_transition_time: Time when the provisioning state was changed. :vartype provisioning_state_transition_time: ~datetime.datetime :ivar allocation_state: Allocation state of the cluster. Possible values are: steady - Indicates that the cluster is not resizing. There are no changes to the number of compute nodes in the cluster in progress. A cluster enters this state when it is created and when no operations are being performed on the cluster to change the number of compute nodes. resizing - Indicates that the cluster is resizing; that is, compute nodes are being added to or removed from the cluster. Possible values include: "steady", "resizing". :vartype allocation_state: str or ~batch_ai.models.AllocationState :ivar allocation_state_transition_time: The time at which the cluster entered its current allocation state. :vartype allocation_state_transition_time: ~datetime.datetime :ivar errors: Collection of errors encountered by various compute nodes during node setup. :vartype errors: list[~batch_ai.models.BatchAIError] :ivar current_node_count: The number of compute nodes currently assigned to the cluster. :vartype current_node_count: int :ivar node_state_counts: Counts of various node states on the cluster. :vartype node_state_counts: ~batch_ai.models.NodeStateCounts """ _validation = { 'id': {'readonly': True}, 'name': {'readonly': True}, 'type': {'readonly': True}, 'creation_time': {'readonly': True}, 'provisioning_state': {'readonly': True}, 'provisioning_state_transition_time': {'readonly': True}, 'allocation_state': {'readonly': True}, 'allocation_state_transition_time': {'readonly': True}, 'errors': {'readonly': True}, 'current_node_count': {'readonly': True}, 'node_state_counts': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'vm_size': {'key': 'properties.vmSize', 'type': 'str'}, 'vm_priority': {'key': 'properties.vmPriority', 'type': 'str'}, 'scale_settings': {'key': 'properties.scaleSettings', 'type': 'ScaleSettings'}, 'virtual_machine_configuration': {'key': 'properties.virtualMachineConfiguration', 'type': 'VirtualMachineConfiguration'}, 'node_setup': {'key': 'properties.nodeSetup', 'type': 'NodeSetup'}, 'user_account_settings': {'key': 'properties.userAccountSettings', 'type': 'UserAccountSettings'}, 'subnet': {'key': 'properties.subnet', 'type': 'ResourceId'}, 'creation_time': {'key': 'properties.creationTime', 'type': 'iso-8601'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'provisioning_state_transition_time': {'key': 'properties.provisioningStateTransitionTime', 'type': 'iso-8601'}, 'allocation_state': {'key': 'properties.allocationState', 'type': 'str'}, 'allocation_state_transition_time': {'key': 'properties.allocationStateTransitionTime', 'type': 'iso-8601'}, 'errors': {'key': 'properties.errors', 'type': '[BatchAIError]'}, 'current_node_count': {'key': 'properties.currentNodeCount', 'type': 'int'}, 'node_state_counts': {'key': 'properties.nodeStateCounts', 'type': 'NodeStateCounts'}, } def __init__( self, *, vm_size: Optional[str] = None, vm_priority: Optional[Union[str, "VmPriority"]] = None, scale_settings: Optional["ScaleSettings"] = None, virtual_machine_configuration: Optional["VirtualMachineConfiguration"] = None, node_setup: Optional["NodeSetup"] = None, user_account_settings: Optional["UserAccountSettings"] = None, subnet: Optional["ResourceId"] = None, **kwargs ): super(Cluster, self).__init__(**kwargs) self.vm_size = vm_size self.vm_priority = vm_priority self.scale_settings = scale_settings self.virtual_machine_configuration = virtual_machine_configuration self.node_setup = node_setup self.user_account_settings = user_account_settings self.subnet = subnet self.creation_time = None self.provisioning_state = None self.provisioning_state_transition_time = None self.allocation_state = None self.allocation_state_transition_time = None self.errors = None self.current_node_count = None self.node_state_counts = None class ClusterCreateParameters(msrest.serialization.Model): """Cluster creation operation. :param vm_size: The size of the virtual machines in the cluster. All nodes in a cluster have the same VM size. For information about available VM sizes for clusters using images from the Virtual Machines Marketplace see Sizes for Virtual Machines (Linux). Batch AI service supports all Azure VM sizes except STANDARD_A0 and those with premium storage (STANDARD_GS, STANDARD_DS, and STANDARD_DSV2 series). :type vm_size: str :param vm_priority: VM priority. Allowed values are: dedicated (default) and lowpriority. Possible values include: "dedicated", "lowpriority". :type vm_priority: str or ~batch_ai.models.VmPriority :param scale_settings: Scale settings for the cluster. Batch AI service supports manual and auto scale clusters. :type scale_settings: ~batch_ai.models.ScaleSettings :param virtual_machine_configuration: OS image configuration for cluster nodes. All nodes in a cluster have the same OS image. :type virtual_machine_configuration: ~batch_ai.models.VirtualMachineConfiguration :param node_setup: Setup to be performed on each compute node in the cluster. :type node_setup: ~batch_ai.models.NodeSetup :param user_account_settings: Settings for an administrator user account that will be created on each compute node in the cluster. :type user_account_settings: ~batch_ai.models.UserAccountSettings :param subnet: Existing virtual network subnet to put the cluster nodes in. Note, if a File Server mount configured in node setup, the File Server's subnet will be used automatically. :type subnet: ~batch_ai.models.ResourceId """ _attribute_map = { 'vm_size': {'key': 'properties.vmSize', 'type': 'str'}, 'vm_priority': {'key': 'properties.vmPriority', 'type': 'str'}, 'scale_settings': {'key': 'properties.scaleSettings', 'type': 'ScaleSettings'}, 'virtual_machine_configuration': {'key': 'properties.virtualMachineConfiguration', 'type': 'VirtualMachineConfiguration'}, 'node_setup': {'key': 'properties.nodeSetup', 'type': 'NodeSetup'}, 'user_account_settings': {'key': 'properties.userAccountSettings', 'type': 'UserAccountSettings'}, 'subnet': {'key': 'properties.subnet', 'type': 'ResourceId'}, } def __init__( self, *, vm_size: Optional[str] = None, vm_priority: Optional[Union[str, "VmPriority"]] = None, scale_settings: Optional["ScaleSettings"] = None, virtual_machine_configuration: Optional["VirtualMachineConfiguration"] = None, node_setup: Optional["NodeSetup"] = None, user_account_settings: Optional["UserAccountSettings"] = None, subnet: Optional["ResourceId"] = None, **kwargs ): super(ClusterCreateParameters, self).__init__(**kwargs) self.vm_size = vm_size self.vm_priority = vm_priority self.scale_settings = scale_settings self.virtual_machine_configuration = virtual_machine_configuration self.node_setup = node_setup self.user_account_settings = user_account_settings self.subnet = subnet class ClusterListResult(msrest.serialization.Model): """Values returned by the List Clusters operation. Variables are only populated by the server, and will be ignored when sending a request. :ivar value: The collection of returned Clusters. :vartype value: list[~batch_ai.models.Cluster] :ivar next_link: The continuation token. :vartype next_link: str """ _validation = { 'value': {'readonly': True}, 'next_link': {'readonly': True}, } _attribute_map = { 'value': {'key': 'value', 'type': '[Cluster]'}, 'next_link': {'key': 'nextLink', 'type': 'str'}, } def __init__( self, **kwargs ): super(ClusterListResult, self).__init__(**kwargs) self.value = None self.next_link = None class ClustersListByWorkspaceOptions(msrest.serialization.Model): """Parameter group. :param max_results: The maximum number of items to return in the response. A maximum of 1000 files can be returned. :type max_results: int """ _validation = { 'max_results': {'maximum': 1000, 'minimum': 1}, } _attribute_map = { 'max_results': {'key': 'maxResults', 'type': 'int'}, } def __init__( self, *, max_results: Optional[int] = 1000, **kwargs ): super(ClustersListByWorkspaceOptions, self).__init__(**kwargs) self.max_results = max_results class ClusterUpdateParameters(msrest.serialization.Model): """Cluster update parameters. :param scale_settings: Desired scale settings for the cluster. Batch AI service supports manual and auto scale clusters. :type scale_settings: ~batch_ai.models.ScaleSettings """ _attribute_map = { 'scale_settings': {'key': 'properties.scaleSettings', 'type': 'ScaleSettings'}, } def __init__( self, *, scale_settings: Optional["ScaleSettings"] = None, **kwargs ): super(ClusterUpdateParameters, self).__init__(**kwargs) self.scale_settings = scale_settings class CNTKsettings(msrest.serialization.Model): """CNTK (aka Microsoft Cognitive Toolkit) job settings. :param language_type: The language to use for launching CNTK (aka Microsoft Cognitive Toolkit) job. Valid values are 'BrainScript' or 'Python'. :type language_type: str :param config_file_path: Specifies the path of the BrainScript config file. This property can be specified only if the languageType is 'BrainScript'. :type config_file_path: str :param python_script_file_path: Python script to execute. This property can be specified only if the languageType is 'Python'. :type python_script_file_path: str :param python_interpreter_path: The path to the Python interpreter. This property can be specified only if the languageType is 'Python'. :type python_interpreter_path: str :param command_line_args: Command line arguments that need to be passed to the python script or cntk executable. :type command_line_args: str :param process_count: Number of processes to launch for the job execution. The default value for this property is equal to nodeCount property. :type process_count: int """ _attribute_map = { 'language_type': {'key': 'languageType', 'type': 'str'}, 'config_file_path': {'key': 'configFilePath', 'type': 'str'}, 'python_script_file_path': {'key': 'pythonScriptFilePath', 'type': 'str'}, 'python_interpreter_path': {'key': 'pythonInterpreterPath', 'type': 'str'}, 'command_line_args': {'key': 'commandLineArgs', 'type': 'str'}, 'process_count': {'key': 'processCount', 'type': 'int'}, } def __init__( self, *, language_type: Optional[str] = None, config_file_path: Optional[str] = None, python_script_file_path: Optional[str] = None, python_interpreter_path: Optional[str] = None, command_line_args: Optional[str] = None, process_count: Optional[int] = None, **kwargs ): super(CNTKsettings, self).__init__(**kwargs) self.language_type = language_type self.config_file_path = config_file_path self.python_script_file_path = python_script_file_path self.python_interpreter_path = python_interpreter_path self.command_line_args = command_line_args self.process_count = process_count class ContainerSettings(msrest.serialization.Model): """Docker container settings. All required parameters must be populated in order to send to Azure. :param image_source_registry: Required. Information about docker image and docker registry to download the container from. :type image_source_registry: ~batch_ai.models.ImageSourceRegistry :param shm_size: Size of /dev/shm. Please refer to docker documentation for supported argument formats. :type shm_size: str """ _validation = { 'image_source_registry': {'required': True}, } _attribute_map = { 'image_source_registry': {'key': 'imageSourceRegistry', 'type': 'ImageSourceRegistry'}, 'shm_size': {'key': 'shmSize', 'type': 'str'}, } def __init__( self, *, image_source_registry: "ImageSourceRegistry", shm_size: Optional[str] = None, **kwargs ): super(ContainerSettings, self).__init__(**kwargs) self.image_source_registry = image_source_registry self.shm_size = shm_size class CustomMpiSettings(msrest.serialization.Model): """Custom MPI job settings. All required parameters must be populated in order to send to Azure. :param command_line: Required. The command line to be executed by mpi runtime on each compute node. :type command_line: str :param process_count: Number of processes to launch for the job execution. The default value for this property is equal to nodeCount property. :type process_count: int """ _validation = { 'command_line': {'required': True}, } _attribute_map = { 'command_line': {'key': 'commandLine', 'type': 'str'}, 'process_count': {'key': 'processCount', 'type': 'int'}, } def __init__( self, *, command_line: str, process_count: Optional[int] = None, **kwargs ): super(CustomMpiSettings, self).__init__(**kwargs) self.command_line = command_line self.process_count = process_count class CustomToolkitSettings(msrest.serialization.Model): """Custom tool kit job settings. :param command_line: The command line to execute on the master node. :type command_line: str """ _attribute_map = { 'command_line': {'key': 'commandLine', 'type': 'str'}, } def __init__( self, *, command_line: Optional[str] = None, **kwargs ): super(CustomToolkitSettings, self).__init__(**kwargs) self.command_line = command_line class DataDisks(msrest.serialization.Model): """Data disks settings. All required parameters must be populated in order to send to Azure. :param disk_size_in_gb: Required. Disk size in GB for the blank data disks. :type disk_size_in_gb: int :param caching_type: Caching type for the disks. Available values are none (default), readonly, readwrite. Caching type can be set only for VM sizes supporting premium storage. Possible values include: "none", "readonly", "readwrite". Default value: "none". :type caching_type: str or ~batch_ai.models.CachingType :param disk_count: Required. Number of data disks attached to the File Server. If multiple disks attached, they will be configured in RAID level 0. :type disk_count: int :param storage_account_type: Required. Type of storage account to be used on the disk. Possible values are: Standard_LRS or Premium_LRS. Premium storage account type can only be used with VM sizes supporting premium storage. Possible values include: "Standard_LRS", "Premium_LRS". :type storage_account_type: str or ~batch_ai.models.StorageAccountType """ _validation = { 'disk_size_in_gb': {'required': True}, 'disk_count': {'required': True}, 'storage_account_type': {'required': True}, } _attribute_map = { 'disk_size_in_gb': {'key': 'diskSizeInGB', 'type': 'int'}, 'caching_type': {'key': 'cachingType', 'type': 'str'}, 'disk_count': {'key': 'diskCount', 'type': 'int'}, 'storage_account_type': {'key': 'storageAccountType', 'type': 'str'}, } def __init__( self, *, disk_size_in_gb: int, disk_count: int, storage_account_type: Union[str, "StorageAccountType"], caching_type: Optional[Union[str, "CachingType"]] = "none", **kwargs ): super(DataDisks, self).__init__(**kwargs) self.disk_size_in_gb = disk_size_in_gb self.caching_type = caching_type self.disk_count = disk_count self.storage_account_type = storage_account_type class EnvironmentVariable(msrest.serialization.Model): """An environment variable definition. All required parameters must be populated in order to send to Azure. :param name: Required. The name of the environment variable. :type name: str :param value: Required. The value of the environment variable. :type value: str """ _validation = { 'name': {'required': True}, 'value': {'required': True}, } _attribute_map = { 'name': {'key': 'name', 'type': 'str'}, 'value': {'key': 'value', 'type': 'str'}, } def __init__( self, *, name: str, value: str, **kwargs ): super(EnvironmentVariable, self).__init__(**kwargs) self.name = name self.value = value class EnvironmentVariableWithSecretValue(msrest.serialization.Model): """An environment variable with secret value definition. All required parameters must be populated in order to send to Azure. :param name: Required. The name of the environment variable to store the secret value. :type name: str :param value: The value of the environment variable. This value will never be reported back by Batch AI. :type value: str :param value_secret_reference: KeyVault store and secret which contains the value for the environment variable. One of value or valueSecretReference must be provided. :type value_secret_reference: ~batch_ai.models.KeyVaultSecretReference """ _validation = { 'name': {'required': True}, } _attribute_map = { 'name': {'key': 'name', 'type': 'str'}, 'value': {'key': 'value', 'type': 'str'}, 'value_secret_reference': {'key': 'valueSecretReference', 'type': 'KeyVaultSecretReference'}, } def __init__( self, *, name: str, value: Optional[str] = None, value_secret_reference: Optional["KeyVaultSecretReference"] = None, **kwargs ): super(EnvironmentVariableWithSecretValue, self).__init__(**kwargs) self.name = name self.value = value self.value_secret_reference = value_secret_reference class Experiment(ProxyResource): """Experiment information. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: The ID of the resource. :vartype id: str :ivar name: The name of the resource. :vartype name: str :ivar type: The type of the resource. :vartype type: str :ivar creation_time: Time when the Experiment was created. :vartype creation_time: ~datetime.datetime :ivar provisioning_state: The provisioned state of the experiment. Possible values include: "creating", "succeeded", "failed", "deleting". :vartype provisioning_state: str or ~batch_ai.models.ProvisioningState :ivar provisioning_state_transition_time: The time at which the experiment entered its current provisioning state. :vartype provisioning_state_transition_time: ~datetime.datetime """ _validation = { 'id': {'readonly': True}, 'name': {'readonly': True}, 'type': {'readonly': True}, 'creation_time': {'readonly': True}, 'provisioning_state': {'readonly': True}, 'provisioning_state_transition_time': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'creation_time': {'key': 'properties.creationTime', 'type': 'iso-8601'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'provisioning_state_transition_time': {'key': 'properties.provisioningStateTransitionTime', 'type': 'iso-8601'}, } def __init__( self, **kwargs ): super(Experiment, self).__init__(**kwargs) self.creation_time = None self.provisioning_state = None self.provisioning_state_transition_time = None class ExperimentListResult(msrest.serialization.Model): """Values returned by the List operation. Variables are only populated by the server, and will be ignored when sending a request. :ivar value: The collection of experiments. :vartype value: list[~batch_ai.models.Experiment] :ivar next_link: The continuation token. :vartype next_link: str """ _validation = { 'value': {'readonly': True}, 'next_link': {'readonly': True}, } _attribute_map = { 'value': {'key': 'value', 'type': '[Experiment]'}, 'next_link': {'key': 'nextLink', 'type': 'str'}, } def __init__( self, **kwargs ): super(ExperimentListResult, self).__init__(**kwargs) self.value = None self.next_link = None class ExperimentsListByWorkspaceOptions(msrest.serialization.Model): """Parameter group. :param max_results: The maximum number of items to return in the response. A maximum of 1000 files can be returned. :type max_results: int """ _validation = { 'max_results': {'maximum': 1000, 'minimum': 1}, } _attribute_map = { 'max_results': {'key': 'maxResults', 'type': 'int'}, } def __init__( self, *, max_results: Optional[int] = 1000, **kwargs ): super(ExperimentsListByWorkspaceOptions, self).__init__(**kwargs) self.max_results = max_results class File(msrest.serialization.Model): """Properties of the file or directory. Variables are only populated by the server, and will be ignored when sending a request. :ivar name: Name of the file. :vartype name: str :ivar file_type: Type of the file. Possible values are file and directory. Possible values include: "file", "directory". :vartype file_type: str or ~batch_ai.models.FileType :ivar download_url: URL to download the corresponding file. The downloadUrl is not returned for directories. :vartype download_url: str :ivar last_modified: The time at which the file was last modified. :vartype last_modified: ~datetime.datetime :ivar content_length: The file of the size. :vartype content_length: long """ _validation = { 'name': {'readonly': True}, 'file_type': {'readonly': True}, 'download_url': {'readonly': True}, 'last_modified': {'readonly': True}, 'content_length': {'readonly': True}, } _attribute_map = { 'name': {'key': 'name', 'type': 'str'}, 'file_type': {'key': 'fileType', 'type': 'str'}, 'download_url': {'key': 'downloadUrl', 'type': 'str'}, 'last_modified': {'key': 'properties.lastModified', 'type': 'iso-8601'}, 'content_length': {'key': 'properties.contentLength', 'type': 'long'}, } def __init__( self, **kwargs ): super(File, self).__init__(**kwargs) self.name = None self.file_type = None self.download_url = None self.last_modified = None self.content_length = None class FileListResult(msrest.serialization.Model): """Values returned by the List operation. Variables are only populated by the server, and will be ignored when sending a request. :ivar value: The collection of returned job directories and files. :vartype value: list[~batch_ai.models.File] :ivar next_link: The continuation token. :vartype next_link: str """ _validation = { 'value': {'readonly': True}, 'next_link': {'readonly': True}, } _attribute_map = { 'value': {'key': 'value', 'type': '[File]'}, 'next_link': {'key': 'nextLink', 'type': 'str'}, } def __init__( self, **kwargs ): super(FileListResult, self).__init__(**kwargs) self.value = None self.next_link = None class FileServer(ProxyResource): """File Server information. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: The ID of the resource. :vartype id: str :ivar name: The name of the resource. :vartype name: str :ivar type: The type of the resource. :vartype type: str :param vm_size: VM size of the File Server. :type vm_size: str :param ssh_configuration: SSH configuration for accessing the File Server node. :type ssh_configuration: ~batch_ai.models.SshConfiguration :param data_disks: Information about disks attached to File Server VM. :type data_disks: ~batch_ai.models.DataDisks :param subnet: File Server virtual network subnet resource ID. :type subnet: ~batch_ai.models.ResourceId :ivar mount_settings: File Server mount settings. :vartype mount_settings: ~batch_ai.models.MountSettings :ivar provisioning_state_transition_time: Time when the provisioning state was changed. :vartype provisioning_state_transition_time: ~datetime.datetime :ivar creation_time: Time when the FileServer was created. :vartype creation_time: ~datetime.datetime :ivar provisioning_state: Provisioning state of the File Server. Possible values: creating - The File Server is getting created; updating - The File Server creation has been accepted and it is getting updated; deleting - The user has requested that the File Server be deleted, and it is in the process of being deleted; failed - The File Server creation has failed with the specified error code. Details about the error code are specified in the message field; succeeded - The File Server creation has succeeded. Possible values include: "creating", "updating", "deleting", "succeeded", "failed". :vartype provisioning_state: str or ~batch_ai.models.FileServerProvisioningState """ _validation = { 'id': {'readonly': True}, 'name': {'readonly': True}, 'type': {'readonly': True}, 'mount_settings': {'readonly': True}, 'provisioning_state_transition_time': {'readonly': True}, 'creation_time': {'readonly': True}, 'provisioning_state': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'vm_size': {'key': 'properties.vmSize', 'type': 'str'}, 'ssh_configuration': {'key': 'properties.sshConfiguration', 'type': 'SshConfiguration'}, 'data_disks': {'key': 'properties.dataDisks', 'type': 'DataDisks'}, 'subnet': {'key': 'properties.subnet', 'type': 'ResourceId'}, 'mount_settings': {'key': 'properties.mountSettings', 'type': 'MountSettings'}, 'provisioning_state_transition_time': {'key': 'properties.provisioningStateTransitionTime', 'type': 'iso-8601'}, 'creation_time': {'key': 'properties.creationTime', 'type': 'iso-8601'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, } def __init__( self, *, vm_size: Optional[str] = None, ssh_configuration: Optional["SshConfiguration"] = None, data_disks: Optional["DataDisks"] = None, subnet: Optional["ResourceId"] = None, **kwargs ): super(FileServer, self).__init__(**kwargs) self.vm_size = vm_size self.ssh_configuration = ssh_configuration self.data_disks = data_disks self.subnet = subnet self.mount_settings = None self.provisioning_state_transition_time = None self.creation_time = None self.provisioning_state = None class FileServerCreateParameters(msrest.serialization.Model): """File Server creation parameters. :param vm_size: The size of the virtual machine for the File Server. For information about available VM sizes from the Virtual Machines Marketplace, see Sizes for Virtual Machines (Linux). :type vm_size: str :param ssh_configuration: SSH configuration for the File Server node. :type ssh_configuration: ~batch_ai.models.SshConfiguration :param data_disks: Settings for the data disks which will be created for the File Server. :type data_disks: ~batch_ai.models.DataDisks :param subnet: Identifier of an existing virtual network subnet to put the File Server in. If not provided, a new virtual network and subnet will be created. :type subnet: ~batch_ai.models.ResourceId """ _attribute_map = { 'vm_size': {'key': 'properties.vmSize', 'type': 'str'}, 'ssh_configuration': {'key': 'properties.sshConfiguration', 'type': 'SshConfiguration'}, 'data_disks': {'key': 'properties.dataDisks', 'type': 'DataDisks'}, 'subnet': {'key': 'properties.subnet', 'type': 'ResourceId'}, } def __init__( self, *, vm_size: Optional[str] = None, ssh_configuration: Optional["SshConfiguration"] = None, data_disks: Optional["DataDisks"] = None, subnet: Optional["ResourceId"] = None, **kwargs ): super(FileServerCreateParameters, self).__init__(**kwargs) self.vm_size = vm_size self.ssh_configuration = ssh_configuration self.data_disks = data_disks self.subnet = subnet class FileServerListResult(msrest.serialization.Model): """Values returned by the File Server List operation. Variables are only populated by the server, and will be ignored when sending a request. :param value: The collection of File Servers. :type value: list[~batch_ai.models.FileServer] :ivar next_link: The continuation token. :vartype next_link: str """ _validation = { 'next_link': {'readonly': True}, } _attribute_map = { 'value': {'key': 'value', 'type': '[FileServer]'}, 'next_link': {'key': 'nextLink', 'type': 'str'}, } def __init__( self, *, value: Optional[List["FileServer"]] = None, **kwargs ): super(FileServerListResult, self).__init__(**kwargs) self.value = value self.next_link = None class FileServerReference(msrest.serialization.Model): """File Server mounting configuration. All required parameters must be populated in order to send to Azure. :param file_server: Required. Resource ID of the existing File Server to be mounted. :type file_server: ~batch_ai.models.ResourceId :param source_directory: File Server directory that needs to be mounted. If this property is not specified, the entire File Server will be mounted. :type source_directory: str :param relative_mount_path: Required. The relative path on the compute node where the File Server will be mounted. Note that all cluster level file servers will be mounted under $AZ_BATCHAI_MOUNT_ROOT location and all job level file servers will be mounted under $AZ_BATCHAI_JOB_MOUNT_ROOT. :type relative_mount_path: str :param mount_options: Mount options to be passed to mount command. :type mount_options: str """ _validation = { 'file_server': {'required': True}, 'relative_mount_path': {'required': True}, } _attribute_map = { 'file_server': {'key': 'fileServer', 'type': 'ResourceId'}, 'source_directory': {'key': 'sourceDirectory', 'type': 'str'}, 'relative_mount_path': {'key': 'relativeMountPath', 'type': 'str'}, 'mount_options': {'key': 'mountOptions', 'type': 'str'}, } def __init__( self, *, file_server: "ResourceId", relative_mount_path: str, source_directory: Optional[str] = None, mount_options: Optional[str] = None, **kwargs ): super(FileServerReference, self).__init__(**kwargs) self.file_server = file_server self.source_directory = source_directory self.relative_mount_path = relative_mount_path self.mount_options = mount_options class FileServersListByWorkspaceOptions(msrest.serialization.Model): """Parameter group. :param max_results: The maximum number of items to return in the response. A maximum of 1000 files can be returned. :type max_results: int """ _validation = { 'max_results': {'maximum': 1000, 'minimum': 1}, } _attribute_map = { 'max_results': {'key': 'maxResults', 'type': 'int'}, } def __init__( self, *, max_results: Optional[int] = 1000, **kwargs ): super(FileServersListByWorkspaceOptions, self).__init__(**kwargs) self.max_results = max_results class HorovodSettings(msrest.serialization.Model): """Specifies the settings for Horovod job. All required parameters must be populated in order to send to Azure. :param python_script_file_path: Required. The python script to execute. :type python_script_file_path: str :param python_interpreter_path: The path to the Python interpreter. :type python_interpreter_path: str :param command_line_args: Command line arguments that need to be passed to the python script. :type command_line_args: str :param process_count: Number of processes to launch for the job execution. The default value for this property is equal to nodeCount property. :type process_count: int """ _validation = { 'python_script_file_path': {'required': True}, } _attribute_map = { 'python_script_file_path': {'key': 'pythonScriptFilePath', 'type': 'str'}, 'python_interpreter_path': {'key': 'pythonInterpreterPath', 'type': 'str'}, 'command_line_args': {'key': 'commandLineArgs', 'type': 'str'}, 'process_count': {'key': 'processCount', 'type': 'int'}, } def __init__( self, *, python_script_file_path: str, python_interpreter_path: Optional[str] = None, command_line_args: Optional[str] = None, process_count: Optional[int] = None, **kwargs ): super(HorovodSettings, self).__init__(**kwargs) self.python_script_file_path = python_script_file_path self.python_interpreter_path = python_interpreter_path self.command_line_args = command_line_args self.process_count = process_count class ImageReference(msrest.serialization.Model): """The OS image reference. All required parameters must be populated in order to send to Azure. :param publisher: Required. Publisher of the image. :type publisher: str :param offer: Required. Offer of the image. :type offer: str :param sku: Required. SKU of the image. :type sku: str :param version: Version of the image. :type version: str :param virtual_machine_image_id: The ARM resource identifier of the virtual machine image for the compute nodes. This is of the form /subscriptions/{subscriptionId}/resourceGroups/{resourceGroup}/providers/Microsoft.Compute/images/{imageName}. The virtual machine image must be in the same region and subscription as the cluster. For information about the firewall settings for the Batch node agent to communicate with the Batch service see https://docs.microsoft.com/en-us/azure/batch/batch-api-basics#virtual-network-vnet-and-firewall-configuration. Note, you need to provide publisher, offer and sku of the base OS image of which the custom image has been derived from. :type virtual_machine_image_id: str """ _validation = { 'publisher': {'required': True}, 'offer': {'required': True}, 'sku': {'required': True}, } _attribute_map = { 'publisher': {'key': 'publisher', 'type': 'str'}, 'offer': {'key': 'offer', 'type': 'str'}, 'sku': {'key': 'sku', 'type': 'str'}, 'version': {'key': 'version', 'type': 'str'}, 'virtual_machine_image_id': {'key': 'virtualMachineImageId', 'type': 'str'}, } def __init__( self, *, publisher: str, offer: str, sku: str, version: Optional[str] = None, virtual_machine_image_id: Optional[str] = None, **kwargs ): super(ImageReference, self).__init__(**kwargs) self.publisher = publisher self.offer = offer self.sku = sku self.version = version self.virtual_machine_image_id = virtual_machine_image_id class ImageSourceRegistry(msrest.serialization.Model): """Information about docker image for the job. All required parameters must be populated in order to send to Azure. :param server_url: URL for image repository. :type server_url: str :param image: Required. The name of the image in the image repository. :type image: str :param credentials: Credentials to access the private docker repository. :type credentials: ~batch_ai.models.PrivateRegistryCredentials """ _validation = { 'image': {'required': True}, } _attribute_map = { 'server_url': {'key': 'serverUrl', 'type': 'str'}, 'image': {'key': 'image', 'type': 'str'}, 'credentials': {'key': 'credentials', 'type': 'PrivateRegistryCredentials'}, } def __init__( self, *, image: str, server_url: Optional[str] = None, credentials: Optional["PrivateRegistryCredentials"] = None, **kwargs ): super(ImageSourceRegistry, self).__init__(**kwargs) self.server_url = server_url self.image = image self.credentials = credentials class InputDirectory(msrest.serialization.Model): """Input directory for the job. All required parameters must be populated in order to send to Azure. :param id: Required. The ID for the input directory. The job can use AZ_BATCHAI\ *INPUT*\ :code:`<id>` environment variable to find the directory path, where :code:`<id>` is the value of id attribute. :type id: str :param path: Required. The path to the input directory. :type path: str """ _validation = { 'id': {'required': True}, 'path': {'required': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'path': {'key': 'path', 'type': 'str'}, } def __init__( self, *, id: str, path: str, **kwargs ): super(InputDirectory, self).__init__(**kwargs) self.id = id self.path = path class Job(ProxyResource): """Information about a Job. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: The ID of the resource. :vartype id: str :ivar name: The name of the resource. :vartype name: str :ivar type: The type of the resource. :vartype type: str :param scheduling_priority: Scheduling priority associated with the job. Possible values include: "low", "normal", "high". :type scheduling_priority: str or ~batch_ai.models.JobPriority :param cluster: Resource ID of the cluster associated with the job. :type cluster: ~batch_ai.models.ResourceId :param mount_volumes: Collection of mount volumes available to the job during execution. These volumes are mounted before the job execution and unmounted after the job completion. The volumes are mounted at location specified by $AZ_BATCHAI_JOB_MOUNT_ROOT environment variable. :type mount_volumes: ~batch_ai.models.MountVolumes :param node_count: The job will be gang scheduled on that many compute nodes. :type node_count: int :param container_settings: If the container was downloaded as part of cluster setup then the same container image will be used. If not provided, the job will run on the VM. :type container_settings: ~batch_ai.models.ContainerSettings :param tool_type: Possible values are: cntk, tensorflow, caffe, caffe2, chainer, pytorch, custom, custommpi, horovod. Possible values include: "cntk", "tensorflow", "caffe", "caffe2", "chainer", "horovod", "custommpi", "custom". :type tool_type: str or ~batch_ai.models.ToolType :param cntk_settings: CNTK (aka Microsoft Cognitive Toolkit) job settings. :type cntk_settings: ~batch_ai.models.CNTKsettings :param py_torch_settings: pyTorch job settings. :type py_torch_settings: ~batch_ai.models.PyTorchSettings :param tensor_flow_settings: TensorFlow job settings. :type tensor_flow_settings: ~batch_ai.models.TensorFlowSettings :param caffe_settings: Caffe job settings. :type caffe_settings: ~batch_ai.models.CaffeSettings :param caffe2_settings: Caffe2 job settings. :type caffe2_settings: ~batch_ai.models.Caffe2Settings :param chainer_settings: Chainer job settings. :type chainer_settings: ~batch_ai.models.ChainerSettings :param custom_toolkit_settings: Custom tool kit job settings. :type custom_toolkit_settings: ~batch_ai.models.CustomToolkitSettings :param custom_mpi_settings: Custom MPI job settings. :type custom_mpi_settings: ~batch_ai.models.CustomMpiSettings :param horovod_settings: Specifies the settings for Horovod job. :type horovod_settings: ~batch_ai.models.HorovodSettings :param job_preparation: The specified actions will run on all the nodes that are part of the job. :type job_preparation: ~batch_ai.models.JobPreparation :ivar job_output_directory_path_segment: A segment of job's output directories path created by Batch AI. Batch AI creates job's output directories under an unique path to avoid conflicts between jobs. This value contains a path segment generated by Batch AI to make the path unique and can be used to find the output directory on the node or mounted filesystem. :vartype job_output_directory_path_segment: str :param std_out_err_path_prefix: The path where the Batch AI service stores stdout, stderror and execution log of the job. :type std_out_err_path_prefix: str :param input_directories: A list of input directories for the job. :type input_directories: list[~batch_ai.models.InputDirectory] :param output_directories: A list of output directories for the job. :type output_directories: list[~batch_ai.models.OutputDirectory] :param environment_variables: A collection of user defined environment variables to be setup for the job. :type environment_variables: list[~batch_ai.models.EnvironmentVariable] :param secrets: A collection of user defined environment variables with secret values to be setup for the job. Server will never report values of these variables back. :type secrets: list[~batch_ai.models.EnvironmentVariableWithSecretValue] :param constraints: Constraints associated with the Job. :type constraints: ~batch_ai.models.JobPropertiesConstraints :ivar creation_time: The creation time of the job. :vartype creation_time: ~datetime.datetime :ivar provisioning_state: The provisioned state of the Batch AI job. Possible values include: "creating", "succeeded", "failed", "deleting". :vartype provisioning_state: str or ~batch_ai.models.ProvisioningState :ivar provisioning_state_transition_time: The time at which the job entered its current provisioning state. :vartype provisioning_state_transition_time: ~datetime.datetime :ivar execution_state: The current state of the job. Possible values are: queued - The job is queued and able to run. A job enters this state when it is created, or when it is awaiting a retry after a failed run. running - The job is running on a compute cluster. This includes job-level preparation such as downloading resource files or set up container specified on the job - it does not necessarily mean that the job command line has started executing. terminating - The job is terminated by the user, the terminate operation is in progress. succeeded - The job has completed running successfully and exited with exit code 0. failed - The job has finished unsuccessfully (failed with a non-zero exit code) and has exhausted its retry limit. A job is also marked as failed if an error occurred launching the job. Possible values include: "queued", "running", "terminating", "succeeded", "failed". :vartype execution_state: str or ~batch_ai.models.ExecutionState :ivar execution_state_transition_time: The time at which the job entered its current execution state. :vartype execution_state_transition_time: ~datetime.datetime :param execution_info: Information about the execution of a job. :type execution_info: ~batch_ai.models.JobPropertiesExecutionInfo """ _validation = { 'id': {'readonly': True}, 'name': {'readonly': True}, 'type': {'readonly': True}, 'job_output_directory_path_segment': {'readonly': True}, 'creation_time': {'readonly': True}, 'provisioning_state': {'readonly': True}, 'provisioning_state_transition_time': {'readonly': True}, 'execution_state': {'readonly': True}, 'execution_state_transition_time': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'scheduling_priority': {'key': 'properties.schedulingPriority', 'type': 'str'}, 'cluster': {'key': 'properties.cluster', 'type': 'ResourceId'}, 'mount_volumes': {'key': 'properties.mountVolumes', 'type': 'MountVolumes'}, 'node_count': {'key': 'properties.nodeCount', 'type': 'int'}, 'container_settings': {'key': 'properties.containerSettings', 'type': 'ContainerSettings'}, 'tool_type': {'key': 'properties.toolType', 'type': 'str'}, 'cntk_settings': {'key': 'properties.cntkSettings', 'type': 'CNTKsettings'}, 'py_torch_settings': {'key': 'properties.pyTorchSettings', 'type': 'PyTorchSettings'}, 'tensor_flow_settings': {'key': 'properties.tensorFlowSettings', 'type': 'TensorFlowSettings'}, 'caffe_settings': {'key': 'properties.caffeSettings', 'type': 'CaffeSettings'}, 'caffe2_settings': {'key': 'properties.caffe2Settings', 'type': 'Caffe2Settings'}, 'chainer_settings': {'key': 'properties.chainerSettings', 'type': 'ChainerSettings'}, 'custom_toolkit_settings': {'key': 'properties.customToolkitSettings', 'type': 'CustomToolkitSettings'}, 'custom_mpi_settings': {'key': 'properties.customMpiSettings', 'type': 'CustomMpiSettings'}, 'horovod_settings': {'key': 'properties.horovodSettings', 'type': 'HorovodSettings'}, 'job_preparation': {'key': 'properties.jobPreparation', 'type': 'JobPreparation'}, 'job_output_directory_path_segment': {'key': 'properties.jobOutputDirectoryPathSegment', 'type': 'str'}, 'std_out_err_path_prefix': {'key': 'properties.stdOutErrPathPrefix', 'type': 'str'}, 'input_directories': {'key': 'properties.inputDirectories', 'type': '[InputDirectory]'}, 'output_directories': {'key': 'properties.outputDirectories', 'type': '[OutputDirectory]'}, 'environment_variables': {'key': 'properties.environmentVariables', 'type': '[EnvironmentVariable]'}, 'secrets': {'key': 'properties.secrets', 'type': '[EnvironmentVariableWithSecretValue]'}, 'constraints': {'key': 'properties.constraints', 'type': 'JobPropertiesConstraints'}, 'creation_time': {'key': 'properties.creationTime', 'type': 'iso-8601'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'provisioning_state_transition_time': {'key': 'properties.provisioningStateTransitionTime', 'type': 'iso-8601'}, 'execution_state': {'key': 'properties.executionState', 'type': 'str'}, 'execution_state_transition_time': {'key': 'properties.executionStateTransitionTime', 'type': 'iso-8601'}, 'execution_info': {'key': 'properties.executionInfo', 'type': 'JobPropertiesExecutionInfo'}, } def __init__( self, *, scheduling_priority: Optional[Union[str, "JobPriority"]] = None, cluster: Optional["ResourceId"] = None, mount_volumes: Optional["MountVolumes"] = None, node_count: Optional[int] = None, container_settings: Optional["ContainerSettings"] = None, tool_type: Optional[Union[str, "ToolType"]] = None, cntk_settings: Optional["CNTKsettings"] = None, py_torch_settings: Optional["PyTorchSettings"] = None, tensor_flow_settings: Optional["TensorFlowSettings"] = None, caffe_settings: Optional["CaffeSettings"] = None, caffe2_settings: Optional["Caffe2Settings"] = None, chainer_settings: Optional["ChainerSettings"] = None, custom_toolkit_settings: Optional["CustomToolkitSettings"] = None, custom_mpi_settings: Optional["CustomMpiSettings"] = None, horovod_settings: Optional["HorovodSettings"] = None, job_preparation: Optional["JobPreparation"] = None, std_out_err_path_prefix: Optional[str] = None, input_directories: Optional[List["InputDirectory"]] = None, output_directories: Optional[List["OutputDirectory"]] = None, environment_variables: Optional[List["EnvironmentVariable"]] = None, secrets: Optional[List["EnvironmentVariableWithSecretValue"]] = None, constraints: Optional["JobPropertiesConstraints"] = None, execution_info: Optional["JobPropertiesExecutionInfo"] = None, **kwargs ): super(Job, self).__init__(**kwargs) self.scheduling_priority = scheduling_priority self.cluster = cluster self.mount_volumes = mount_volumes self.node_count = node_count self.container_settings = container_settings self.tool_type = tool_type self.cntk_settings = cntk_settings self.py_torch_settings = py_torch_settings self.tensor_flow_settings = tensor_flow_settings self.caffe_settings = caffe_settings self.caffe2_settings = caffe2_settings self.chainer_settings = chainer_settings self.custom_toolkit_settings = custom_toolkit_settings self.custom_mpi_settings = custom_mpi_settings self.horovod_settings = horovod_settings self.job_preparation = job_preparation self.job_output_directory_path_segment = None self.std_out_err_path_prefix = std_out_err_path_prefix self.input_directories = input_directories self.output_directories = output_directories self.environment_variables = environment_variables self.secrets = secrets self.constraints = constraints self.creation_time = None self.provisioning_state = None self.provisioning_state_transition_time = None self.execution_state = None self.execution_state_transition_time = None self.execution_info = execution_info class JobBasePropertiesConstraints(msrest.serialization.Model): """Constraints associated with the Job. :param max_wall_clock_time: Max time the job can run. Default value: 1 week. :type max_wall_clock_time: ~datetime.timedelta """ _attribute_map = { 'max_wall_clock_time': {'key': 'maxWallClockTime', 'type': 'duration'}, } def __init__( self, *, max_wall_clock_time: Optional[datetime.timedelta] = "7.00:00:00", **kwargs ): super(JobBasePropertiesConstraints, self).__init__(**kwargs) self.max_wall_clock_time = max_wall_clock_time class JobCreateParameters(msrest.serialization.Model): """Job creation parameters. :param scheduling_priority: Scheduling priority associated with the job. Possible values: low, normal, high. Possible values include: "low", "normal", "high". :type scheduling_priority: str or ~batch_ai.models.JobPriority :param cluster: Resource ID of the cluster on which this job will run. :type cluster: ~batch_ai.models.ResourceId :param mount_volumes: Information on mount volumes to be used by the job. These volumes will be mounted before the job execution and will be unmounted after the job completion. The volumes will be mounted at location specified by $AZ_BATCHAI_JOB_MOUNT_ROOT environment variable. :type mount_volumes: ~batch_ai.models.MountVolumes :param node_count: Number of compute nodes to run the job on. The job will be gang scheduled on that many compute nodes. :type node_count: int :param container_settings: Docker container settings for the job. If not provided, the job will run directly on the node. :type container_settings: ~batch_ai.models.ContainerSettings :param cntk_settings: Settings for CNTK (aka Microsoft Cognitive Toolkit) job. :type cntk_settings: ~batch_ai.models.CNTKsettings :param py_torch_settings: Settings for pyTorch job. :type py_torch_settings: ~batch_ai.models.PyTorchSettings :param tensor_flow_settings: Settings for Tensor Flow job. :type tensor_flow_settings: ~batch_ai.models.TensorFlowSettings :param caffe_settings: Settings for Caffe job. :type caffe_settings: ~batch_ai.models.CaffeSettings :param caffe2_settings: Settings for Caffe2 job. :type caffe2_settings: ~batch_ai.models.Caffe2Settings :param chainer_settings: Settings for Chainer job. :type chainer_settings: ~batch_ai.models.ChainerSettings :param custom_toolkit_settings: Settings for custom tool kit job. :type custom_toolkit_settings: ~batch_ai.models.CustomToolkitSettings :param custom_mpi_settings: Settings for custom MPI job. :type custom_mpi_settings: ~batch_ai.models.CustomMpiSettings :param horovod_settings: Settings for Horovod job. :type horovod_settings: ~batch_ai.models.HorovodSettings :param job_preparation: A command line to be executed on each node allocated for the job before tool kit is launched. :type job_preparation: ~batch_ai.models.JobPreparation :param std_out_err_path_prefix: The path where the Batch AI service will store stdout, stderror and execution log of the job. :type std_out_err_path_prefix: str :param input_directories: A list of input directories for the job. :type input_directories: list[~batch_ai.models.InputDirectory] :param output_directories: A list of output directories for the job. :type output_directories: list[~batch_ai.models.OutputDirectory] :param environment_variables: A list of user defined environment variables which will be setup for the job. :type environment_variables: list[~batch_ai.models.EnvironmentVariable] :param secrets: A list of user defined environment variables with secret values which will be setup for the job. Server will never report values of these variables back. :type secrets: list[~batch_ai.models.EnvironmentVariableWithSecretValue] :param constraints: Constraints associated with the Job. :type constraints: ~batch_ai.models.JobBasePropertiesConstraints """ _attribute_map = { 'scheduling_priority': {'key': 'properties.schedulingPriority', 'type': 'str'}, 'cluster': {'key': 'properties.cluster', 'type': 'ResourceId'}, 'mount_volumes': {'key': 'properties.mountVolumes', 'type': 'MountVolumes'}, 'node_count': {'key': 'properties.nodeCount', 'type': 'int'}, 'container_settings': {'key': 'properties.containerSettings', 'type': 'ContainerSettings'}, 'cntk_settings': {'key': 'properties.cntkSettings', 'type': 'CNTKsettings'}, 'py_torch_settings': {'key': 'properties.pyTorchSettings', 'type': 'PyTorchSettings'}, 'tensor_flow_settings': {'key': 'properties.tensorFlowSettings', 'type': 'TensorFlowSettings'}, 'caffe_settings': {'key': 'properties.caffeSettings', 'type': 'CaffeSettings'}, 'caffe2_settings': {'key': 'properties.caffe2Settings', 'type': 'Caffe2Settings'}, 'chainer_settings': {'key': 'properties.chainerSettings', 'type': 'ChainerSettings'}, 'custom_toolkit_settings': {'key': 'properties.customToolkitSettings', 'type': 'CustomToolkitSettings'}, 'custom_mpi_settings': {'key': 'properties.customMpiSettings', 'type': 'CustomMpiSettings'}, 'horovod_settings': {'key': 'properties.horovodSettings', 'type': 'HorovodSettings'}, 'job_preparation': {'key': 'properties.jobPreparation', 'type': 'JobPreparation'}, 'std_out_err_path_prefix': {'key': 'properties.stdOutErrPathPrefix', 'type': 'str'}, 'input_directories': {'key': 'properties.inputDirectories', 'type': '[InputDirectory]'}, 'output_directories': {'key': 'properties.outputDirectories', 'type': '[OutputDirectory]'}, 'environment_variables': {'key': 'properties.environmentVariables', 'type': '[EnvironmentVariable]'}, 'secrets': {'key': 'properties.secrets', 'type': '[EnvironmentVariableWithSecretValue]'}, 'constraints': {'key': 'properties.constraints', 'type': 'JobBasePropertiesConstraints'}, } def __init__( self, *, scheduling_priority: Optional[Union[str, "JobPriority"]] = None, cluster: Optional["ResourceId"] = None, mount_volumes: Optional["MountVolumes"] = None, node_count: Optional[int] = None, container_settings: Optional["ContainerSettings"] = None, cntk_settings: Optional["CNTKsettings"] = None, py_torch_settings: Optional["PyTorchSettings"] = None, tensor_flow_settings: Optional["TensorFlowSettings"] = None, caffe_settings: Optional["CaffeSettings"] = None, caffe2_settings: Optional["Caffe2Settings"] = None, chainer_settings: Optional["ChainerSettings"] = None, custom_toolkit_settings: Optional["CustomToolkitSettings"] = None, custom_mpi_settings: Optional["CustomMpiSettings"] = None, horovod_settings: Optional["HorovodSettings"] = None, job_preparation: Optional["JobPreparation"] = None, std_out_err_path_prefix: Optional[str] = None, input_directories: Optional[List["InputDirectory"]] = None, output_directories: Optional[List["OutputDirectory"]] = None, environment_variables: Optional[List["EnvironmentVariable"]] = None, secrets: Optional[List["EnvironmentVariableWithSecretValue"]] = None, constraints: Optional["JobBasePropertiesConstraints"] = None, **kwargs ): super(JobCreateParameters, self).__init__(**kwargs) self.scheduling_priority = scheduling_priority self.cluster = cluster self.mount_volumes = mount_volumes self.node_count = node_count self.container_settings = container_settings self.cntk_settings = cntk_settings self.py_torch_settings = py_torch_settings self.tensor_flow_settings = tensor_flow_settings self.caffe_settings = caffe_settings self.caffe2_settings = caffe2_settings self.chainer_settings = chainer_settings self.custom_toolkit_settings = custom_toolkit_settings self.custom_mpi_settings = custom_mpi_settings self.horovod_settings = horovod_settings self.job_preparation = job_preparation self.std_out_err_path_prefix = std_out_err_path_prefix self.input_directories = input_directories self.output_directories = output_directories self.environment_variables = environment_variables self.secrets = secrets self.constraints = constraints class JobListResult(msrest.serialization.Model): """Values returned by the List operation. Variables are only populated by the server, and will be ignored when sending a request. :ivar value: The collection of jobs. :vartype value: list[~batch_ai.models.Job] :ivar next_link: The continuation token. :vartype next_link: str """ _validation = { 'value': {'readonly': True}, 'next_link': {'readonly': True}, } _attribute_map = { 'value': {'key': 'value', 'type': '[Job]'}, 'next_link': {'key': 'nextLink', 'type': 'str'}, } def __init__( self, **kwargs ): super(JobListResult, self).__init__(**kwargs) self.value = None self.next_link = None class JobPreparation(msrest.serialization.Model): """Job preparation settings. All required parameters must be populated in order to send to Azure. :param command_line: Required. The command line to execute. If containerSettings is specified on the job, this commandLine will be executed in the same container as job. Otherwise it will be executed on the node. :type command_line: str """ _validation = { 'command_line': {'required': True}, } _attribute_map = { 'command_line': {'key': 'commandLine', 'type': 'str'}, } def __init__( self, *, command_line: str, **kwargs ): super(JobPreparation, self).__init__(**kwargs) self.command_line = command_line class JobPropertiesConstraints(msrest.serialization.Model): """Constraints associated with the Job. :param max_wall_clock_time: Max time the job can run. Default value: 1 week. :type max_wall_clock_time: ~datetime.timedelta """ _attribute_map = { 'max_wall_clock_time': {'key': 'maxWallClockTime', 'type': 'duration'}, } def __init__( self, *, max_wall_clock_time: Optional[datetime.timedelta] = "7.00:00:00", **kwargs ): super(JobPropertiesConstraints, self).__init__(**kwargs) self.max_wall_clock_time = max_wall_clock_time class JobPropertiesExecutionInfo(msrest.serialization.Model): """Information about the execution of a job. Variables are only populated by the server, and will be ignored when sending a request. :ivar start_time: The time at which the job started running. 'Running' corresponds to the running state. If the job has been restarted or retried, this is the most recent time at which the job started running. This property is present only for job that are in the running or completed state. :vartype start_time: ~datetime.datetime :ivar end_time: The time at which the job completed. This property is only returned if the job is in completed state. :vartype end_time: ~datetime.datetime :ivar exit_code: The exit code of the job. This property is only returned if the job is in completed state. :vartype exit_code: int :ivar errors: A collection of errors encountered by the service during job execution. :vartype errors: list[~batch_ai.models.BatchAIError] """ _validation = { 'start_time': {'readonly': True}, 'end_time': {'readonly': True}, 'exit_code': {'readonly': True}, 'errors': {'readonly': True}, } _attribute_map = { 'start_time': {'key': 'startTime', 'type': 'iso-8601'}, 'end_time': {'key': 'endTime', 'type': 'iso-8601'}, 'exit_code': {'key': 'exitCode', 'type': 'int'}, 'errors': {'key': 'errors', 'type': '[BatchAIError]'}, } def __init__( self, **kwargs ): super(JobPropertiesExecutionInfo, self).__init__(**kwargs) self.start_time = None self.end_time = None self.exit_code = None self.errors = None class JobsListByExperimentOptions(msrest.serialization.Model): """Parameter group. :param max_results: The maximum number of items to return in the response. A maximum of 1000 files can be returned. :type max_results: int """ _validation = { 'max_results': {'maximum': 1000, 'minimum': 1}, } _attribute_map = { 'max_results': {'key': 'maxResults', 'type': 'int'}, } def __init__( self, *, max_results: Optional[int] = 1000, **kwargs ): super(JobsListByExperimentOptions, self).__init__(**kwargs) self.max_results = max_results class JobsListOutputFilesOptions(msrest.serialization.Model): """Parameter group. All required parameters must be populated in order to send to Azure. :param outputdirectoryid: Required. Id of the job output directory. This is the OutputDirectory-->id parameter that is given by the user during Create Job. :type outputdirectoryid: str :param directory: The path to the directory. :type directory: str :param linkexpiryinminutes: The number of minutes after which the download link will expire. :type linkexpiryinminutes: int :param max_results: The maximum number of items to return in the response. A maximum of 1000 files can be returned. :type max_results: int """ _validation = { 'outputdirectoryid': {'required': True}, 'linkexpiryinminutes': {'maximum': 600, 'minimum': 5}, 'max_results': {'maximum': 1000, 'minimum': 1}, } _attribute_map = { 'outputdirectoryid': {'key': 'outputdirectoryid', 'type': 'str'}, 'directory': {'key': 'directory', 'type': 'str'}, 'linkexpiryinminutes': {'key': 'linkexpiryinminutes', 'type': 'int'}, 'max_results': {'key': 'maxResults', 'type': 'int'}, } def __init__( self, *, outputdirectoryid: str, directory: Optional[str] = ".", linkexpiryinminutes: Optional[int] = 60, max_results: Optional[int] = 1000, **kwargs ): super(JobsListOutputFilesOptions, self).__init__(**kwargs) self.outputdirectoryid = outputdirectoryid self.directory = directory self.linkexpiryinminutes = linkexpiryinminutes self.max_results = max_results class KeyVaultSecretReference(msrest.serialization.Model): """Key Vault Secret reference. All required parameters must be populated in order to send to Azure. :param source_vault: Required. Fully qualified resource identifier of the Key Vault. :type source_vault: ~batch_ai.models.ResourceId :param secret_url: Required. The URL referencing a secret in the Key Vault. :type secret_url: str """ _validation = { 'source_vault': {'required': True}, 'secret_url': {'required': True}, } _attribute_map = { 'source_vault': {'key': 'sourceVault', 'type': 'ResourceId'}, 'secret_url': {'key': 'secretUrl', 'type': 'str'}, } def __init__( self, *, source_vault: "ResourceId", secret_url: str, **kwargs ): super(KeyVaultSecretReference, self).__init__(**kwargs) self.source_vault = source_vault self.secret_url = secret_url class ListUsagesResult(msrest.serialization.Model): """The List Usages operation response. Variables are only populated by the server, and will be ignored when sending a request. :ivar value: The list of compute resource usages. :vartype value: list[~batch_ai.models.Usage] :ivar next_link: The URI to fetch the next page of compute resource usage information. Call ListNext() with this to fetch the next page of compute resource usage information. :vartype next_link: str """ _validation = { 'value': {'readonly': True}, 'next_link': {'readonly': True}, } _attribute_map = { 'value': {'key': 'value', 'type': '[Usage]'}, 'next_link': {'key': 'nextLink', 'type': 'str'}, } def __init__( self, **kwargs ): super(ListUsagesResult, self).__init__(**kwargs) self.value = None self.next_link = None class ManualScaleSettings(msrest.serialization.Model): """Manual scale settings for the cluster. All required parameters must be populated in order to send to Azure. :param target_node_count: Required. The desired number of compute nodes in the Cluster. Default is 0. :type target_node_count: int :param node_deallocation_option: An action to be performed when the cluster size is decreasing. The default value is requeue. Possible values include: "requeue", "terminate", "waitforjobcompletion". Default value: "requeue". :type node_deallocation_option: str or ~batch_ai.models.DeallocationOption """ _validation = { 'target_node_count': {'required': True}, } _attribute_map = { 'target_node_count': {'key': 'targetNodeCount', 'type': 'int'}, 'node_deallocation_option': {'key': 'nodeDeallocationOption', 'type': 'str'}, } def __init__( self, *, target_node_count: int, node_deallocation_option: Optional[Union[str, "DeallocationOption"]] = "requeue", **kwargs ): super(ManualScaleSettings, self).__init__(**kwargs) self.target_node_count = target_node_count self.node_deallocation_option = node_deallocation_option class MountSettings(msrest.serialization.Model): """File Server mount Information. :param mount_point: Path where the data disks are mounted on the File Server. :type mount_point: str :param file_server_public_ip: Public IP address of the File Server which can be used to SSH to the node from outside of the subnet. :type file_server_public_ip: str :param file_server_internal_ip: Internal IP address of the File Server which can be used to access the File Server from within the subnet. :type file_server_internal_ip: str """ _attribute_map = { 'mount_point': {'key': 'mountPoint', 'type': 'str'}, 'file_server_public_ip': {'key': 'fileServerPublicIP', 'type': 'str'}, 'file_server_internal_ip': {'key': 'fileServerInternalIP', 'type': 'str'}, } def __init__( self, *, mount_point: Optional[str] = None, file_server_public_ip: Optional[str] = None, file_server_internal_ip: Optional[str] = None, **kwargs ): super(MountSettings, self).__init__(**kwargs) self.mount_point = mount_point self.file_server_public_ip = file_server_public_ip self.file_server_internal_ip = file_server_internal_ip class MountVolumes(msrest.serialization.Model): """Details of volumes to mount on the cluster. :param azure_file_shares: A collection of Azure File Shares that are to be mounted to the cluster nodes. :type azure_file_shares: list[~batch_ai.models.AzureFileShareReference] :param azure_blob_file_systems: A collection of Azure Blob Containers that are to be mounted to the cluster nodes. :type azure_blob_file_systems: list[~batch_ai.models.AzureBlobFileSystemReference] :param file_servers: A collection of Batch AI File Servers that are to be mounted to the cluster nodes. :type file_servers: list[~batch_ai.models.FileServerReference] :param unmanaged_file_systems: A collection of unmanaged file systems that are to be mounted to the cluster nodes. :type unmanaged_file_systems: list[~batch_ai.models.UnmanagedFileSystemReference] """ _attribute_map = { 'azure_file_shares': {'key': 'azureFileShares', 'type': '[AzureFileShareReference]'}, 'azure_blob_file_systems': {'key': 'azureBlobFileSystems', 'type': '[AzureBlobFileSystemReference]'}, 'file_servers': {'key': 'fileServers', 'type': '[FileServerReference]'}, 'unmanaged_file_systems': {'key': 'unmanagedFileSystems', 'type': '[UnmanagedFileSystemReference]'}, } def __init__( self, *, azure_file_shares: Optional[List["AzureFileShareReference"]] = None, azure_blob_file_systems: Optional[List["AzureBlobFileSystemReference"]] = None, file_servers: Optional[List["FileServerReference"]] = None, unmanaged_file_systems: Optional[List["UnmanagedFileSystemReference"]] = None, **kwargs ): super(MountVolumes, self).__init__(**kwargs) self.azure_file_shares = azure_file_shares self.azure_blob_file_systems = azure_blob_file_systems self.file_servers = file_servers self.unmanaged_file_systems = unmanaged_file_systems class NameValuePair(msrest.serialization.Model): """Name-value pair. :param name: The name in the name-value pair. :type name: str :param value: The value in the name-value pair. :type value: str """ _attribute_map = { 'name': {'key': 'name', 'type': 'str'}, 'value': {'key': 'value', 'type': 'str'}, } def __init__( self, *, name: Optional[str] = None, value: Optional[str] = None, **kwargs ): super(NameValuePair, self).__init__(**kwargs) self.name = name self.value = value class NodeSetup(msrest.serialization.Model): """Node setup settings. :param setup_task: Setup task to run on cluster nodes when nodes got created or rebooted. The setup task code needs to be idempotent. Generally the setup task is used to download static data that is required for all jobs that run on the cluster VMs and/or to download/install software. :type setup_task: ~batch_ai.models.SetupTask :param mount_volumes: Mount volumes to be available to setup task and all jobs executing on the cluster. The volumes will be mounted at location specified by $AZ_BATCHAI_MOUNT_ROOT environment variable. :type mount_volumes: ~batch_ai.models.MountVolumes :param performance_counters_settings: Settings for performance counters collecting and uploading. :type performance_counters_settings: ~batch_ai.models.PerformanceCountersSettings """ _attribute_map = { 'setup_task': {'key': 'setupTask', 'type': 'SetupTask'}, 'mount_volumes': {'key': 'mountVolumes', 'type': 'MountVolumes'}, 'performance_counters_settings': {'key': 'performanceCountersSettings', 'type': 'PerformanceCountersSettings'}, } def __init__( self, *, setup_task: Optional["SetupTask"] = None, mount_volumes: Optional["MountVolumes"] = None, performance_counters_settings: Optional["PerformanceCountersSettings"] = None, **kwargs ): super(NodeSetup, self).__init__(**kwargs) self.setup_task = setup_task self.mount_volumes = mount_volumes self.performance_counters_settings = performance_counters_settings class NodeStateCounts(msrest.serialization.Model): """Counts of various compute node states on the cluster. Variables are only populated by the server, and will be ignored when sending a request. :ivar idle_node_count: Number of compute nodes in idle state. :vartype idle_node_count: int :ivar running_node_count: Number of compute nodes which are running jobs. :vartype running_node_count: int :ivar preparing_node_count: Number of compute nodes which are being prepared. :vartype preparing_node_count: int :ivar unusable_node_count: Number of compute nodes which are in unusable state. :vartype unusable_node_count: int :ivar leaving_node_count: Number of compute nodes which are leaving the cluster. :vartype leaving_node_count: int """ _validation = { 'idle_node_count': {'readonly': True}, 'running_node_count': {'readonly': True}, 'preparing_node_count': {'readonly': True}, 'unusable_node_count': {'readonly': True}, 'leaving_node_count': {'readonly': True}, } _attribute_map = { 'idle_node_count': {'key': 'idleNodeCount', 'type': 'int'}, 'running_node_count': {'key': 'runningNodeCount', 'type': 'int'}, 'preparing_node_count': {'key': 'preparingNodeCount', 'type': 'int'}, 'unusable_node_count': {'key': 'unusableNodeCount', 'type': 'int'}, 'leaving_node_count': {'key': 'leavingNodeCount', 'type': 'int'}, } def __init__( self, **kwargs ): super(NodeStateCounts, self).__init__(**kwargs) self.idle_node_count = None self.running_node_count = None self.preparing_node_count = None self.unusable_node_count = None self.leaving_node_count = None class Operation(msrest.serialization.Model): """Details of a REST API operation. Variables are only populated by the server, and will be ignored when sending a request. :ivar name: This is of the format {provider}/{resource}/{operation}. :vartype name: str :param display: The object that describes the operation. :type display: ~batch_ai.models.OperationDisplay :ivar origin: The intended executor of the operation. :vartype origin: str :param properties: Any object. :type properties: any """ _validation = { 'name': {'readonly': True}, 'origin': {'readonly': True}, } _attribute_map = { 'name': {'key': 'name', 'type': 'str'}, 'display': {'key': 'display', 'type': 'OperationDisplay'}, 'origin': {'key': 'origin', 'type': 'str'}, 'properties': {'key': 'properties', 'type': 'object'}, } def __init__( self, *, display: Optional["OperationDisplay"] = None, properties: Optional[Any] = None, **kwargs ): super(Operation, self).__init__(**kwargs) self.name = None self.display = display self.origin = None self.properties = properties class OperationDisplay(msrest.serialization.Model): """The object that describes the operation. Variables are only populated by the server, and will be ignored when sending a request. :ivar provider: Friendly name of the resource provider. :vartype provider: str :ivar operation: For example: read, write, delete, or listKeys/action. :vartype operation: str :ivar resource: The resource type on which the operation is performed. :vartype resource: str :ivar description: The friendly name of the operation. :vartype description: str """ _validation = { 'provider': {'readonly': True}, 'operation': {'readonly': True}, 'resource': {'readonly': True}, 'description': {'readonly': True}, } _attribute_map = { 'provider': {'key': 'provider', 'type': 'str'}, 'operation': {'key': 'operation', 'type': 'str'}, 'resource': {'key': 'resource', 'type': 'str'}, 'description': {'key': 'description', 'type': 'str'}, } def __init__( self, **kwargs ): super(OperationDisplay, self).__init__(**kwargs) self.provider = None self.operation = None self.resource = None self.description = None class OperationListResult(msrest.serialization.Model): """Contains the list of all operations supported by BatchAI resource provider. Variables are only populated by the server, and will be ignored when sending a request. :ivar value: The list of operations supported by the resource provider. :vartype value: list[~batch_ai.models.Operation] :ivar next_link: The URL to get the next set of operation list results if there are any. :vartype next_link: str """ _validation = { 'value': {'readonly': True}, 'next_link': {'readonly': True}, } _attribute_map = { 'value': {'key': 'value', 'type': '[Operation]'}, 'next_link': {'key': 'nextLink', 'type': 'str'}, } def __init__( self, **kwargs ): super(OperationListResult, self).__init__(**kwargs) self.value = None self.next_link = None class OutputDirectory(msrest.serialization.Model): """Output directory for the job. All required parameters must be populated in order to send to Azure. :param id: Required. The ID of the output directory. The job can use AZ_BATCHAI\ *OUTPUT*\ :code:`<id>` environment variable to find the directory path, where :code:`<id>` is the value of id attribute. :type id: str :param path_prefix: Required. The prefix path where the output directory will be created. Note, this is an absolute path to prefix. E.g. $AZ_BATCHAI_MOUNT_ROOT/MyNFS/MyLogs. The full path to the output directory by combining pathPrefix, jobOutputDirectoryPathSegment (reported by get job) and pathSuffix. :type path_prefix: str :param path_suffix: The suffix path where the output directory will be created. E.g. models. You can find the full path to the output directory by combining pathPrefix, jobOutputDirectoryPathSegment (reported by get job) and pathSuffix. :type path_suffix: str """ _validation = { 'id': {'required': True}, 'path_prefix': {'required': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'path_prefix': {'key': 'pathPrefix', 'type': 'str'}, 'path_suffix': {'key': 'pathSuffix', 'type': 'str'}, } def __init__( self, *, id: str, path_prefix: str, path_suffix: Optional[str] = None, **kwargs ): super(OutputDirectory, self).__init__(**kwargs) self.id = id self.path_prefix = path_prefix self.path_suffix = path_suffix class PerformanceCountersSettings(msrest.serialization.Model): """Performance counters reporting settings. All required parameters must be populated in order to send to Azure. :param app_insights_reference: Required. Azure Application Insights information for performance counters reporting. If provided, Batch AI will upload node performance counters to the corresponding Azure Application Insights account. :type app_insights_reference: ~batch_ai.models.AppInsightsReference """ _validation = { 'app_insights_reference': {'required': True}, } _attribute_map = { 'app_insights_reference': {'key': 'appInsightsReference', 'type': 'AppInsightsReference'}, } def __init__( self, *, app_insights_reference: "AppInsightsReference", **kwargs ): super(PerformanceCountersSettings, self).__init__(**kwargs) self.app_insights_reference = app_insights_reference class PrivateRegistryCredentials(msrest.serialization.Model): """Credentials to access a container image in a private repository. All required parameters must be populated in order to send to Azure. :param username: Required. User name to login to the repository. :type username: str :param password: User password to login to the docker repository. One of password or passwordSecretReference must be specified. :type password: str :param password_secret_reference: KeyVault Secret storing the password. Users can store their secrets in Azure KeyVault and pass it to the Batch AI service to integrate with KeyVault. One of password or passwordSecretReference must be specified. :type password_secret_reference: ~batch_ai.models.KeyVaultSecretReference """ _validation = { 'username': {'required': True}, } _attribute_map = { 'username': {'key': 'username', 'type': 'str'}, 'password': {'key': 'password', 'type': 'str'}, 'password_secret_reference': {'key': 'passwordSecretReference', 'type': 'KeyVaultSecretReference'}, } def __init__( self, *, username: str, password: Optional[str] = None, password_secret_reference: Optional["KeyVaultSecretReference"] = None, **kwargs ): super(PrivateRegistryCredentials, self).__init__(**kwargs) self.username = username self.password = password self.password_secret_reference = password_secret_reference class PyTorchSettings(msrest.serialization.Model): """pyTorch job settings. All required parameters must be populated in order to send to Azure. :param python_script_file_path: Required. The python script to execute. :type python_script_file_path: str :param python_interpreter_path: The path to the Python interpreter. :type python_interpreter_path: str :param command_line_args: Command line arguments that need to be passed to the python script. :type command_line_args: str :param process_count: Number of processes to launch for the job execution. The default value for this property is equal to nodeCount property. :type process_count: int :param communication_backend: Type of the communication backend for distributed jobs. Valid values are 'TCP', 'Gloo' or 'MPI'. Not required for non-distributed jobs. :type communication_backend: str """ _validation = { 'python_script_file_path': {'required': True}, } _attribute_map = { 'python_script_file_path': {'key': 'pythonScriptFilePath', 'type': 'str'}, 'python_interpreter_path': {'key': 'pythonInterpreterPath', 'type': 'str'}, 'command_line_args': {'key': 'commandLineArgs', 'type': 'str'}, 'process_count': {'key': 'processCount', 'type': 'int'}, 'communication_backend': {'key': 'communicationBackend', 'type': 'str'}, } def __init__( self, *, python_script_file_path: str, python_interpreter_path: Optional[str] = None, command_line_args: Optional[str] = None, process_count: Optional[int] = None, communication_backend: Optional[str] = None, **kwargs ): super(PyTorchSettings, self).__init__(**kwargs) self.python_script_file_path = python_script_file_path self.python_interpreter_path = python_interpreter_path self.command_line_args = command_line_args self.process_count = process_count self.communication_backend = communication_backend class RemoteLoginInformation(msrest.serialization.Model): """Login details to SSH to a compute node in cluster. Variables are only populated by the server, and will be ignored when sending a request. :ivar node_id: ID of the compute node. :vartype node_id: str :ivar ip_address: Public IP address of the compute node. :vartype ip_address: str :ivar port: SSH port number of the node. :vartype port: int """ _validation = { 'node_id': {'readonly': True}, 'ip_address': {'readonly': True}, 'port': {'readonly': True}, } _attribute_map = { 'node_id': {'key': 'nodeId', 'type': 'str'}, 'ip_address': {'key': 'ipAddress', 'type': 'str'}, 'port': {'key': 'port', 'type': 'int'}, } def __init__( self, **kwargs ): super(RemoteLoginInformation, self).__init__(**kwargs) self.node_id = None self.ip_address = None self.port = None class RemoteLoginInformationListResult(msrest.serialization.Model): """Values returned by the List operation. Variables are only populated by the server, and will be ignored when sending a request. :ivar value: The collection of returned remote login details. :vartype value: list[~batch_ai.models.RemoteLoginInformation] :ivar next_link: The continuation token. :vartype next_link: str """ _validation = { 'value': {'readonly': True}, 'next_link': {'readonly': True}, } _attribute_map = { 'value': {'key': 'value', 'type': '[RemoteLoginInformation]'}, 'next_link': {'key': 'nextLink', 'type': 'str'}, } def __init__( self, **kwargs ): super(RemoteLoginInformationListResult, self).__init__(**kwargs) self.value = None self.next_link = None class Resource(msrest.serialization.Model): """A definition of an Azure resource. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: The ID of the resource. :vartype id: str :ivar name: The name of the resource. :vartype name: str :ivar type: The type of the resource. :vartype type: str :ivar location: The location of the resource. :vartype location: str :ivar tags: A set of tags. The tags of the resource. :vartype tags: dict[str, str] """ _validation = { 'id': {'readonly': True}, 'name': {'readonly': True}, 'type': {'readonly': True}, 'location': {'readonly': True}, 'tags': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'location': {'key': 'location', 'type': 'str'}, 'tags': {'key': 'tags', 'type': '{str}'}, } def __init__( self, **kwargs ): super(Resource, self).__init__(**kwargs) self.id = None self.name = None self.type = None self.location = None self.tags = None class ResourceId(msrest.serialization.Model): """Represents a resource ID. For example, for a subnet, it is the resource URL for the subnet. All required parameters must be populated in order to send to Azure. :param id: Required. The ID of the resource. :type id: str """ _validation = { 'id': {'required': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, } def __init__( self, *, id: str, **kwargs ): super(ResourceId, self).__init__(**kwargs) self.id = id class ScaleSettings(msrest.serialization.Model): """At least one of manual or autoScale settings must be specified. Only one of manual or autoScale settings can be specified. If autoScale settings are specified, the system automatically scales the cluster up and down (within the supplied limits) based on the pending jobs on the cluster. :param manual: Manual scale settings for the cluster. :type manual: ~batch_ai.models.ManualScaleSettings :param auto_scale: Auto-scale settings for the cluster. :type auto_scale: ~batch_ai.models.AutoScaleSettings """ _attribute_map = { 'manual': {'key': 'manual', 'type': 'ManualScaleSettings'}, 'auto_scale': {'key': 'autoScale', 'type': 'AutoScaleSettings'}, } def __init__( self, *, manual: Optional["ManualScaleSettings"] = None, auto_scale: Optional["AutoScaleSettings"] = None, **kwargs ): super(ScaleSettings, self).__init__(**kwargs) self.manual = manual self.auto_scale = auto_scale class SetupTask(msrest.serialization.Model): """Specifies a setup task which can be used to customize the compute nodes of the cluster. Variables are only populated by the server, and will be ignored when sending a request. All required parameters must be populated in order to send to Azure. :param command_line: Required. The command line to be executed on each cluster's node after it being allocated or rebooted. The command is executed in a bash subshell as a root. :type command_line: str :param environment_variables: A collection of user defined environment variables to be set for setup task. :type environment_variables: list[~batch_ai.models.EnvironmentVariable] :param secrets: A collection of user defined environment variables with secret values to be set for the setup task. Server will never report values of these variables back. :type secrets: list[~batch_ai.models.EnvironmentVariableWithSecretValue] :param std_out_err_path_prefix: Required. The prefix of a path where the Batch AI service will upload the stdout, stderr and execution log of the setup task. :type std_out_err_path_prefix: str :ivar std_out_err_path_suffix: A path segment appended by Batch AI to stdOutErrPathPrefix to form a path where stdout, stderr and execution log of the setup task will be uploaded. Batch AI creates the setup task output directories under an unique path to avoid conflicts between different clusters. The full path can be obtained by concatenation of stdOutErrPathPrefix and stdOutErrPathSuffix. :vartype std_out_err_path_suffix: str """ _validation = { 'command_line': {'required': True}, 'std_out_err_path_prefix': {'required': True}, 'std_out_err_path_suffix': {'readonly': True}, } _attribute_map = { 'command_line': {'key': 'commandLine', 'type': 'str'}, 'environment_variables': {'key': 'environmentVariables', 'type': '[EnvironmentVariable]'}, 'secrets': {'key': 'secrets', 'type': '[EnvironmentVariableWithSecretValue]'}, 'std_out_err_path_prefix': {'key': 'stdOutErrPathPrefix', 'type': 'str'}, 'std_out_err_path_suffix': {'key': 'stdOutErrPathSuffix', 'type': 'str'}, } def __init__( self, *, command_line: str, std_out_err_path_prefix: str, environment_variables: Optional[List["EnvironmentVariable"]] = None, secrets: Optional[List["EnvironmentVariableWithSecretValue"]] = None, **kwargs ): super(SetupTask, self).__init__(**kwargs) self.command_line = command_line self.environment_variables = environment_variables self.secrets = secrets self.std_out_err_path_prefix = std_out_err_path_prefix self.std_out_err_path_suffix = None class SshConfiguration(msrest.serialization.Model): """SSH configuration. All required parameters must be populated in order to send to Azure. :param public_ips_to_allow: List of source IP ranges to allow SSH connection from. The default value is '*' (all source IPs are allowed). Maximum number of IP ranges that can be specified is 400. :type public_ips_to_allow: list[str] :param user_account_settings: Required. Settings for administrator user account to be created on a node. The account can be used to establish SSH connection to the node. :type user_account_settings: ~batch_ai.models.UserAccountSettings """ _validation = { 'user_account_settings': {'required': True}, } _attribute_map = { 'public_ips_to_allow': {'key': 'publicIPsToAllow', 'type': '[str]'}, 'user_account_settings': {'key': 'userAccountSettings', 'type': 'UserAccountSettings'}, } def __init__( self, *, user_account_settings: "UserAccountSettings", public_ips_to_allow: Optional[List[str]] = None, **kwargs ): super(SshConfiguration, self).__init__(**kwargs) self.public_ips_to_allow = public_ips_to_allow self.user_account_settings = user_account_settings class TensorFlowSettings(msrest.serialization.Model): """TensorFlow job settings. All required parameters must be populated in order to send to Azure. :param python_script_file_path: Required. The python script to execute. :type python_script_file_path: str :param python_interpreter_path: The path to the Python interpreter. :type python_interpreter_path: str :param master_command_line_args: Command line arguments that need to be passed to the python script for the master task. :type master_command_line_args: str :param worker_command_line_args: Command line arguments that need to be passed to the python script for the worker task. Optional for single process jobs. :type worker_command_line_args: str :param parameter_server_command_line_args: Command line arguments that need to be passed to the python script for the parameter server. Optional for single process jobs. :type parameter_server_command_line_args: str :param worker_count: The number of worker tasks. If specified, the value must be less than or equal to (nodeCount * numberOfGPUs per VM). If not specified, the default value is equal to nodeCount. This property can be specified only for distributed TensorFlow training. :type worker_count: int :param parameter_server_count: The number of parameter server tasks. If specified, the value must be less than or equal to nodeCount. If not specified, the default value is equal to 1 for distributed TensorFlow training. This property can be specified only for distributed TensorFlow training. :type parameter_server_count: int """ _validation = { 'python_script_file_path': {'required': True}, } _attribute_map = { 'python_script_file_path': {'key': 'pythonScriptFilePath', 'type': 'str'}, 'python_interpreter_path': {'key': 'pythonInterpreterPath', 'type': 'str'}, 'master_command_line_args': {'key': 'masterCommandLineArgs', 'type': 'str'}, 'worker_command_line_args': {'key': 'workerCommandLineArgs', 'type': 'str'}, 'parameter_server_command_line_args': {'key': 'parameterServerCommandLineArgs', 'type': 'str'}, 'worker_count': {'key': 'workerCount', 'type': 'int'}, 'parameter_server_count': {'key': 'parameterServerCount', 'type': 'int'}, } def __init__( self, *, python_script_file_path: str, python_interpreter_path: Optional[str] = None, master_command_line_args: Optional[str] = None, worker_command_line_args: Optional[str] = None, parameter_server_command_line_args: Optional[str] = None, worker_count: Optional[int] = None, parameter_server_count: Optional[int] = None, **kwargs ): super(TensorFlowSettings, self).__init__(**kwargs) self.python_script_file_path = python_script_file_path self.python_interpreter_path = python_interpreter_path self.master_command_line_args = master_command_line_args self.worker_command_line_args = worker_command_line_args self.parameter_server_command_line_args = parameter_server_command_line_args self.worker_count = worker_count self.parameter_server_count = parameter_server_count class UnmanagedFileSystemReference(msrest.serialization.Model): """Unmanaged file system mounting configuration. All required parameters must be populated in order to send to Azure. :param mount_command: Required. Mount command line. Note, Batch AI will append mount path to the command on its own. :type mount_command: str :param relative_mount_path: Required. The relative path on the compute node where the unmanaged file system will be mounted. Note that all cluster level unmanaged file systems will be mounted under $AZ_BATCHAI_MOUNT_ROOT location and all job level unmanaged file systems will be mounted under $AZ_BATCHAI_JOB_MOUNT_ROOT. :type relative_mount_path: str """ _validation = { 'mount_command': {'required': True}, 'relative_mount_path': {'required': True}, } _attribute_map = { 'mount_command': {'key': 'mountCommand', 'type': 'str'}, 'relative_mount_path': {'key': 'relativeMountPath', 'type': 'str'}, } def __init__( self, *, mount_command: str, relative_mount_path: str, **kwargs ): super(UnmanagedFileSystemReference, self).__init__(**kwargs) self.mount_command = mount_command self.relative_mount_path = relative_mount_path class Usage(msrest.serialization.Model): """Describes Batch AI Resource Usage. Variables are only populated by the server, and will be ignored when sending a request. :ivar unit: An enum describing the unit of usage measurement. Possible values include: "Count". :vartype unit: str or ~batch_ai.models.UsageUnit :ivar current_value: The current usage of the resource. :vartype current_value: int :ivar limit: The maximum permitted usage of the resource. :vartype limit: long :ivar name: The name of the type of usage. :vartype name: ~batch_ai.models.UsageName """ _validation = { 'unit': {'readonly': True}, 'current_value': {'readonly': True}, 'limit': {'readonly': True}, 'name': {'readonly': True}, } _attribute_map = { 'unit': {'key': 'unit', 'type': 'str'}, 'current_value': {'key': 'currentValue', 'type': 'int'}, 'limit': {'key': 'limit', 'type': 'long'}, 'name': {'key': 'name', 'type': 'UsageName'}, } def __init__( self, **kwargs ): super(Usage, self).__init__(**kwargs) self.unit = None self.current_value = None self.limit = None self.name = None class UsageName(msrest.serialization.Model): """The Usage Names. Variables are only populated by the server, and will be ignored when sending a request. :ivar value: The name of the resource. :vartype value: str :ivar localized_value: The localized name of the resource. :vartype localized_value: str """ _validation = { 'value': {'readonly': True}, 'localized_value': {'readonly': True}, } _attribute_map = { 'value': {'key': 'value', 'type': 'str'}, 'localized_value': {'key': 'localizedValue', 'type': 'str'}, } def __init__( self, **kwargs ): super(UsageName, self).__init__(**kwargs) self.value = None self.localized_value = None class UserAccountSettings(msrest.serialization.Model): """Settings for user account that gets created on each on the nodes of a cluster. All required parameters must be populated in order to send to Azure. :param admin_user_name: Required. Name of the administrator user account which can be used to SSH to nodes. :type admin_user_name: str :param admin_user_ssh_public_key: SSH public key of the administrator user account. :type admin_user_ssh_public_key: str :param admin_user_password: Password of the administrator user account. :type admin_user_password: str """ _validation = { 'admin_user_name': {'required': True}, } _attribute_map = { 'admin_user_name': {'key': 'adminUserName', 'type': 'str'}, 'admin_user_ssh_public_key': {'key': 'adminUserSshPublicKey', 'type': 'str'}, 'admin_user_password': {'key': 'adminUserPassword', 'type': 'str'}, } def __init__( self, *, admin_user_name: str, admin_user_ssh_public_key: Optional[str] = None, admin_user_password: Optional[str] = None, **kwargs ): super(UserAccountSettings, self).__init__(**kwargs) self.admin_user_name = admin_user_name self.admin_user_ssh_public_key = admin_user_ssh_public_key self.admin_user_password = admin_user_password class VirtualMachineConfiguration(msrest.serialization.Model): """VM configuration. :param image_reference: OS image reference for cluster nodes. :type image_reference: ~batch_ai.models.ImageReference """ _attribute_map = { 'image_reference': {'key': 'imageReference', 'type': 'ImageReference'}, } def __init__( self, *, image_reference: Optional["ImageReference"] = None, **kwargs ): super(VirtualMachineConfiguration, self).__init__(**kwargs) self.image_reference = image_reference class Workspace(Resource): """Batch AI Workspace information. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: The ID of the resource. :vartype id: str :ivar name: The name of the resource. :vartype name: str :ivar type: The type of the resource. :vartype type: str :ivar location: The location of the resource. :vartype location: str :ivar tags: A set of tags. The tags of the resource. :vartype tags: dict[str, str] :ivar creation_time: Time when the Workspace was created. :vartype creation_time: ~datetime.datetime :ivar provisioning_state: The provisioned state of the Workspace. Possible values include: "creating", "succeeded", "failed", "deleting". :vartype provisioning_state: str or ~batch_ai.models.ProvisioningState :ivar provisioning_state_transition_time: The time at which the workspace entered its current provisioning state. :vartype provisioning_state_transition_time: ~datetime.datetime """ _validation = { 'id': {'readonly': True}, 'name': {'readonly': True}, 'type': {'readonly': True}, 'location': {'readonly': True}, 'tags': {'readonly': True}, 'creation_time': {'readonly': True}, 'provisioning_state': {'readonly': True}, 'provisioning_state_transition_time': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'location': {'key': 'location', 'type': 'str'}, 'tags': {'key': 'tags', 'type': '{str}'}, 'creation_time': {'key': 'properties.creationTime', 'type': 'iso-8601'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'provisioning_state_transition_time': {'key': 'properties.provisioningStateTransitionTime', 'type': 'iso-8601'}, } def __init__( self, **kwargs ): super(Workspace, self).__init__(**kwargs) self.creation_time = None self.provisioning_state = None self.provisioning_state_transition_time = None class WorkspaceCreateParameters(msrest.serialization.Model): """Workspace creation parameters. All required parameters must be populated in order to send to Azure. :param location: Required. The region in which to create the Workspace. :type location: str :param tags: A set of tags. The user specified tags associated with the Workspace. :type tags: dict[str, str] """ _validation = { 'location': {'required': True}, } _attribute_map = { 'location': {'key': 'location', 'type': 'str'}, 'tags': {'key': 'tags', 'type': '{str}'}, } def __init__( self, *, location: str, tags: Optional[Dict[str, str]] = None, **kwargs ): super(WorkspaceCreateParameters, self).__init__(**kwargs) self.location = location self.tags = tags class WorkspaceListResult(msrest.serialization.Model): """Values returned by the List operation. Variables are only populated by the server, and will be ignored when sending a request. :ivar value: The collection of workspaces. :vartype value: list[~batch_ai.models.Workspace] :ivar next_link: The continuation token. :vartype next_link: str """ _validation = { 'value': {'readonly': True}, 'next_link': {'readonly': True}, } _attribute_map = { 'value': {'key': 'value', 'type': '[Workspace]'}, 'next_link': {'key': 'nextLink', 'type': 'str'}, } def __init__( self, **kwargs ): super(WorkspaceListResult, self).__init__(**kwargs) self.value = None self.next_link = None class WorkspacesListByResourceGroupOptions(msrest.serialization.Model): """Parameter group. :param max_results: The maximum number of items to return in the response. A maximum of 1000 files can be returned. :type max_results: int """ _validation = { 'max_results': {'maximum': 1000, 'minimum': 1}, } _attribute_map = { 'max_results': {'key': 'maxResults', 'type': 'int'}, } def __init__( self, *, max_results: Optional[int] = 1000, **kwargs ): super(WorkspacesListByResourceGroupOptions, self).__init__(**kwargs) self.max_results = max_results class WorkspacesListOptions(msrest.serialization.Model): """Parameter group. :param max_results: The maximum number of items to return in the response. A maximum of 1000 files can be returned. :type max_results: int """ _validation = { 'max_results': {'maximum': 1000, 'minimum': 1}, } _attribute_map = { 'max_results': {'key': 'maxResults', 'type': 'int'}, } def __init__( self, *, max_results: Optional[int] = 1000, **kwargs ): super(WorkspacesListOptions, self).__init__(**kwargs) self.max_results = max_results class WorkspaceUpdateParameters(msrest.serialization.Model): """Workspace update parameters. :param tags: A set of tags. The user specified tags associated with the Workspace. :type tags: dict[str, str] """ _attribute_map = { 'tags': {'key': 'tags', 'type': '{str}'}, } def __init__( self, *, tags: Optional[Dict[str, str]] = None, **kwargs ): super(WorkspaceUpdateParameters, self).__init__(**kwargs) self.tags = tags
0.938209
0.378718
from enum import Enum, EnumMeta from six import with_metaclass class _CaseInsensitiveEnumMeta(EnumMeta): def __getitem__(self, name): return super().__getitem__(name.upper()) def __getattr__(cls, name): """Return the enum member matching `name` We use __getattr__ instead of descriptors or inserting into the enum class' __dict__ in order to support `name` and `value` being both properties for enum members (which live in the class' __dict__) and enum members themselves. """ try: return cls._member_map_[name.upper()] except KeyError: raise AttributeError(name) class AllocationState(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): """Allocation state of the cluster. Possible values are: steady - Indicates that the cluster is not resizing. There are no changes to the number of compute nodes in the cluster in progress. A cluster enters this state when it is created and when no operations are being performed on the cluster to change the number of compute nodes. resizing - Indicates that the cluster is resizing; that is, compute nodes are being added to or removed from the cluster. """ STEADY = "steady" RESIZING = "resizing" class CachingType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): """Caching type for the disks. Available values are none (default), readonly, readwrite. Caching type can be set only for VM sizes supporting premium storage. """ NONE = "none" READONLY = "readonly" READWRITE = "readwrite" class DeallocationOption(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): """Actions which should be performed when compute nodes are removed from the cluster. Possible values are: requeue (default) - Terminate running jobs and requeue them so the jobs will run again. Remove compute nodes as soon as jobs have been terminated; terminate - Terminate running jobs. The jobs will not run again. Remove compute nodes as soon as jobs have been terminated. waitforjobcompletion - Allow currently running jobs to complete. Schedule no new jobs while waiting. Remove compute nodes when all jobs have completed. """ REQUEUE = "requeue" TERMINATE = "terminate" WAITFORJOBCOMPLETION = "waitforjobcompletion" class ExecutionState(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): """The current state of the job. Possible values are: queued - The job is queued and able to run. A job enters this state when it is created, or when it is awaiting a retry after a failed run. running - The job is running on a compute cluster. This includes job-level preparation such as downloading resource files or set up container specified on the job - it does not necessarily mean that the job command line has started executing. terminating - The job is terminated by the user, the terminate operation is in progress. succeeded - The job has completed running successfully and exited with exit code 0. failed - The job has finished unsuccessfully (failed with a non-zero exit code) and has exhausted its retry limit. A job is also marked as failed if an error occurred launching the job. """ QUEUED = "queued" RUNNING = "running" TERMINATING = "terminating" SUCCEEDED = "succeeded" FAILED = "failed" class FileServerProvisioningState(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): """Provisioning state of the File Server. Possible values: creating - The File Server is getting created; updating - The File Server creation has been accepted and it is getting updated; deleting - The user has requested that the File Server be deleted, and it is in the process of being deleted; failed - The File Server creation has failed with the specified error code. Details about the error code are specified in the message field; succeeded - The File Server creation has succeeded. """ CREATING = "creating" UPDATING = "updating" DELETING = "deleting" SUCCEEDED = "succeeded" FAILED = "failed" class FileType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): """Type of the file. Possible values are file and directory. """ FILE = "file" DIRECTORY = "directory" class JobPriority(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): """Scheduling priority associated with the job. Possible values: low, normal, high. """ LOW = "low" NORMAL = "normal" HIGH = "high" class ProvisioningState(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): """Provisioning state of the cluster. Possible value are: creating - Specifies that the cluster is being created. succeeded - Specifies that the cluster has been created successfully. failed - Specifies that the cluster creation has failed. deleting - Specifies that the cluster is being deleted. """ CREATING = "creating" SUCCEEDED = "succeeded" FAILED = "failed" DELETING = "deleting" class StorageAccountType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): """Type of storage account to be used on the disk. Possible values are: Standard_LRS or Premium_LRS. Premium storage account type can only be used with VM sizes supporting premium storage. """ STANDARD_LRS = "Standard_LRS" PREMIUM_LRS = "Premium_LRS" class ToolType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): """The toolkit type of the job. """ CNTK = "cntk" TENSORFLOW = "tensorflow" CAFFE = "caffe" CAFFE2 = "caffe2" CHAINER = "chainer" HOROVOD = "horovod" CUSTOMMPI = "custommpi" CUSTOM = "custom" class UsageUnit(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): """An enum describing the unit of usage measurement. """ COUNT = "Count" class VmPriority(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): """VM priority. Allowed values are: dedicated (default) and lowpriority. """ DEDICATED = "dedicated" LOWPRIORITY = "lowpriority"
azure-mgmt-batchai
/azure-mgmt-batchai-7.0.0b1.zip/azure-mgmt-batchai-7.0.0b1/azure/mgmt/batchai/models/_batch_ai_enums.py
_batch_ai_enums.py
from enum import Enum, EnumMeta from six import with_metaclass class _CaseInsensitiveEnumMeta(EnumMeta): def __getitem__(self, name): return super().__getitem__(name.upper()) def __getattr__(cls, name): """Return the enum member matching `name` We use __getattr__ instead of descriptors or inserting into the enum class' __dict__ in order to support `name` and `value` being both properties for enum members (which live in the class' __dict__) and enum members themselves. """ try: return cls._member_map_[name.upper()] except KeyError: raise AttributeError(name) class AllocationState(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): """Allocation state of the cluster. Possible values are: steady - Indicates that the cluster is not resizing. There are no changes to the number of compute nodes in the cluster in progress. A cluster enters this state when it is created and when no operations are being performed on the cluster to change the number of compute nodes. resizing - Indicates that the cluster is resizing; that is, compute nodes are being added to or removed from the cluster. """ STEADY = "steady" RESIZING = "resizing" class CachingType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): """Caching type for the disks. Available values are none (default), readonly, readwrite. Caching type can be set only for VM sizes supporting premium storage. """ NONE = "none" READONLY = "readonly" READWRITE = "readwrite" class DeallocationOption(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): """Actions which should be performed when compute nodes are removed from the cluster. Possible values are: requeue (default) - Terminate running jobs and requeue them so the jobs will run again. Remove compute nodes as soon as jobs have been terminated; terminate - Terminate running jobs. The jobs will not run again. Remove compute nodes as soon as jobs have been terminated. waitforjobcompletion - Allow currently running jobs to complete. Schedule no new jobs while waiting. Remove compute nodes when all jobs have completed. """ REQUEUE = "requeue" TERMINATE = "terminate" WAITFORJOBCOMPLETION = "waitforjobcompletion" class ExecutionState(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): """The current state of the job. Possible values are: queued - The job is queued and able to run. A job enters this state when it is created, or when it is awaiting a retry after a failed run. running - The job is running on a compute cluster. This includes job-level preparation such as downloading resource files or set up container specified on the job - it does not necessarily mean that the job command line has started executing. terminating - The job is terminated by the user, the terminate operation is in progress. succeeded - The job has completed running successfully and exited with exit code 0. failed - The job has finished unsuccessfully (failed with a non-zero exit code) and has exhausted its retry limit. A job is also marked as failed if an error occurred launching the job. """ QUEUED = "queued" RUNNING = "running" TERMINATING = "terminating" SUCCEEDED = "succeeded" FAILED = "failed" class FileServerProvisioningState(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): """Provisioning state of the File Server. Possible values: creating - The File Server is getting created; updating - The File Server creation has been accepted and it is getting updated; deleting - The user has requested that the File Server be deleted, and it is in the process of being deleted; failed - The File Server creation has failed with the specified error code. Details about the error code are specified in the message field; succeeded - The File Server creation has succeeded. """ CREATING = "creating" UPDATING = "updating" DELETING = "deleting" SUCCEEDED = "succeeded" FAILED = "failed" class FileType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): """Type of the file. Possible values are file and directory. """ FILE = "file" DIRECTORY = "directory" class JobPriority(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): """Scheduling priority associated with the job. Possible values: low, normal, high. """ LOW = "low" NORMAL = "normal" HIGH = "high" class ProvisioningState(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): """Provisioning state of the cluster. Possible value are: creating - Specifies that the cluster is being created. succeeded - Specifies that the cluster has been created successfully. failed - Specifies that the cluster creation has failed. deleting - Specifies that the cluster is being deleted. """ CREATING = "creating" SUCCEEDED = "succeeded" FAILED = "failed" DELETING = "deleting" class StorageAccountType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): """Type of storage account to be used on the disk. Possible values are: Standard_LRS or Premium_LRS. Premium storage account type can only be used with VM sizes supporting premium storage. """ STANDARD_LRS = "Standard_LRS" PREMIUM_LRS = "Premium_LRS" class ToolType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): """The toolkit type of the job. """ CNTK = "cntk" TENSORFLOW = "tensorflow" CAFFE = "caffe" CAFFE2 = "caffe2" CHAINER = "chainer" HOROVOD = "horovod" CUSTOMMPI = "custommpi" CUSTOM = "custom" class UsageUnit(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): """An enum describing the unit of usage measurement. """ COUNT = "Count" class VmPriority(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): """VM priority. Allowed values are: dedicated (default) and lowpriority. """ DEDICATED = "dedicated" LOWPRIORITY = "lowpriority"
0.751375
0.327857
try: from ._models_py3 import AppInsightsReference from ._models_py3 import AutoScaleSettings from ._models_py3 import AzureBlobFileSystemReference from ._models_py3 import AzureFileShareReference from ._models_py3 import AzureStorageCredentialsInfo from ._models_py3 import BatchAIError from ._models_py3 import CNTKsettings from ._models_py3 import Caffe2Settings from ._models_py3 import CaffeSettings from ._models_py3 import ChainerSettings from ._models_py3 import CloudErrorBody from ._models_py3 import Cluster from ._models_py3 import ClusterCreateParameters from ._models_py3 import ClusterListResult from ._models_py3 import ClusterUpdateParameters from ._models_py3 import ClustersListByWorkspaceOptions from ._models_py3 import ContainerSettings from ._models_py3 import CustomMpiSettings from ._models_py3 import CustomToolkitSettings from ._models_py3 import DataDisks from ._models_py3 import EnvironmentVariable from ._models_py3 import EnvironmentVariableWithSecretValue from ._models_py3 import Experiment from ._models_py3 import ExperimentListResult from ._models_py3 import ExperimentsListByWorkspaceOptions from ._models_py3 import File from ._models_py3 import FileListResult from ._models_py3 import FileServer from ._models_py3 import FileServerCreateParameters from ._models_py3 import FileServerListResult from ._models_py3 import FileServerReference from ._models_py3 import FileServersListByWorkspaceOptions from ._models_py3 import HorovodSettings from ._models_py3 import ImageReference from ._models_py3 import ImageSourceRegistry from ._models_py3 import InputDirectory from ._models_py3 import Job from ._models_py3 import JobBasePropertiesConstraints from ._models_py3 import JobCreateParameters from ._models_py3 import JobListResult from ._models_py3 import JobPreparation from ._models_py3 import JobPropertiesConstraints from ._models_py3 import JobPropertiesExecutionInfo from ._models_py3 import JobsListByExperimentOptions from ._models_py3 import JobsListOutputFilesOptions from ._models_py3 import KeyVaultSecretReference from ._models_py3 import ListUsagesResult from ._models_py3 import ManualScaleSettings from ._models_py3 import MountSettings from ._models_py3 import MountVolumes from ._models_py3 import NameValuePair from ._models_py3 import NodeSetup from ._models_py3 import NodeStateCounts from ._models_py3 import Operation from ._models_py3 import OperationDisplay from ._models_py3 import OperationListResult from ._models_py3 import OutputDirectory from ._models_py3 import PerformanceCountersSettings from ._models_py3 import PrivateRegistryCredentials from ._models_py3 import ProxyResource from ._models_py3 import PyTorchSettings from ._models_py3 import RemoteLoginInformation from ._models_py3 import RemoteLoginInformationListResult from ._models_py3 import Resource from ._models_py3 import ResourceId from ._models_py3 import ScaleSettings from ._models_py3 import SetupTask from ._models_py3 import SshConfiguration from ._models_py3 import TensorFlowSettings from ._models_py3 import UnmanagedFileSystemReference from ._models_py3 import Usage from ._models_py3 import UsageName from ._models_py3 import UserAccountSettings from ._models_py3 import VirtualMachineConfiguration from ._models_py3 import Workspace from ._models_py3 import WorkspaceCreateParameters from ._models_py3 import WorkspaceListResult from ._models_py3 import WorkspaceUpdateParameters from ._models_py3 import WorkspacesListByResourceGroupOptions from ._models_py3 import WorkspacesListOptions except (SyntaxError, ImportError): from ._models import AppInsightsReference # type: ignore from ._models import AutoScaleSettings # type: ignore from ._models import AzureBlobFileSystemReference # type: ignore from ._models import AzureFileShareReference # type: ignore from ._models import AzureStorageCredentialsInfo # type: ignore from ._models import BatchAIError # type: ignore from ._models import CNTKsettings # type: ignore from ._models import Caffe2Settings # type: ignore from ._models import CaffeSettings # type: ignore from ._models import ChainerSettings # type: ignore from ._models import CloudErrorBody # type: ignore from ._models import Cluster # type: ignore from ._models import ClusterCreateParameters # type: ignore from ._models import ClusterListResult # type: ignore from ._models import ClusterUpdateParameters # type: ignore from ._models import ClustersListByWorkspaceOptions # type: ignore from ._models import ContainerSettings # type: ignore from ._models import CustomMpiSettings # type: ignore from ._models import CustomToolkitSettings # type: ignore from ._models import DataDisks # type: ignore from ._models import EnvironmentVariable # type: ignore from ._models import EnvironmentVariableWithSecretValue # type: ignore from ._models import Experiment # type: ignore from ._models import ExperimentListResult # type: ignore from ._models import ExperimentsListByWorkspaceOptions # type: ignore from ._models import File # type: ignore from ._models import FileListResult # type: ignore from ._models import FileServer # type: ignore from ._models import FileServerCreateParameters # type: ignore from ._models import FileServerListResult # type: ignore from ._models import FileServerReference # type: ignore from ._models import FileServersListByWorkspaceOptions # type: ignore from ._models import HorovodSettings # type: ignore from ._models import ImageReference # type: ignore from ._models import ImageSourceRegistry # type: ignore from ._models import InputDirectory # type: ignore from ._models import Job # type: ignore from ._models import JobBasePropertiesConstraints # type: ignore from ._models import JobCreateParameters # type: ignore from ._models import JobListResult # type: ignore from ._models import JobPreparation # type: ignore from ._models import JobPropertiesConstraints # type: ignore from ._models import JobPropertiesExecutionInfo # type: ignore from ._models import JobsListByExperimentOptions # type: ignore from ._models import JobsListOutputFilesOptions # type: ignore from ._models import KeyVaultSecretReference # type: ignore from ._models import ListUsagesResult # type: ignore from ._models import ManualScaleSettings # type: ignore from ._models import MountSettings # type: ignore from ._models import MountVolumes # type: ignore from ._models import NameValuePair # type: ignore from ._models import NodeSetup # type: ignore from ._models import NodeStateCounts # type: ignore from ._models import Operation # type: ignore from ._models import OperationDisplay # type: ignore from ._models import OperationListResult # type: ignore from ._models import OutputDirectory # type: ignore from ._models import PerformanceCountersSettings # type: ignore from ._models import PrivateRegistryCredentials # type: ignore from ._models import ProxyResource # type: ignore from ._models import PyTorchSettings # type: ignore from ._models import RemoteLoginInformation # type: ignore from ._models import RemoteLoginInformationListResult # type: ignore from ._models import Resource # type: ignore from ._models import ResourceId # type: ignore from ._models import ScaleSettings # type: ignore from ._models import SetupTask # type: ignore from ._models import SshConfiguration # type: ignore from ._models import TensorFlowSettings # type: ignore from ._models import UnmanagedFileSystemReference # type: ignore from ._models import Usage # type: ignore from ._models import UsageName # type: ignore from ._models import UserAccountSettings # type: ignore from ._models import VirtualMachineConfiguration # type: ignore from ._models import Workspace # type: ignore from ._models import WorkspaceCreateParameters # type: ignore from ._models import WorkspaceListResult # type: ignore from ._models import WorkspaceUpdateParameters # type: ignore from ._models import WorkspacesListByResourceGroupOptions # type: ignore from ._models import WorkspacesListOptions # type: ignore from ._batch_ai_enums import ( AllocationState, CachingType, DeallocationOption, ExecutionState, FileServerProvisioningState, FileType, JobPriority, ProvisioningState, StorageAccountType, ToolType, UsageUnit, VmPriority, ) __all__ = [ 'AppInsightsReference', 'AutoScaleSettings', 'AzureBlobFileSystemReference', 'AzureFileShareReference', 'AzureStorageCredentialsInfo', 'BatchAIError', 'CNTKsettings', 'Caffe2Settings', 'CaffeSettings', 'ChainerSettings', 'CloudErrorBody', 'Cluster', 'ClusterCreateParameters', 'ClusterListResult', 'ClusterUpdateParameters', 'ClustersListByWorkspaceOptions', 'ContainerSettings', 'CustomMpiSettings', 'CustomToolkitSettings', 'DataDisks', 'EnvironmentVariable', 'EnvironmentVariableWithSecretValue', 'Experiment', 'ExperimentListResult', 'ExperimentsListByWorkspaceOptions', 'File', 'FileListResult', 'FileServer', 'FileServerCreateParameters', 'FileServerListResult', 'FileServerReference', 'FileServersListByWorkspaceOptions', 'HorovodSettings', 'ImageReference', 'ImageSourceRegistry', 'InputDirectory', 'Job', 'JobBasePropertiesConstraints', 'JobCreateParameters', 'JobListResult', 'JobPreparation', 'JobPropertiesConstraints', 'JobPropertiesExecutionInfo', 'JobsListByExperimentOptions', 'JobsListOutputFilesOptions', 'KeyVaultSecretReference', 'ListUsagesResult', 'ManualScaleSettings', 'MountSettings', 'MountVolumes', 'NameValuePair', 'NodeSetup', 'NodeStateCounts', 'Operation', 'OperationDisplay', 'OperationListResult', 'OutputDirectory', 'PerformanceCountersSettings', 'PrivateRegistryCredentials', 'ProxyResource', 'PyTorchSettings', 'RemoteLoginInformation', 'RemoteLoginInformationListResult', 'Resource', 'ResourceId', 'ScaleSettings', 'SetupTask', 'SshConfiguration', 'TensorFlowSettings', 'UnmanagedFileSystemReference', 'Usage', 'UsageName', 'UserAccountSettings', 'VirtualMachineConfiguration', 'Workspace', 'WorkspaceCreateParameters', 'WorkspaceListResult', 'WorkspaceUpdateParameters', 'WorkspacesListByResourceGroupOptions', 'WorkspacesListOptions', 'AllocationState', 'CachingType', 'DeallocationOption', 'ExecutionState', 'FileServerProvisioningState', 'FileType', 'JobPriority', 'ProvisioningState', 'StorageAccountType', 'ToolType', 'UsageUnit', 'VmPriority', ]
azure-mgmt-batchai
/azure-mgmt-batchai-7.0.0b1.zip/azure-mgmt-batchai-7.0.0b1/azure/mgmt/batchai/models/__init__.py
__init__.py
try: from ._models_py3 import AppInsightsReference from ._models_py3 import AutoScaleSettings from ._models_py3 import AzureBlobFileSystemReference from ._models_py3 import AzureFileShareReference from ._models_py3 import AzureStorageCredentialsInfo from ._models_py3 import BatchAIError from ._models_py3 import CNTKsettings from ._models_py3 import Caffe2Settings from ._models_py3 import CaffeSettings from ._models_py3 import ChainerSettings from ._models_py3 import CloudErrorBody from ._models_py3 import Cluster from ._models_py3 import ClusterCreateParameters from ._models_py3 import ClusterListResult from ._models_py3 import ClusterUpdateParameters from ._models_py3 import ClustersListByWorkspaceOptions from ._models_py3 import ContainerSettings from ._models_py3 import CustomMpiSettings from ._models_py3 import CustomToolkitSettings from ._models_py3 import DataDisks from ._models_py3 import EnvironmentVariable from ._models_py3 import EnvironmentVariableWithSecretValue from ._models_py3 import Experiment from ._models_py3 import ExperimentListResult from ._models_py3 import ExperimentsListByWorkspaceOptions from ._models_py3 import File from ._models_py3 import FileListResult from ._models_py3 import FileServer from ._models_py3 import FileServerCreateParameters from ._models_py3 import FileServerListResult from ._models_py3 import FileServerReference from ._models_py3 import FileServersListByWorkspaceOptions from ._models_py3 import HorovodSettings from ._models_py3 import ImageReference from ._models_py3 import ImageSourceRegistry from ._models_py3 import InputDirectory from ._models_py3 import Job from ._models_py3 import JobBasePropertiesConstraints from ._models_py3 import JobCreateParameters from ._models_py3 import JobListResult from ._models_py3 import JobPreparation from ._models_py3 import JobPropertiesConstraints from ._models_py3 import JobPropertiesExecutionInfo from ._models_py3 import JobsListByExperimentOptions from ._models_py3 import JobsListOutputFilesOptions from ._models_py3 import KeyVaultSecretReference from ._models_py3 import ListUsagesResult from ._models_py3 import ManualScaleSettings from ._models_py3 import MountSettings from ._models_py3 import MountVolumes from ._models_py3 import NameValuePair from ._models_py3 import NodeSetup from ._models_py3 import NodeStateCounts from ._models_py3 import Operation from ._models_py3 import OperationDisplay from ._models_py3 import OperationListResult from ._models_py3 import OutputDirectory from ._models_py3 import PerformanceCountersSettings from ._models_py3 import PrivateRegistryCredentials from ._models_py3 import ProxyResource from ._models_py3 import PyTorchSettings from ._models_py3 import RemoteLoginInformation from ._models_py3 import RemoteLoginInformationListResult from ._models_py3 import Resource from ._models_py3 import ResourceId from ._models_py3 import ScaleSettings from ._models_py3 import SetupTask from ._models_py3 import SshConfiguration from ._models_py3 import TensorFlowSettings from ._models_py3 import UnmanagedFileSystemReference from ._models_py3 import Usage from ._models_py3 import UsageName from ._models_py3 import UserAccountSettings from ._models_py3 import VirtualMachineConfiguration from ._models_py3 import Workspace from ._models_py3 import WorkspaceCreateParameters from ._models_py3 import WorkspaceListResult from ._models_py3 import WorkspaceUpdateParameters from ._models_py3 import WorkspacesListByResourceGroupOptions from ._models_py3 import WorkspacesListOptions except (SyntaxError, ImportError): from ._models import AppInsightsReference # type: ignore from ._models import AutoScaleSettings # type: ignore from ._models import AzureBlobFileSystemReference # type: ignore from ._models import AzureFileShareReference # type: ignore from ._models import AzureStorageCredentialsInfo # type: ignore from ._models import BatchAIError # type: ignore from ._models import CNTKsettings # type: ignore from ._models import Caffe2Settings # type: ignore from ._models import CaffeSettings # type: ignore from ._models import ChainerSettings # type: ignore from ._models import CloudErrorBody # type: ignore from ._models import Cluster # type: ignore from ._models import ClusterCreateParameters # type: ignore from ._models import ClusterListResult # type: ignore from ._models import ClusterUpdateParameters # type: ignore from ._models import ClustersListByWorkspaceOptions # type: ignore from ._models import ContainerSettings # type: ignore from ._models import CustomMpiSettings # type: ignore from ._models import CustomToolkitSettings # type: ignore from ._models import DataDisks # type: ignore from ._models import EnvironmentVariable # type: ignore from ._models import EnvironmentVariableWithSecretValue # type: ignore from ._models import Experiment # type: ignore from ._models import ExperimentListResult # type: ignore from ._models import ExperimentsListByWorkspaceOptions # type: ignore from ._models import File # type: ignore from ._models import FileListResult # type: ignore from ._models import FileServer # type: ignore from ._models import FileServerCreateParameters # type: ignore from ._models import FileServerListResult # type: ignore from ._models import FileServerReference # type: ignore from ._models import FileServersListByWorkspaceOptions # type: ignore from ._models import HorovodSettings # type: ignore from ._models import ImageReference # type: ignore from ._models import ImageSourceRegistry # type: ignore from ._models import InputDirectory # type: ignore from ._models import Job # type: ignore from ._models import JobBasePropertiesConstraints # type: ignore from ._models import JobCreateParameters # type: ignore from ._models import JobListResult # type: ignore from ._models import JobPreparation # type: ignore from ._models import JobPropertiesConstraints # type: ignore from ._models import JobPropertiesExecutionInfo # type: ignore from ._models import JobsListByExperimentOptions # type: ignore from ._models import JobsListOutputFilesOptions # type: ignore from ._models import KeyVaultSecretReference # type: ignore from ._models import ListUsagesResult # type: ignore from ._models import ManualScaleSettings # type: ignore from ._models import MountSettings # type: ignore from ._models import MountVolumes # type: ignore from ._models import NameValuePair # type: ignore from ._models import NodeSetup # type: ignore from ._models import NodeStateCounts # type: ignore from ._models import Operation # type: ignore from ._models import OperationDisplay # type: ignore from ._models import OperationListResult # type: ignore from ._models import OutputDirectory # type: ignore from ._models import PerformanceCountersSettings # type: ignore from ._models import PrivateRegistryCredentials # type: ignore from ._models import ProxyResource # type: ignore from ._models import PyTorchSettings # type: ignore from ._models import RemoteLoginInformation # type: ignore from ._models import RemoteLoginInformationListResult # type: ignore from ._models import Resource # type: ignore from ._models import ResourceId # type: ignore from ._models import ScaleSettings # type: ignore from ._models import SetupTask # type: ignore from ._models import SshConfiguration # type: ignore from ._models import TensorFlowSettings # type: ignore from ._models import UnmanagedFileSystemReference # type: ignore from ._models import Usage # type: ignore from ._models import UsageName # type: ignore from ._models import UserAccountSettings # type: ignore from ._models import VirtualMachineConfiguration # type: ignore from ._models import Workspace # type: ignore from ._models import WorkspaceCreateParameters # type: ignore from ._models import WorkspaceListResult # type: ignore from ._models import WorkspaceUpdateParameters # type: ignore from ._models import WorkspacesListByResourceGroupOptions # type: ignore from ._models import WorkspacesListOptions # type: ignore from ._batch_ai_enums import ( AllocationState, CachingType, DeallocationOption, ExecutionState, FileServerProvisioningState, FileType, JobPriority, ProvisioningState, StorageAccountType, ToolType, UsageUnit, VmPriority, ) __all__ = [ 'AppInsightsReference', 'AutoScaleSettings', 'AzureBlobFileSystemReference', 'AzureFileShareReference', 'AzureStorageCredentialsInfo', 'BatchAIError', 'CNTKsettings', 'Caffe2Settings', 'CaffeSettings', 'ChainerSettings', 'CloudErrorBody', 'Cluster', 'ClusterCreateParameters', 'ClusterListResult', 'ClusterUpdateParameters', 'ClustersListByWorkspaceOptions', 'ContainerSettings', 'CustomMpiSettings', 'CustomToolkitSettings', 'DataDisks', 'EnvironmentVariable', 'EnvironmentVariableWithSecretValue', 'Experiment', 'ExperimentListResult', 'ExperimentsListByWorkspaceOptions', 'File', 'FileListResult', 'FileServer', 'FileServerCreateParameters', 'FileServerListResult', 'FileServerReference', 'FileServersListByWorkspaceOptions', 'HorovodSettings', 'ImageReference', 'ImageSourceRegistry', 'InputDirectory', 'Job', 'JobBasePropertiesConstraints', 'JobCreateParameters', 'JobListResult', 'JobPreparation', 'JobPropertiesConstraints', 'JobPropertiesExecutionInfo', 'JobsListByExperimentOptions', 'JobsListOutputFilesOptions', 'KeyVaultSecretReference', 'ListUsagesResult', 'ManualScaleSettings', 'MountSettings', 'MountVolumes', 'NameValuePair', 'NodeSetup', 'NodeStateCounts', 'Operation', 'OperationDisplay', 'OperationListResult', 'OutputDirectory', 'PerformanceCountersSettings', 'PrivateRegistryCredentials', 'ProxyResource', 'PyTorchSettings', 'RemoteLoginInformation', 'RemoteLoginInformationListResult', 'Resource', 'ResourceId', 'ScaleSettings', 'SetupTask', 'SshConfiguration', 'TensorFlowSettings', 'UnmanagedFileSystemReference', 'Usage', 'UsageName', 'UserAccountSettings', 'VirtualMachineConfiguration', 'Workspace', 'WorkspaceCreateParameters', 'WorkspaceListResult', 'WorkspaceUpdateParameters', 'WorkspacesListByResourceGroupOptions', 'WorkspacesListOptions', 'AllocationState', 'CachingType', 'DeallocationOption', 'ExecutionState', 'FileServerProvisioningState', 'FileType', 'JobPriority', 'ProvisioningState', 'StorageAccountType', 'ToolType', 'UsageUnit', 'VmPriority', ]
0.482185
0.070528
from copy import deepcopy from typing import Any, TYPE_CHECKING from azure.core.rest import HttpRequest, HttpResponse from azure.mgmt.core import ARMPipelineClient from . import models from ._configuration import BillingManagementClientConfiguration from ._serialization import Deserializer, Serializer from .operations import ( AddressOperations, AgreementsOperations, AvailableBalancesOperations, BillingAccountsOperations, BillingPeriodsOperations, BillingPermissionsOperations, BillingProfilesOperations, BillingPropertyOperations, BillingRoleAssignmentsOperations, BillingRoleDefinitionsOperations, BillingSubscriptionsOperations, CustomersOperations, EnrollmentAccountsOperations, InstructionsOperations, InvoiceSectionsOperations, InvoicesOperations, Operations, PoliciesOperations, ProductsOperations, ReservationsOperations, TransactionsOperations, ) if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials import TokenCredential class BillingManagementClient: # pylint: disable=client-accepts-api-version-keyword,too-many-instance-attributes """Billing client provides access to billing resources for Azure subscriptions. :ivar billing_accounts: BillingAccountsOperations operations :vartype billing_accounts: azure.mgmt.billing.operations.BillingAccountsOperations :ivar address: AddressOperations operations :vartype address: azure.mgmt.billing.operations.AddressOperations :ivar available_balances: AvailableBalancesOperations operations :vartype available_balances: azure.mgmt.billing.operations.AvailableBalancesOperations :ivar instructions: InstructionsOperations operations :vartype instructions: azure.mgmt.billing.operations.InstructionsOperations :ivar billing_profiles: BillingProfilesOperations operations :vartype billing_profiles: azure.mgmt.billing.operations.BillingProfilesOperations :ivar customers: CustomersOperations operations :vartype customers: azure.mgmt.billing.operations.CustomersOperations :ivar invoice_sections: InvoiceSectionsOperations operations :vartype invoice_sections: azure.mgmt.billing.operations.InvoiceSectionsOperations :ivar billing_permissions: BillingPermissionsOperations operations :vartype billing_permissions: azure.mgmt.billing.operations.BillingPermissionsOperations :ivar billing_subscriptions: BillingSubscriptionsOperations operations :vartype billing_subscriptions: azure.mgmt.billing.operations.BillingSubscriptionsOperations :ivar products: ProductsOperations operations :vartype products: azure.mgmt.billing.operations.ProductsOperations :ivar invoices: InvoicesOperations operations :vartype invoices: azure.mgmt.billing.operations.InvoicesOperations :ivar transactions: TransactionsOperations operations :vartype transactions: azure.mgmt.billing.operations.TransactionsOperations :ivar policies: PoliciesOperations operations :vartype policies: azure.mgmt.billing.operations.PoliciesOperations :ivar billing_property: BillingPropertyOperations operations :vartype billing_property: azure.mgmt.billing.operations.BillingPropertyOperations :ivar billing_role_definitions: BillingRoleDefinitionsOperations operations :vartype billing_role_definitions: azure.mgmt.billing.operations.BillingRoleDefinitionsOperations :ivar billing_role_assignments: BillingRoleAssignmentsOperations operations :vartype billing_role_assignments: azure.mgmt.billing.operations.BillingRoleAssignmentsOperations :ivar agreements: AgreementsOperations operations :vartype agreements: azure.mgmt.billing.operations.AgreementsOperations :ivar reservations: ReservationsOperations operations :vartype reservations: azure.mgmt.billing.operations.ReservationsOperations :ivar enrollment_accounts: EnrollmentAccountsOperations operations :vartype enrollment_accounts: azure.mgmt.billing.operations.EnrollmentAccountsOperations :ivar billing_periods: BillingPeriodsOperations operations :vartype billing_periods: azure.mgmt.billing.operations.BillingPeriodsOperations :ivar operations: Operations operations :vartype operations: azure.mgmt.billing.operations.Operations :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials.TokenCredential :param subscription_id: The ID that uniquely identifies an Azure subscription. Required. :type subscription_id: str :param base_url: Service URL. Default value is "https://management.azure.com". :type base_url: str :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. """ def __init__( self, credential: "TokenCredential", subscription_id: str, base_url: str = "https://management.azure.com", **kwargs: Any ) -> None: self._config = BillingManagementClientConfiguration( credential=credential, subscription_id=subscription_id, **kwargs ) self._client = ARMPipelineClient(base_url=base_url, config=self._config, **kwargs) client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} self._serialize = Serializer(client_models) self._deserialize = Deserializer(client_models) self._serialize.client_side_validation = False self.billing_accounts = BillingAccountsOperations( self._client, self._config, self._serialize, self._deserialize ) self.address = AddressOperations(self._client, self._config, self._serialize, self._deserialize) self.available_balances = AvailableBalancesOperations( self._client, self._config, self._serialize, self._deserialize ) self.instructions = InstructionsOperations(self._client, self._config, self._serialize, self._deserialize) self.billing_profiles = BillingProfilesOperations( self._client, self._config, self._serialize, self._deserialize ) self.customers = CustomersOperations(self._client, self._config, self._serialize, self._deserialize) self.invoice_sections = InvoiceSectionsOperations( self._client, self._config, self._serialize, self._deserialize ) self.billing_permissions = BillingPermissionsOperations( self._client, self._config, self._serialize, self._deserialize ) self.billing_subscriptions = BillingSubscriptionsOperations( self._client, self._config, self._serialize, self._deserialize ) self.products = ProductsOperations(self._client, self._config, self._serialize, self._deserialize) self.invoices = InvoicesOperations(self._client, self._config, self._serialize, self._deserialize) self.transactions = TransactionsOperations(self._client, self._config, self._serialize, self._deserialize) self.policies = PoliciesOperations(self._client, self._config, self._serialize, self._deserialize) self.billing_property = BillingPropertyOperations( self._client, self._config, self._serialize, self._deserialize ) self.billing_role_definitions = BillingRoleDefinitionsOperations( self._client, self._config, self._serialize, self._deserialize ) self.billing_role_assignments = BillingRoleAssignmentsOperations( self._client, self._config, self._serialize, self._deserialize ) self.agreements = AgreementsOperations(self._client, self._config, self._serialize, self._deserialize) self.reservations = ReservationsOperations(self._client, self._config, self._serialize, self._deserialize) self.enrollment_accounts = EnrollmentAccountsOperations( self._client, self._config, self._serialize, self._deserialize ) self.billing_periods = BillingPeriodsOperations(self._client, self._config, self._serialize, self._deserialize) self.operations = Operations(self._client, self._config, self._serialize, self._deserialize) def _send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: """Runs the network request through the client's chained policies. >>> from azure.core.rest import HttpRequest >>> request = HttpRequest("GET", "https://www.example.org/") <HttpRequest [GET], url: 'https://www.example.org/'> >>> response = client._send_request(request) <HttpResponse: 200 OK> For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request :param request: The network request you want to make. Required. :type request: ~azure.core.rest.HttpRequest :keyword bool stream: Whether the response payload will be streamed. Defaults to False. :return: The response of your network call. Does not do error handling on your response. :rtype: ~azure.core.rest.HttpResponse """ request_copy = deepcopy(request) request_copy.url = self._client.format_url(request_copy.url) return self._client.send_request(request_copy, **kwargs) def close(self): # type: () -> None self._client.close() def __enter__(self): # type: () -> BillingManagementClient self._client.__enter__() return self def __exit__(self, *exc_details): # type: (Any) -> None self._client.__exit__(*exc_details)
azure-mgmt-billing
/azure_mgmt_billing-6.1.0b1-py3-none-any.whl/azure/mgmt/billing/_billing_management_client.py
_billing_management_client.py
from copy import deepcopy from typing import Any, TYPE_CHECKING from azure.core.rest import HttpRequest, HttpResponse from azure.mgmt.core import ARMPipelineClient from . import models from ._configuration import BillingManagementClientConfiguration from ._serialization import Deserializer, Serializer from .operations import ( AddressOperations, AgreementsOperations, AvailableBalancesOperations, BillingAccountsOperations, BillingPeriodsOperations, BillingPermissionsOperations, BillingProfilesOperations, BillingPropertyOperations, BillingRoleAssignmentsOperations, BillingRoleDefinitionsOperations, BillingSubscriptionsOperations, CustomersOperations, EnrollmentAccountsOperations, InstructionsOperations, InvoiceSectionsOperations, InvoicesOperations, Operations, PoliciesOperations, ProductsOperations, ReservationsOperations, TransactionsOperations, ) if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials import TokenCredential class BillingManagementClient: # pylint: disable=client-accepts-api-version-keyword,too-many-instance-attributes """Billing client provides access to billing resources for Azure subscriptions. :ivar billing_accounts: BillingAccountsOperations operations :vartype billing_accounts: azure.mgmt.billing.operations.BillingAccountsOperations :ivar address: AddressOperations operations :vartype address: azure.mgmt.billing.operations.AddressOperations :ivar available_balances: AvailableBalancesOperations operations :vartype available_balances: azure.mgmt.billing.operations.AvailableBalancesOperations :ivar instructions: InstructionsOperations operations :vartype instructions: azure.mgmt.billing.operations.InstructionsOperations :ivar billing_profiles: BillingProfilesOperations operations :vartype billing_profiles: azure.mgmt.billing.operations.BillingProfilesOperations :ivar customers: CustomersOperations operations :vartype customers: azure.mgmt.billing.operations.CustomersOperations :ivar invoice_sections: InvoiceSectionsOperations operations :vartype invoice_sections: azure.mgmt.billing.operations.InvoiceSectionsOperations :ivar billing_permissions: BillingPermissionsOperations operations :vartype billing_permissions: azure.mgmt.billing.operations.BillingPermissionsOperations :ivar billing_subscriptions: BillingSubscriptionsOperations operations :vartype billing_subscriptions: azure.mgmt.billing.operations.BillingSubscriptionsOperations :ivar products: ProductsOperations operations :vartype products: azure.mgmt.billing.operations.ProductsOperations :ivar invoices: InvoicesOperations operations :vartype invoices: azure.mgmt.billing.operations.InvoicesOperations :ivar transactions: TransactionsOperations operations :vartype transactions: azure.mgmt.billing.operations.TransactionsOperations :ivar policies: PoliciesOperations operations :vartype policies: azure.mgmt.billing.operations.PoliciesOperations :ivar billing_property: BillingPropertyOperations operations :vartype billing_property: azure.mgmt.billing.operations.BillingPropertyOperations :ivar billing_role_definitions: BillingRoleDefinitionsOperations operations :vartype billing_role_definitions: azure.mgmt.billing.operations.BillingRoleDefinitionsOperations :ivar billing_role_assignments: BillingRoleAssignmentsOperations operations :vartype billing_role_assignments: azure.mgmt.billing.operations.BillingRoleAssignmentsOperations :ivar agreements: AgreementsOperations operations :vartype agreements: azure.mgmt.billing.operations.AgreementsOperations :ivar reservations: ReservationsOperations operations :vartype reservations: azure.mgmt.billing.operations.ReservationsOperations :ivar enrollment_accounts: EnrollmentAccountsOperations operations :vartype enrollment_accounts: azure.mgmt.billing.operations.EnrollmentAccountsOperations :ivar billing_periods: BillingPeriodsOperations operations :vartype billing_periods: azure.mgmt.billing.operations.BillingPeriodsOperations :ivar operations: Operations operations :vartype operations: azure.mgmt.billing.operations.Operations :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials.TokenCredential :param subscription_id: The ID that uniquely identifies an Azure subscription. Required. :type subscription_id: str :param base_url: Service URL. Default value is "https://management.azure.com". :type base_url: str :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. """ def __init__( self, credential: "TokenCredential", subscription_id: str, base_url: str = "https://management.azure.com", **kwargs: Any ) -> None: self._config = BillingManagementClientConfiguration( credential=credential, subscription_id=subscription_id, **kwargs ) self._client = ARMPipelineClient(base_url=base_url, config=self._config, **kwargs) client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} self._serialize = Serializer(client_models) self._deserialize = Deserializer(client_models) self._serialize.client_side_validation = False self.billing_accounts = BillingAccountsOperations( self._client, self._config, self._serialize, self._deserialize ) self.address = AddressOperations(self._client, self._config, self._serialize, self._deserialize) self.available_balances = AvailableBalancesOperations( self._client, self._config, self._serialize, self._deserialize ) self.instructions = InstructionsOperations(self._client, self._config, self._serialize, self._deserialize) self.billing_profiles = BillingProfilesOperations( self._client, self._config, self._serialize, self._deserialize ) self.customers = CustomersOperations(self._client, self._config, self._serialize, self._deserialize) self.invoice_sections = InvoiceSectionsOperations( self._client, self._config, self._serialize, self._deserialize ) self.billing_permissions = BillingPermissionsOperations( self._client, self._config, self._serialize, self._deserialize ) self.billing_subscriptions = BillingSubscriptionsOperations( self._client, self._config, self._serialize, self._deserialize ) self.products = ProductsOperations(self._client, self._config, self._serialize, self._deserialize) self.invoices = InvoicesOperations(self._client, self._config, self._serialize, self._deserialize) self.transactions = TransactionsOperations(self._client, self._config, self._serialize, self._deserialize) self.policies = PoliciesOperations(self._client, self._config, self._serialize, self._deserialize) self.billing_property = BillingPropertyOperations( self._client, self._config, self._serialize, self._deserialize ) self.billing_role_definitions = BillingRoleDefinitionsOperations( self._client, self._config, self._serialize, self._deserialize ) self.billing_role_assignments = BillingRoleAssignmentsOperations( self._client, self._config, self._serialize, self._deserialize ) self.agreements = AgreementsOperations(self._client, self._config, self._serialize, self._deserialize) self.reservations = ReservationsOperations(self._client, self._config, self._serialize, self._deserialize) self.enrollment_accounts = EnrollmentAccountsOperations( self._client, self._config, self._serialize, self._deserialize ) self.billing_periods = BillingPeriodsOperations(self._client, self._config, self._serialize, self._deserialize) self.operations = Operations(self._client, self._config, self._serialize, self._deserialize) def _send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: """Runs the network request through the client's chained policies. >>> from azure.core.rest import HttpRequest >>> request = HttpRequest("GET", "https://www.example.org/") <HttpRequest [GET], url: 'https://www.example.org/'> >>> response = client._send_request(request) <HttpResponse: 200 OK> For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request :param request: The network request you want to make. Required. :type request: ~azure.core.rest.HttpRequest :keyword bool stream: Whether the response payload will be streamed. Defaults to False. :return: The response of your network call. Does not do error handling on your response. :rtype: ~azure.core.rest.HttpResponse """ request_copy = deepcopy(request) request_copy.url = self._client.format_url(request_copy.url) return self._client.send_request(request_copy, **kwargs) def close(self): # type: () -> None self._client.close() def __enter__(self): # type: () -> BillingManagementClient self._client.__enter__() return self def __exit__(self, *exc_details): # type: (Any) -> None self._client.__exit__(*exc_details)
0.813238
0.118819
from typing import Any, TYPE_CHECKING from azure.core.configuration import Configuration from azure.core.pipeline import policies from azure.mgmt.core.policies import ARMChallengeAuthenticationPolicy, ARMHttpLoggingPolicy from ._version import VERSION if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials import TokenCredential class BillingManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes """Configuration for BillingManagementClient. Note that all parameters used to create this instance are saved as instance attributes. :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials.TokenCredential :param subscription_id: The ID that uniquely identifies an Azure subscription. Required. :type subscription_id: str """ def __init__(self, credential: "TokenCredential", subscription_id: str, **kwargs: Any) -> None: super(BillingManagementClientConfiguration, self).__init__(**kwargs) if credential is None: raise ValueError("Parameter 'credential' must not be None.") if subscription_id is None: raise ValueError("Parameter 'subscription_id' must not be None.") self.credential = credential self.subscription_id = subscription_id self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) kwargs.setdefault("sdk_moniker", "mgmt-billing/{}".format(VERSION)) self._configure(**kwargs) def _configure( self, **kwargs # type: Any ): # type: (...) -> None self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) self.retry_policy = kwargs.get("retry_policy") or policies.RetryPolicy(**kwargs) self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) self.redirect_policy = kwargs.get("redirect_policy") or policies.RedirectPolicy(**kwargs) self.authentication_policy = kwargs.get("authentication_policy") if self.credential and not self.authentication_policy: self.authentication_policy = ARMChallengeAuthenticationPolicy( self.credential, *self.credential_scopes, **kwargs )
azure-mgmt-billing
/azure_mgmt_billing-6.1.0b1-py3-none-any.whl/azure/mgmt/billing/_configuration.py
_configuration.py
from typing import Any, TYPE_CHECKING from azure.core.configuration import Configuration from azure.core.pipeline import policies from azure.mgmt.core.policies import ARMChallengeAuthenticationPolicy, ARMHttpLoggingPolicy from ._version import VERSION if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials import TokenCredential class BillingManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes """Configuration for BillingManagementClient. Note that all parameters used to create this instance are saved as instance attributes. :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials.TokenCredential :param subscription_id: The ID that uniquely identifies an Azure subscription. Required. :type subscription_id: str """ def __init__(self, credential: "TokenCredential", subscription_id: str, **kwargs: Any) -> None: super(BillingManagementClientConfiguration, self).__init__(**kwargs) if credential is None: raise ValueError("Parameter 'credential' must not be None.") if subscription_id is None: raise ValueError("Parameter 'subscription_id' must not be None.") self.credential = credential self.subscription_id = subscription_id self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) kwargs.setdefault("sdk_moniker", "mgmt-billing/{}".format(VERSION)) self._configure(**kwargs) def _configure( self, **kwargs # type: Any ): # type: (...) -> None self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) self.retry_policy = kwargs.get("retry_policy") or policies.RetryPolicy(**kwargs) self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) self.redirect_policy = kwargs.get("redirect_policy") or policies.RedirectPolicy(**kwargs) self.authentication_policy = kwargs.get("authentication_policy") if self.credential and not self.authentication_policy: self.authentication_policy = ARMChallengeAuthenticationPolicy( self.credential, *self.credential_scopes, **kwargs )
0.814643
0.076546
import sys from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, overload from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, map_error, ) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models from .._serialization import Serializer from .._vendor import _convert_request, _format_url_section if sys.version_info >= (3, 8): from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports else: from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False def build_list_by_billing_profile_request( billing_account_name: str, billing_profile_name: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/instructions", ) # pylint: disable=line-too-long path_format_arguments = { "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), "billingProfileName": _SERIALIZER.url("billing_profile_name", billing_profile_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_get_request( billing_account_name: str, billing_profile_name: str, instruction_name: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/instructions/{instructionName}", ) # pylint: disable=line-too-long path_format_arguments = { "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), "billingProfileName": _SERIALIZER.url("billing_profile_name", billing_profile_name, "str"), "instructionName": _SERIALIZER.url("instruction_name", instruction_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_put_request( billing_account_name: str, billing_profile_name: str, instruction_name: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/instructions/{instructionName}", ) # pylint: disable=line-too-long path_format_arguments = { "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), "billingProfileName": _SERIALIZER.url("billing_profile_name", billing_profile_name, "str"), "instructionName": _SERIALIZER.url("instruction_name", instruction_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers if content_type is not None: _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) class InstructionsOperations: """ .. warning:: **DO NOT** instantiate this class directly. Instead, you should access the following operations through :class:`~azure.mgmt.billing.BillingManagementClient`'s :attr:`instructions` attribute. """ models = _models def __init__(self, *args, **kwargs): input_args = list(args) self._client = input_args.pop(0) if input_args else kwargs.pop("client") self._config = input_args.pop(0) if input_args else kwargs.pop("config") self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace def list_by_billing_profile( self, billing_account_name: str, billing_profile_name: str, **kwargs: Any ) -> Iterable["_models.Instruction"]: """Lists the instructions by billing profile id. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either Instruction or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billing.models.Instruction] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.InstructionListResult] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_by_billing_profile_request( billing_account_name=billing_account_name, billing_profile_name=billing_profile_name, api_version=api_version, template_url=self.list_by_billing_profile.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore else: request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request def extract_data(pipeline_response): deserialized = self._deserialize("InstructionListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return ItemPaged(get_next, extract_data) list_by_billing_profile.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/instructions"} # type: ignore @distributed_trace def get( self, billing_account_name: str, billing_profile_name: str, instruction_name: str, **kwargs: Any ) -> _models.Instruction: """Get the instruction by name. These are custom billing instructions and are only applicable for certain customers. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :param instruction_name: Instruction Name. Required. :type instruction_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Instruction or the result of cls(response) :rtype: ~azure.mgmt.billing.models.Instruction :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.Instruction] request = build_get_request( billing_account_name=billing_account_name, billing_profile_name=billing_profile_name, instruction_name=instruction_name, api_version=api_version, template_url=self.get.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize("Instruction", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/instructions/{instructionName}"} # type: ignore @overload def put( self, billing_account_name: str, billing_profile_name: str, instruction_name: str, parameters: _models.Instruction, *, content_type: str = "application/json", **kwargs: Any ) -> _models.Instruction: """Creates or updates an instruction. These are custom billing instructions and are only applicable for certain customers. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :param instruction_name: Instruction Name. Required. :type instruction_name: str :param parameters: The new instruction. Required. :type parameters: ~azure.mgmt.billing.models.Instruction :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Instruction or the result of cls(response) :rtype: ~azure.mgmt.billing.models.Instruction :raises ~azure.core.exceptions.HttpResponseError: """ @overload def put( self, billing_account_name: str, billing_profile_name: str, instruction_name: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any ) -> _models.Instruction: """Creates or updates an instruction. These are custom billing instructions and are only applicable for certain customers. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :param instruction_name: Instruction Name. Required. :type instruction_name: str :param parameters: The new instruction. Required. :type parameters: IO :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Instruction or the result of cls(response) :rtype: ~azure.mgmt.billing.models.Instruction :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace def put( self, billing_account_name: str, billing_profile_name: str, instruction_name: str, parameters: Union[_models.Instruction, IO], **kwargs: Any ) -> _models.Instruction: """Creates or updates an instruction. These are custom billing instructions and are only applicable for certain customers. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :param instruction_name: Instruction Name. Required. :type instruction_name: str :param parameters: The new instruction. Is either a model type or a IO type. Required. :type parameters: ~azure.mgmt.billing.models.Instruction or IO :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. Default value is None. :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Instruction or the result of cls(response) :rtype: ~azure.mgmt.billing.models.Instruction :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] cls = kwargs.pop("cls", None) # type: ClsType[_models.Instruction] content_type = content_type or "application/json" _json = None _content = None if isinstance(parameters, (IO, bytes)): _content = parameters else: _json = self._serialize.body(parameters, "Instruction") request = build_put_request( billing_account_name=billing_account_name, billing_profile_name=billing_profile_name, instruction_name=instruction_name, api_version=api_version, content_type=content_type, json=_json, content=_content, template_url=self.put.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize("Instruction", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized put.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/instructions/{instructionName}"} # type: ignore
azure-mgmt-billing
/azure_mgmt_billing-6.1.0b1-py3-none-any.whl/azure/mgmt/billing/operations/_instructions_operations.py
_instructions_operations.py
import sys from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, overload from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, map_error, ) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models from .._serialization import Serializer from .._vendor import _convert_request, _format_url_section if sys.version_info >= (3, 8): from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports else: from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False def build_list_by_billing_profile_request( billing_account_name: str, billing_profile_name: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/instructions", ) # pylint: disable=line-too-long path_format_arguments = { "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), "billingProfileName": _SERIALIZER.url("billing_profile_name", billing_profile_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_get_request( billing_account_name: str, billing_profile_name: str, instruction_name: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/instructions/{instructionName}", ) # pylint: disable=line-too-long path_format_arguments = { "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), "billingProfileName": _SERIALIZER.url("billing_profile_name", billing_profile_name, "str"), "instructionName": _SERIALIZER.url("instruction_name", instruction_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_put_request( billing_account_name: str, billing_profile_name: str, instruction_name: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/instructions/{instructionName}", ) # pylint: disable=line-too-long path_format_arguments = { "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), "billingProfileName": _SERIALIZER.url("billing_profile_name", billing_profile_name, "str"), "instructionName": _SERIALIZER.url("instruction_name", instruction_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers if content_type is not None: _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) class InstructionsOperations: """ .. warning:: **DO NOT** instantiate this class directly. Instead, you should access the following operations through :class:`~azure.mgmt.billing.BillingManagementClient`'s :attr:`instructions` attribute. """ models = _models def __init__(self, *args, **kwargs): input_args = list(args) self._client = input_args.pop(0) if input_args else kwargs.pop("client") self._config = input_args.pop(0) if input_args else kwargs.pop("config") self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace def list_by_billing_profile( self, billing_account_name: str, billing_profile_name: str, **kwargs: Any ) -> Iterable["_models.Instruction"]: """Lists the instructions by billing profile id. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either Instruction or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billing.models.Instruction] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.InstructionListResult] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_by_billing_profile_request( billing_account_name=billing_account_name, billing_profile_name=billing_profile_name, api_version=api_version, template_url=self.list_by_billing_profile.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore else: request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request def extract_data(pipeline_response): deserialized = self._deserialize("InstructionListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return ItemPaged(get_next, extract_data) list_by_billing_profile.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/instructions"} # type: ignore @distributed_trace def get( self, billing_account_name: str, billing_profile_name: str, instruction_name: str, **kwargs: Any ) -> _models.Instruction: """Get the instruction by name. These are custom billing instructions and are only applicable for certain customers. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :param instruction_name: Instruction Name. Required. :type instruction_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Instruction or the result of cls(response) :rtype: ~azure.mgmt.billing.models.Instruction :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.Instruction] request = build_get_request( billing_account_name=billing_account_name, billing_profile_name=billing_profile_name, instruction_name=instruction_name, api_version=api_version, template_url=self.get.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize("Instruction", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/instructions/{instructionName}"} # type: ignore @overload def put( self, billing_account_name: str, billing_profile_name: str, instruction_name: str, parameters: _models.Instruction, *, content_type: str = "application/json", **kwargs: Any ) -> _models.Instruction: """Creates or updates an instruction. These are custom billing instructions and are only applicable for certain customers. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :param instruction_name: Instruction Name. Required. :type instruction_name: str :param parameters: The new instruction. Required. :type parameters: ~azure.mgmt.billing.models.Instruction :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Instruction or the result of cls(response) :rtype: ~azure.mgmt.billing.models.Instruction :raises ~azure.core.exceptions.HttpResponseError: """ @overload def put( self, billing_account_name: str, billing_profile_name: str, instruction_name: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any ) -> _models.Instruction: """Creates or updates an instruction. These are custom billing instructions and are only applicable for certain customers. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :param instruction_name: Instruction Name. Required. :type instruction_name: str :param parameters: The new instruction. Required. :type parameters: IO :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Instruction or the result of cls(response) :rtype: ~azure.mgmt.billing.models.Instruction :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace def put( self, billing_account_name: str, billing_profile_name: str, instruction_name: str, parameters: Union[_models.Instruction, IO], **kwargs: Any ) -> _models.Instruction: """Creates or updates an instruction. These are custom billing instructions and are only applicable for certain customers. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :param instruction_name: Instruction Name. Required. :type instruction_name: str :param parameters: The new instruction. Is either a model type or a IO type. Required. :type parameters: ~azure.mgmt.billing.models.Instruction or IO :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. Default value is None. :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Instruction or the result of cls(response) :rtype: ~azure.mgmt.billing.models.Instruction :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] cls = kwargs.pop("cls", None) # type: ClsType[_models.Instruction] content_type = content_type or "application/json" _json = None _content = None if isinstance(parameters, (IO, bytes)): _content = parameters else: _json = self._serialize.body(parameters, "Instruction") request = build_put_request( billing_account_name=billing_account_name, billing_profile_name=billing_profile_name, instruction_name=instruction_name, api_version=api_version, content_type=content_type, json=_json, content=_content, template_url=self.put.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize("Instruction", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized put.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/instructions/{instructionName}"} # type: ignore
0.639398
0.085251
import sys from typing import Any, Callable, Dict, Iterable, Optional, TypeVar from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, map_error, ) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models from .._serialization import Serializer from .._vendor import _convert_request, _format_url_section if sys.version_info >= (3, 8): from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports else: from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False def build_list_by_customer_request(billing_account_name: str, customer_name: str, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/customers/{customerName}/billingPermissions", ) # pylint: disable=line-too-long path_format_arguments = { "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), "customerName": _SERIALIZER.url("customer_name", customer_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_list_by_billing_account_request(billing_account_name: str, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingPermissions" ) path_format_arguments = { "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_list_by_invoice_sections_request( billing_account_name: str, billing_profile_name: str, invoice_section_name: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoiceSections/{invoiceSectionName}/billingPermissions", ) # pylint: disable=line-too-long path_format_arguments = { "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), "billingProfileName": _SERIALIZER.url("billing_profile_name", billing_profile_name, "str"), "invoiceSectionName": _SERIALIZER.url("invoice_section_name", invoice_section_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_list_by_billing_profile_request( billing_account_name: str, billing_profile_name: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/billingPermissions", ) # pylint: disable=line-too-long path_format_arguments = { "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), "billingProfileName": _SERIALIZER.url("billing_profile_name", billing_profile_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) class BillingPermissionsOperations: """ .. warning:: **DO NOT** instantiate this class directly. Instead, you should access the following operations through :class:`~azure.mgmt.billing.BillingManagementClient`'s :attr:`billing_permissions` attribute. """ models = _models def __init__(self, *args, **kwargs): input_args = list(args) self._client = input_args.pop(0) if input_args else kwargs.pop("client") self._config = input_args.pop(0) if input_args else kwargs.pop("config") self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace def list_by_customer( self, billing_account_name: str, customer_name: str, **kwargs: Any ) -> Iterable["_models.BillingPermissionsProperties"]: """Lists the billing permissions the caller has for a customer. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param customer_name: The ID that uniquely identifies a customer. Required. :type customer_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either BillingPermissionsProperties or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billing.models.BillingPermissionsProperties] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingPermissionsListResult] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_by_customer_request( billing_account_name=billing_account_name, customer_name=customer_name, api_version=api_version, template_url=self.list_by_customer.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore else: request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request def extract_data(pipeline_response): deserialized = self._deserialize("BillingPermissionsListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return ItemPaged(get_next, extract_data) list_by_customer.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/customers/{customerName}/billingPermissions"} # type: ignore @distributed_trace def list_by_billing_account( self, billing_account_name: str, **kwargs: Any ) -> Iterable["_models.BillingPermissionsProperties"]: """Lists the billing permissions the caller has on a billing account. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either BillingPermissionsProperties or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billing.models.BillingPermissionsProperties] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingPermissionsListResult] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_by_billing_account_request( billing_account_name=billing_account_name, api_version=api_version, template_url=self.list_by_billing_account.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore else: request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request def extract_data(pipeline_response): deserialized = self._deserialize("BillingPermissionsListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return ItemPaged(get_next, extract_data) list_by_billing_account.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingPermissions"} # type: ignore @distributed_trace def list_by_invoice_sections( self, billing_account_name: str, billing_profile_name: str, invoice_section_name: str, **kwargs: Any ) -> Iterable["_models.BillingPermissionsProperties"]: """Lists the billing permissions the caller has on an invoice section. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :param invoice_section_name: The ID that uniquely identifies an invoice section. Required. :type invoice_section_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either BillingPermissionsProperties or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billing.models.BillingPermissionsProperties] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingPermissionsListResult] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_by_invoice_sections_request( billing_account_name=billing_account_name, billing_profile_name=billing_profile_name, invoice_section_name=invoice_section_name, api_version=api_version, template_url=self.list_by_invoice_sections.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore else: request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request def extract_data(pipeline_response): deserialized = self._deserialize("BillingPermissionsListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return ItemPaged(get_next, extract_data) list_by_invoice_sections.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoiceSections/{invoiceSectionName}/billingPermissions"} # type: ignore @distributed_trace def list_by_billing_profile( self, billing_account_name: str, billing_profile_name: str, **kwargs: Any ) -> Iterable["_models.BillingPermissionsProperties"]: """Lists the billing permissions the caller has on a billing profile. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either BillingPermissionsProperties or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billing.models.BillingPermissionsProperties] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingPermissionsListResult] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_by_billing_profile_request( billing_account_name=billing_account_name, billing_profile_name=billing_profile_name, api_version=api_version, template_url=self.list_by_billing_profile.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore else: request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request def extract_data(pipeline_response): deserialized = self._deserialize("BillingPermissionsListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return ItemPaged(get_next, extract_data) list_by_billing_profile.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/billingPermissions"} # type: ignore
azure-mgmt-billing
/azure_mgmt_billing-6.1.0b1-py3-none-any.whl/azure/mgmt/billing/operations/_billing_permissions_operations.py
_billing_permissions_operations.py
import sys from typing import Any, Callable, Dict, Iterable, Optional, TypeVar from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, map_error, ) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models from .._serialization import Serializer from .._vendor import _convert_request, _format_url_section if sys.version_info >= (3, 8): from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports else: from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False def build_list_by_customer_request(billing_account_name: str, customer_name: str, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/customers/{customerName}/billingPermissions", ) # pylint: disable=line-too-long path_format_arguments = { "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), "customerName": _SERIALIZER.url("customer_name", customer_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_list_by_billing_account_request(billing_account_name: str, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingPermissions" ) path_format_arguments = { "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_list_by_invoice_sections_request( billing_account_name: str, billing_profile_name: str, invoice_section_name: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoiceSections/{invoiceSectionName}/billingPermissions", ) # pylint: disable=line-too-long path_format_arguments = { "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), "billingProfileName": _SERIALIZER.url("billing_profile_name", billing_profile_name, "str"), "invoiceSectionName": _SERIALIZER.url("invoice_section_name", invoice_section_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_list_by_billing_profile_request( billing_account_name: str, billing_profile_name: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/billingPermissions", ) # pylint: disable=line-too-long path_format_arguments = { "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), "billingProfileName": _SERIALIZER.url("billing_profile_name", billing_profile_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) class BillingPermissionsOperations: """ .. warning:: **DO NOT** instantiate this class directly. Instead, you should access the following operations through :class:`~azure.mgmt.billing.BillingManagementClient`'s :attr:`billing_permissions` attribute. """ models = _models def __init__(self, *args, **kwargs): input_args = list(args) self._client = input_args.pop(0) if input_args else kwargs.pop("client") self._config = input_args.pop(0) if input_args else kwargs.pop("config") self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace def list_by_customer( self, billing_account_name: str, customer_name: str, **kwargs: Any ) -> Iterable["_models.BillingPermissionsProperties"]: """Lists the billing permissions the caller has for a customer. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param customer_name: The ID that uniquely identifies a customer. Required. :type customer_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either BillingPermissionsProperties or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billing.models.BillingPermissionsProperties] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingPermissionsListResult] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_by_customer_request( billing_account_name=billing_account_name, customer_name=customer_name, api_version=api_version, template_url=self.list_by_customer.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore else: request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request def extract_data(pipeline_response): deserialized = self._deserialize("BillingPermissionsListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return ItemPaged(get_next, extract_data) list_by_customer.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/customers/{customerName}/billingPermissions"} # type: ignore @distributed_trace def list_by_billing_account( self, billing_account_name: str, **kwargs: Any ) -> Iterable["_models.BillingPermissionsProperties"]: """Lists the billing permissions the caller has on a billing account. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either BillingPermissionsProperties or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billing.models.BillingPermissionsProperties] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingPermissionsListResult] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_by_billing_account_request( billing_account_name=billing_account_name, api_version=api_version, template_url=self.list_by_billing_account.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore else: request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request def extract_data(pipeline_response): deserialized = self._deserialize("BillingPermissionsListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return ItemPaged(get_next, extract_data) list_by_billing_account.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingPermissions"} # type: ignore @distributed_trace def list_by_invoice_sections( self, billing_account_name: str, billing_profile_name: str, invoice_section_name: str, **kwargs: Any ) -> Iterable["_models.BillingPermissionsProperties"]: """Lists the billing permissions the caller has on an invoice section. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :param invoice_section_name: The ID that uniquely identifies an invoice section. Required. :type invoice_section_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either BillingPermissionsProperties or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billing.models.BillingPermissionsProperties] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingPermissionsListResult] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_by_invoice_sections_request( billing_account_name=billing_account_name, billing_profile_name=billing_profile_name, invoice_section_name=invoice_section_name, api_version=api_version, template_url=self.list_by_invoice_sections.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore else: request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request def extract_data(pipeline_response): deserialized = self._deserialize("BillingPermissionsListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return ItemPaged(get_next, extract_data) list_by_invoice_sections.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoiceSections/{invoiceSectionName}/billingPermissions"} # type: ignore @distributed_trace def list_by_billing_profile( self, billing_account_name: str, billing_profile_name: str, **kwargs: Any ) -> Iterable["_models.BillingPermissionsProperties"]: """Lists the billing permissions the caller has on a billing profile. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either BillingPermissionsProperties or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billing.models.BillingPermissionsProperties] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingPermissionsListResult] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_by_billing_profile_request( billing_account_name=billing_account_name, billing_profile_name=billing_profile_name, api_version=api_version, template_url=self.list_by_billing_profile.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore else: request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request def extract_data(pipeline_response): deserialized = self._deserialize("BillingPermissionsListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return ItemPaged(get_next, extract_data) list_by_billing_profile.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/billingPermissions"} # type: ignore
0.533884
0.089097
import sys from typing import Any, Callable, Dict, Iterable, Optional, TypeVar from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, map_error, ) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models from .._serialization import Serializer from .._vendor import _convert_request, _format_url_section if sys.version_info >= (3, 8): from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports else: from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False def build_list_request( subscription_id: str, *, filter: Optional[str] = None, skiptoken: Optional[str] = None, top: Optional[int] = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop( "api_version", _params.pop("api-version", "2018-03-01-preview") ) # type: Literal["2018-03-01-preview"] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Billing/billingPeriods") path_format_arguments = { "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if filter is not None: _params["$filter"] = _SERIALIZER.query("filter", filter, "str") if skiptoken is not None: _params["$skiptoken"] = _SERIALIZER.query("skiptoken", skiptoken, "str") if top is not None: _params["$top"] = _SERIALIZER.query("top", top, "int", maximum=100, minimum=1) # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_get_request(billing_period_name: str, subscription_id: str, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop( "api_version", _params.pop("api-version", "2018-03-01-preview") ) # type: Literal["2018-03-01-preview"] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Billing/billingPeriods/{billingPeriodName}" ) # pylint: disable=line-too-long path_format_arguments = { "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), "billingPeriodName": _SERIALIZER.url("billing_period_name", billing_period_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) class BillingPeriodsOperations: """ .. warning:: **DO NOT** instantiate this class directly. Instead, you should access the following operations through :class:`~azure.mgmt.billing.BillingManagementClient`'s :attr:`billing_periods` attribute. """ models = _models def __init__(self, *args, **kwargs): input_args = list(args) self._client = input_args.pop(0) if input_args else kwargs.pop("client") self._config = input_args.pop(0) if input_args else kwargs.pop("config") self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace def list( self, filter: Optional[str] = None, skiptoken: Optional[str] = None, top: Optional[int] = None, **kwargs: Any ) -> Iterable["_models.BillingPeriod"]: """Lists the available billing periods for a subscription in reverse chronological order. This is only supported for Azure Web-Direct subscriptions. Other subscription types which were not purchased directly through the Azure web portal are not supported through this preview API. :param filter: May be used to filter billing periods by billingPeriodEndDate. The filter supports 'eq', 'lt', 'gt', 'le', 'ge', and 'and'. It does not currently support 'ne', 'or', or 'not'. Default value is None. :type filter: str :param skiptoken: Skiptoken is only used if a previous operation returned a partial result. If a previous response contains a nextLink element, the value of the nextLink element will include a skiptoken parameter that specifies a starting point to use for subsequent calls. Default value is None. :type skiptoken: str :param top: May be used to limit the number of results to the most recent N billing periods. Default value is None. :type top: int :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either BillingPeriod or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billing.models.BillingPeriod] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop( "api_version", _params.pop("api-version", "2018-03-01-preview") ) # type: Literal["2018-03-01-preview"] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingPeriodsListResult] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_request( subscription_id=self._config.subscription_id, filter=filter, skiptoken=skiptoken, top=top, api_version=api_version, template_url=self.list.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore else: request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request def extract_data(pipeline_response): deserialized = self._deserialize("BillingPeriodsListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return ItemPaged(get_next, extract_data) list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Billing/billingPeriods"} # type: ignore @distributed_trace def get(self, billing_period_name: str, **kwargs: Any) -> _models.BillingPeriod: """Gets a named billing period. This is only supported for Azure Web-Direct subscriptions. Other subscription types which were not purchased directly through the Azure web portal are not supported through this preview API. :param billing_period_name: The name of a BillingPeriod resource. Required. :type billing_period_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: BillingPeriod or the result of cls(response) :rtype: ~azure.mgmt.billing.models.BillingPeriod :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop( "api_version", _params.pop("api-version", "2018-03-01-preview") ) # type: Literal["2018-03-01-preview"] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingPeriod] request = build_get_request( billing_period_name=billing_period_name, subscription_id=self._config.subscription_id, api_version=api_version, template_url=self.get.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize("BillingPeriod", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Billing/billingPeriods/{billingPeriodName}"} # type: ignore
azure-mgmt-billing
/azure_mgmt_billing-6.1.0b1-py3-none-any.whl/azure/mgmt/billing/operations/_billing_periods_operations.py
_billing_periods_operations.py
import sys from typing import Any, Callable, Dict, Iterable, Optional, TypeVar from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, map_error, ) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models from .._serialization import Serializer from .._vendor import _convert_request, _format_url_section if sys.version_info >= (3, 8): from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports else: from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False def build_list_request( subscription_id: str, *, filter: Optional[str] = None, skiptoken: Optional[str] = None, top: Optional[int] = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop( "api_version", _params.pop("api-version", "2018-03-01-preview") ) # type: Literal["2018-03-01-preview"] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Billing/billingPeriods") path_format_arguments = { "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if filter is not None: _params["$filter"] = _SERIALIZER.query("filter", filter, "str") if skiptoken is not None: _params["$skiptoken"] = _SERIALIZER.query("skiptoken", skiptoken, "str") if top is not None: _params["$top"] = _SERIALIZER.query("top", top, "int", maximum=100, minimum=1) # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_get_request(billing_period_name: str, subscription_id: str, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop( "api_version", _params.pop("api-version", "2018-03-01-preview") ) # type: Literal["2018-03-01-preview"] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Billing/billingPeriods/{billingPeriodName}" ) # pylint: disable=line-too-long path_format_arguments = { "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), "billingPeriodName": _SERIALIZER.url("billing_period_name", billing_period_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) class BillingPeriodsOperations: """ .. warning:: **DO NOT** instantiate this class directly. Instead, you should access the following operations through :class:`~azure.mgmt.billing.BillingManagementClient`'s :attr:`billing_periods` attribute. """ models = _models def __init__(self, *args, **kwargs): input_args = list(args) self._client = input_args.pop(0) if input_args else kwargs.pop("client") self._config = input_args.pop(0) if input_args else kwargs.pop("config") self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace def list( self, filter: Optional[str] = None, skiptoken: Optional[str] = None, top: Optional[int] = None, **kwargs: Any ) -> Iterable["_models.BillingPeriod"]: """Lists the available billing periods for a subscription in reverse chronological order. This is only supported for Azure Web-Direct subscriptions. Other subscription types which were not purchased directly through the Azure web portal are not supported through this preview API. :param filter: May be used to filter billing periods by billingPeriodEndDate. The filter supports 'eq', 'lt', 'gt', 'le', 'ge', and 'and'. It does not currently support 'ne', 'or', or 'not'. Default value is None. :type filter: str :param skiptoken: Skiptoken is only used if a previous operation returned a partial result. If a previous response contains a nextLink element, the value of the nextLink element will include a skiptoken parameter that specifies a starting point to use for subsequent calls. Default value is None. :type skiptoken: str :param top: May be used to limit the number of results to the most recent N billing periods. Default value is None. :type top: int :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either BillingPeriod or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billing.models.BillingPeriod] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop( "api_version", _params.pop("api-version", "2018-03-01-preview") ) # type: Literal["2018-03-01-preview"] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingPeriodsListResult] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_request( subscription_id=self._config.subscription_id, filter=filter, skiptoken=skiptoken, top=top, api_version=api_version, template_url=self.list.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore else: request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request def extract_data(pipeline_response): deserialized = self._deserialize("BillingPeriodsListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return ItemPaged(get_next, extract_data) list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Billing/billingPeriods"} # type: ignore @distributed_trace def get(self, billing_period_name: str, **kwargs: Any) -> _models.BillingPeriod: """Gets a named billing period. This is only supported for Azure Web-Direct subscriptions. Other subscription types which were not purchased directly through the Azure web portal are not supported through this preview API. :param billing_period_name: The name of a BillingPeriod resource. Required. :type billing_period_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: BillingPeriod or the result of cls(response) :rtype: ~azure.mgmt.billing.models.BillingPeriod :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop( "api_version", _params.pop("api-version", "2018-03-01-preview") ) # type: Literal["2018-03-01-preview"] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingPeriod] request = build_get_request( billing_period_name=billing_period_name, subscription_id=self._config.subscription_id, api_version=api_version, template_url=self.get.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize("BillingPeriod", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Billing/billingPeriods/{billingPeriodName}"} # type: ignore
0.683314
0.077553
import sys from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, overload from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, map_error, ) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models from .._serialization import Serializer from .._vendor import _convert_request, _format_url_section if sys.version_info >= (3, 8): from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports else: from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False def build_get_by_billing_profile_request( billing_account_name: str, billing_profile_name: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/policies/default", ) # pylint: disable=line-too-long path_format_arguments = { "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), "billingProfileName": _SERIALIZER.url("billing_profile_name", billing_profile_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_update_request(billing_account_name: str, billing_profile_name: str, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/policies/default", ) # pylint: disable=line-too-long path_format_arguments = { "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), "billingProfileName": _SERIALIZER.url("billing_profile_name", billing_profile_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers if content_type is not None: _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) def build_get_by_customer_request(billing_account_name: str, customer_name: str, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/customers/{customerName}/policies/default", ) # pylint: disable=line-too-long path_format_arguments = { "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), "customerName": _SERIALIZER.url("customer_name", customer_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_update_customer_request(billing_account_name: str, customer_name: str, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/customers/{customerName}/policies/default", ) # pylint: disable=line-too-long path_format_arguments = { "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), "customerName": _SERIALIZER.url("customer_name", customer_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers if content_type is not None: _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) class PoliciesOperations: """ .. warning:: **DO NOT** instantiate this class directly. Instead, you should access the following operations through :class:`~azure.mgmt.billing.BillingManagementClient`'s :attr:`policies` attribute. """ models = _models def __init__(self, *args, **kwargs): input_args = list(args) self._client = input_args.pop(0) if input_args else kwargs.pop("client") self._config = input_args.pop(0) if input_args else kwargs.pop("config") self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace def get_by_billing_profile( self, billing_account_name: str, billing_profile_name: str, **kwargs: Any ) -> _models.Policy: """Lists the policies for a billing profile. This operation is supported only for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Policy or the result of cls(response) :rtype: ~azure.mgmt.billing.models.Policy :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.Policy] request = build_get_by_billing_profile_request( billing_account_name=billing_account_name, billing_profile_name=billing_profile_name, api_version=api_version, template_url=self.get_by_billing_profile.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize("Policy", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get_by_billing_profile.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/policies/default"} # type: ignore @overload def update( self, billing_account_name: str, billing_profile_name: str, parameters: _models.Policy, *, content_type: str = "application/json", **kwargs: Any ) -> _models.Policy: """Updates the policies for a billing profile. This operation is supported only for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :param parameters: Request parameters that are provided to the update policies operation. Required. :type parameters: ~azure.mgmt.billing.models.Policy :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Policy or the result of cls(response) :rtype: ~azure.mgmt.billing.models.Policy :raises ~azure.core.exceptions.HttpResponseError: """ @overload def update( self, billing_account_name: str, billing_profile_name: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any ) -> _models.Policy: """Updates the policies for a billing profile. This operation is supported only for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :param parameters: Request parameters that are provided to the update policies operation. Required. :type parameters: IO :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Policy or the result of cls(response) :rtype: ~azure.mgmt.billing.models.Policy :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace def update( self, billing_account_name: str, billing_profile_name: str, parameters: Union[_models.Policy, IO], **kwargs: Any ) -> _models.Policy: """Updates the policies for a billing profile. This operation is supported only for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :param parameters: Request parameters that are provided to the update policies operation. Is either a model type or a IO type. Required. :type parameters: ~azure.mgmt.billing.models.Policy or IO :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. Default value is None. :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Policy or the result of cls(response) :rtype: ~azure.mgmt.billing.models.Policy :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] cls = kwargs.pop("cls", None) # type: ClsType[_models.Policy] content_type = content_type or "application/json" _json = None _content = None if isinstance(parameters, (IO, bytes)): _content = parameters else: _json = self._serialize.body(parameters, "Policy") request = build_update_request( billing_account_name=billing_account_name, billing_profile_name=billing_profile_name, api_version=api_version, content_type=content_type, json=_json, content=_content, template_url=self.update.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize("Policy", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized update.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/policies/default"} # type: ignore @distributed_trace def get_by_customer(self, billing_account_name: str, customer_name: str, **kwargs: Any) -> _models.CustomerPolicy: """Lists the policies for a customer. This operation is supported only for billing accounts with agreement type Microsoft Partner Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param customer_name: The ID that uniquely identifies a customer. Required. :type customer_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: CustomerPolicy or the result of cls(response) :rtype: ~azure.mgmt.billing.models.CustomerPolicy :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.CustomerPolicy] request = build_get_by_customer_request( billing_account_name=billing_account_name, customer_name=customer_name, api_version=api_version, template_url=self.get_by_customer.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize("CustomerPolicy", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get_by_customer.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/customers/{customerName}/policies/default"} # type: ignore @overload def update_customer( self, billing_account_name: str, customer_name: str, parameters: _models.CustomerPolicy, *, content_type: str = "application/json", **kwargs: Any ) -> _models.CustomerPolicy: """Updates the policies for a customer. This operation is supported only for billing accounts with agreement type Microsoft Partner Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param customer_name: The ID that uniquely identifies a customer. Required. :type customer_name: str :param parameters: Request parameters that are provided to the update policies operation. Required. :type parameters: ~azure.mgmt.billing.models.CustomerPolicy :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: CustomerPolicy or the result of cls(response) :rtype: ~azure.mgmt.billing.models.CustomerPolicy :raises ~azure.core.exceptions.HttpResponseError: """ @overload def update_customer( self, billing_account_name: str, customer_name: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any ) -> _models.CustomerPolicy: """Updates the policies for a customer. This operation is supported only for billing accounts with agreement type Microsoft Partner Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param customer_name: The ID that uniquely identifies a customer. Required. :type customer_name: str :param parameters: Request parameters that are provided to the update policies operation. Required. :type parameters: IO :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: CustomerPolicy or the result of cls(response) :rtype: ~azure.mgmt.billing.models.CustomerPolicy :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace def update_customer( self, billing_account_name: str, customer_name: str, parameters: Union[_models.CustomerPolicy, IO], **kwargs: Any ) -> _models.CustomerPolicy: """Updates the policies for a customer. This operation is supported only for billing accounts with agreement type Microsoft Partner Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param customer_name: The ID that uniquely identifies a customer. Required. :type customer_name: str :param parameters: Request parameters that are provided to the update policies operation. Is either a model type or a IO type. Required. :type parameters: ~azure.mgmt.billing.models.CustomerPolicy or IO :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. Default value is None. :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: CustomerPolicy or the result of cls(response) :rtype: ~azure.mgmt.billing.models.CustomerPolicy :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] cls = kwargs.pop("cls", None) # type: ClsType[_models.CustomerPolicy] content_type = content_type or "application/json" _json = None _content = None if isinstance(parameters, (IO, bytes)): _content = parameters else: _json = self._serialize.body(parameters, "CustomerPolicy") request = build_update_customer_request( billing_account_name=billing_account_name, customer_name=customer_name, api_version=api_version, content_type=content_type, json=_json, content=_content, template_url=self.update_customer.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize("CustomerPolicy", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized update_customer.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/customers/{customerName}/policies/default"} # type: ignore
azure-mgmt-billing
/azure_mgmt_billing-6.1.0b1-py3-none-any.whl/azure/mgmt/billing/operations/_policies_operations.py
_policies_operations.py
import sys from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, overload from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, map_error, ) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models from .._serialization import Serializer from .._vendor import _convert_request, _format_url_section if sys.version_info >= (3, 8): from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports else: from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False def build_get_by_billing_profile_request( billing_account_name: str, billing_profile_name: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/policies/default", ) # pylint: disable=line-too-long path_format_arguments = { "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), "billingProfileName": _SERIALIZER.url("billing_profile_name", billing_profile_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_update_request(billing_account_name: str, billing_profile_name: str, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/policies/default", ) # pylint: disable=line-too-long path_format_arguments = { "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), "billingProfileName": _SERIALIZER.url("billing_profile_name", billing_profile_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers if content_type is not None: _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) def build_get_by_customer_request(billing_account_name: str, customer_name: str, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/customers/{customerName}/policies/default", ) # pylint: disable=line-too-long path_format_arguments = { "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), "customerName": _SERIALIZER.url("customer_name", customer_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_update_customer_request(billing_account_name: str, customer_name: str, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/customers/{customerName}/policies/default", ) # pylint: disable=line-too-long path_format_arguments = { "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), "customerName": _SERIALIZER.url("customer_name", customer_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers if content_type is not None: _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) class PoliciesOperations: """ .. warning:: **DO NOT** instantiate this class directly. Instead, you should access the following operations through :class:`~azure.mgmt.billing.BillingManagementClient`'s :attr:`policies` attribute. """ models = _models def __init__(self, *args, **kwargs): input_args = list(args) self._client = input_args.pop(0) if input_args else kwargs.pop("client") self._config = input_args.pop(0) if input_args else kwargs.pop("config") self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace def get_by_billing_profile( self, billing_account_name: str, billing_profile_name: str, **kwargs: Any ) -> _models.Policy: """Lists the policies for a billing profile. This operation is supported only for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Policy or the result of cls(response) :rtype: ~azure.mgmt.billing.models.Policy :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.Policy] request = build_get_by_billing_profile_request( billing_account_name=billing_account_name, billing_profile_name=billing_profile_name, api_version=api_version, template_url=self.get_by_billing_profile.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize("Policy", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get_by_billing_profile.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/policies/default"} # type: ignore @overload def update( self, billing_account_name: str, billing_profile_name: str, parameters: _models.Policy, *, content_type: str = "application/json", **kwargs: Any ) -> _models.Policy: """Updates the policies for a billing profile. This operation is supported only for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :param parameters: Request parameters that are provided to the update policies operation. Required. :type parameters: ~azure.mgmt.billing.models.Policy :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Policy or the result of cls(response) :rtype: ~azure.mgmt.billing.models.Policy :raises ~azure.core.exceptions.HttpResponseError: """ @overload def update( self, billing_account_name: str, billing_profile_name: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any ) -> _models.Policy: """Updates the policies for a billing profile. This operation is supported only for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :param parameters: Request parameters that are provided to the update policies operation. Required. :type parameters: IO :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Policy or the result of cls(response) :rtype: ~azure.mgmt.billing.models.Policy :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace def update( self, billing_account_name: str, billing_profile_name: str, parameters: Union[_models.Policy, IO], **kwargs: Any ) -> _models.Policy: """Updates the policies for a billing profile. This operation is supported only for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :param parameters: Request parameters that are provided to the update policies operation. Is either a model type or a IO type. Required. :type parameters: ~azure.mgmt.billing.models.Policy or IO :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. Default value is None. :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Policy or the result of cls(response) :rtype: ~azure.mgmt.billing.models.Policy :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] cls = kwargs.pop("cls", None) # type: ClsType[_models.Policy] content_type = content_type or "application/json" _json = None _content = None if isinstance(parameters, (IO, bytes)): _content = parameters else: _json = self._serialize.body(parameters, "Policy") request = build_update_request( billing_account_name=billing_account_name, billing_profile_name=billing_profile_name, api_version=api_version, content_type=content_type, json=_json, content=_content, template_url=self.update.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize("Policy", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized update.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/policies/default"} # type: ignore @distributed_trace def get_by_customer(self, billing_account_name: str, customer_name: str, **kwargs: Any) -> _models.CustomerPolicy: """Lists the policies for a customer. This operation is supported only for billing accounts with agreement type Microsoft Partner Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param customer_name: The ID that uniquely identifies a customer. Required. :type customer_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: CustomerPolicy or the result of cls(response) :rtype: ~azure.mgmt.billing.models.CustomerPolicy :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.CustomerPolicy] request = build_get_by_customer_request( billing_account_name=billing_account_name, customer_name=customer_name, api_version=api_version, template_url=self.get_by_customer.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize("CustomerPolicy", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get_by_customer.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/customers/{customerName}/policies/default"} # type: ignore @overload def update_customer( self, billing_account_name: str, customer_name: str, parameters: _models.CustomerPolicy, *, content_type: str = "application/json", **kwargs: Any ) -> _models.CustomerPolicy: """Updates the policies for a customer. This operation is supported only for billing accounts with agreement type Microsoft Partner Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param customer_name: The ID that uniquely identifies a customer. Required. :type customer_name: str :param parameters: Request parameters that are provided to the update policies operation. Required. :type parameters: ~azure.mgmt.billing.models.CustomerPolicy :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: CustomerPolicy or the result of cls(response) :rtype: ~azure.mgmt.billing.models.CustomerPolicy :raises ~azure.core.exceptions.HttpResponseError: """ @overload def update_customer( self, billing_account_name: str, customer_name: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any ) -> _models.CustomerPolicy: """Updates the policies for a customer. This operation is supported only for billing accounts with agreement type Microsoft Partner Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param customer_name: The ID that uniquely identifies a customer. Required. :type customer_name: str :param parameters: Request parameters that are provided to the update policies operation. Required. :type parameters: IO :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: CustomerPolicy or the result of cls(response) :rtype: ~azure.mgmt.billing.models.CustomerPolicy :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace def update_customer( self, billing_account_name: str, customer_name: str, parameters: Union[_models.CustomerPolicy, IO], **kwargs: Any ) -> _models.CustomerPolicy: """Updates the policies for a customer. This operation is supported only for billing accounts with agreement type Microsoft Partner Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param customer_name: The ID that uniquely identifies a customer. Required. :type customer_name: str :param parameters: Request parameters that are provided to the update policies operation. Is either a model type or a IO type. Required. :type parameters: ~azure.mgmt.billing.models.CustomerPolicy or IO :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. Default value is None. :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: CustomerPolicy or the result of cls(response) :rtype: ~azure.mgmt.billing.models.CustomerPolicy :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] cls = kwargs.pop("cls", None) # type: ClsType[_models.CustomerPolicy] content_type = content_type or "application/json" _json = None _content = None if isinstance(parameters, (IO, bytes)): _content = parameters else: _json = self._serialize.body(parameters, "CustomerPolicy") request = build_update_customer_request( billing_account_name=billing_account_name, customer_name=customer_name, api_version=api_version, content_type=content_type, json=_json, content=_content, template_url=self.update_customer.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize("CustomerPolicy", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized update_customer.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/customers/{customerName}/policies/default"} # type: ignore
0.519765
0.085404
import sys from typing import Any, Callable, Dict, Iterable, Optional, TypeVar from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, map_error, ) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models from .._serialization import Serializer from .._vendor import _convert_request, _format_url_section if sys.version_info >= (3, 8): from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports else: from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False def build_list_by_billing_account_request( billing_account_name: str, *, expand: Optional[str] = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop("template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/agreements") path_format_arguments = { "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if expand is not None: _params["$expand"] = _SERIALIZER.query("expand", expand, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_get_request( billing_account_name: str, agreement_name: str, *, expand: Optional[str] = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/agreements/{agreementName}" ) # pylint: disable=line-too-long path_format_arguments = { "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), "agreementName": _SERIALIZER.url("agreement_name", agreement_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if expand is not None: _params["$expand"] = _SERIALIZER.query("expand", expand, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) class AgreementsOperations: """ .. warning:: **DO NOT** instantiate this class directly. Instead, you should access the following operations through :class:`~azure.mgmt.billing.BillingManagementClient`'s :attr:`agreements` attribute. """ models = _models def __init__(self, *args, **kwargs): input_args = list(args) self._client = input_args.pop(0) if input_args else kwargs.pop("client") self._config = input_args.pop(0) if input_args else kwargs.pop("config") self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace def list_by_billing_account( self, billing_account_name: str, expand: Optional[str] = None, **kwargs: Any ) -> Iterable["_models.Agreement"]: """Lists the agreements for a billing account. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param expand: May be used to expand the participants. Default value is None. :type expand: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either Agreement or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billing.models.Agreement] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.AgreementListResult] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_by_billing_account_request( billing_account_name=billing_account_name, expand=expand, api_version=api_version, template_url=self.list_by_billing_account.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore else: request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request def extract_data(pipeline_response): deserialized = self._deserialize("AgreementListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return ItemPaged(get_next, extract_data) list_by_billing_account.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/agreements"} # type: ignore @distributed_trace def get( self, billing_account_name: str, agreement_name: str, expand: Optional[str] = None, **kwargs: Any ) -> _models.Agreement: """Gets an agreement by ID. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param agreement_name: The ID that uniquely identifies an agreement. Required. :type agreement_name: str :param expand: May be used to expand the participants. Default value is None. :type expand: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Agreement or the result of cls(response) :rtype: ~azure.mgmt.billing.models.Agreement :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.Agreement] request = build_get_request( billing_account_name=billing_account_name, agreement_name=agreement_name, expand=expand, api_version=api_version, template_url=self.get.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize("Agreement", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/agreements/{agreementName}"} # type: ignore
azure-mgmt-billing
/azure_mgmt_billing-6.1.0b1-py3-none-any.whl/azure/mgmt/billing/operations/_agreements_operations.py
_agreements_operations.py
import sys from typing import Any, Callable, Dict, Iterable, Optional, TypeVar from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, map_error, ) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models from .._serialization import Serializer from .._vendor import _convert_request, _format_url_section if sys.version_info >= (3, 8): from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports else: from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False def build_list_by_billing_account_request( billing_account_name: str, *, expand: Optional[str] = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop("template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/agreements") path_format_arguments = { "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if expand is not None: _params["$expand"] = _SERIALIZER.query("expand", expand, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_get_request( billing_account_name: str, agreement_name: str, *, expand: Optional[str] = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/agreements/{agreementName}" ) # pylint: disable=line-too-long path_format_arguments = { "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), "agreementName": _SERIALIZER.url("agreement_name", agreement_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if expand is not None: _params["$expand"] = _SERIALIZER.query("expand", expand, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) class AgreementsOperations: """ .. warning:: **DO NOT** instantiate this class directly. Instead, you should access the following operations through :class:`~azure.mgmt.billing.BillingManagementClient`'s :attr:`agreements` attribute. """ models = _models def __init__(self, *args, **kwargs): input_args = list(args) self._client = input_args.pop(0) if input_args else kwargs.pop("client") self._config = input_args.pop(0) if input_args else kwargs.pop("config") self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace def list_by_billing_account( self, billing_account_name: str, expand: Optional[str] = None, **kwargs: Any ) -> Iterable["_models.Agreement"]: """Lists the agreements for a billing account. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param expand: May be used to expand the participants. Default value is None. :type expand: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either Agreement or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billing.models.Agreement] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.AgreementListResult] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_by_billing_account_request( billing_account_name=billing_account_name, expand=expand, api_version=api_version, template_url=self.list_by_billing_account.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore else: request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request def extract_data(pipeline_response): deserialized = self._deserialize("AgreementListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return ItemPaged(get_next, extract_data) list_by_billing_account.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/agreements"} # type: ignore @distributed_trace def get( self, billing_account_name: str, agreement_name: str, expand: Optional[str] = None, **kwargs: Any ) -> _models.Agreement: """Gets an agreement by ID. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param agreement_name: The ID that uniquely identifies an agreement. Required. :type agreement_name: str :param expand: May be used to expand the participants. Default value is None. :type expand: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Agreement or the result of cls(response) :rtype: ~azure.mgmt.billing.models.Agreement :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.Agreement] request = build_get_request( billing_account_name=billing_account_name, agreement_name=agreement_name, expand=expand, api_version=api_version, template_url=self.get.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize("Agreement", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/agreements/{agreementName}"} # type: ignore
0.619241
0.083553
import sys from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, cast, overload from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, map_error, ) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse from azure.core.polling import LROPoller, NoPolling, PollingMethod from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.arm_polling import ARMPolling from .. import models as _models from .._serialization import Serializer from .._vendor import _convert_request, _format_url_section if sys.version_info >= (3, 8): from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports else: from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False def build_list_by_billing_profile_request( billing_account_name: str, billing_profile_name: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoiceSections", ) # pylint: disable=line-too-long path_format_arguments = { "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), "billingProfileName": _SERIALIZER.url("billing_profile_name", billing_profile_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_get_request( billing_account_name: str, billing_profile_name: str, invoice_section_name: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoiceSections/{invoiceSectionName}", ) # pylint: disable=line-too-long path_format_arguments = { "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), "billingProfileName": _SERIALIZER.url("billing_profile_name", billing_profile_name, "str"), "invoiceSectionName": _SERIALIZER.url("invoice_section_name", invoice_section_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_create_or_update_request( billing_account_name: str, billing_profile_name: str, invoice_section_name: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoiceSections/{invoiceSectionName}", ) # pylint: disable=line-too-long path_format_arguments = { "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), "billingProfileName": _SERIALIZER.url("billing_profile_name", billing_profile_name, "str"), "invoiceSectionName": _SERIALIZER.url("invoice_section_name", invoice_section_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers if content_type is not None: _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) class InvoiceSectionsOperations: """ .. warning:: **DO NOT** instantiate this class directly. Instead, you should access the following operations through :class:`~azure.mgmt.billing.BillingManagementClient`'s :attr:`invoice_sections` attribute. """ models = _models def __init__(self, *args, **kwargs): input_args = list(args) self._client = input_args.pop(0) if input_args else kwargs.pop("client") self._config = input_args.pop(0) if input_args else kwargs.pop("config") self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace def list_by_billing_profile( self, billing_account_name: str, billing_profile_name: str, **kwargs: Any ) -> Iterable["_models.InvoiceSection"]: """Lists the invoice sections that a user has access to. The operation is supported only for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either InvoiceSection or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billing.models.InvoiceSection] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.InvoiceSectionListResult] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_by_billing_profile_request( billing_account_name=billing_account_name, billing_profile_name=billing_profile_name, api_version=api_version, template_url=self.list_by_billing_profile.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore else: request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request def extract_data(pipeline_response): deserialized = self._deserialize("InvoiceSectionListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return ItemPaged(get_next, extract_data) list_by_billing_profile.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoiceSections"} # type: ignore @distributed_trace def get( self, billing_account_name: str, billing_profile_name: str, invoice_section_name: str, **kwargs: Any ) -> _models.InvoiceSection: """Gets an invoice section by its ID. The operation is supported only for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :param invoice_section_name: The ID that uniquely identifies an invoice section. Required. :type invoice_section_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: InvoiceSection or the result of cls(response) :rtype: ~azure.mgmt.billing.models.InvoiceSection :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.InvoiceSection] request = build_get_request( billing_account_name=billing_account_name, billing_profile_name=billing_profile_name, invoice_section_name=invoice_section_name, api_version=api_version, template_url=self.get.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize("InvoiceSection", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoiceSections/{invoiceSectionName}"} # type: ignore def _create_or_update_initial( self, billing_account_name: str, billing_profile_name: str, invoice_section_name: str, parameters: Union[_models.InvoiceSection, IO], **kwargs: Any ) -> Optional[_models.InvoiceSection]: error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.InvoiceSection]] content_type = content_type or "application/json" _json = None _content = None if isinstance(parameters, (IO, bytes)): _content = parameters else: _json = self._serialize.body(parameters, "InvoiceSection") request = build_create_or_update_request( billing_account_name=billing_account_name, billing_profile_name=billing_profile_name, invoice_section_name=invoice_section_name, api_version=api_version, content_type=content_type, json=_json, content=_content, template_url=self._create_or_update_initial.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = None response_headers = {} if response.status_code == 200: deserialized = self._deserialize("InvoiceSection", pipeline_response) if response.status_code == 202: response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) if cls: return cls(pipeline_response, deserialized, response_headers) return deserialized _create_or_update_initial.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoiceSections/{invoiceSectionName}"} # type: ignore @overload def begin_create_or_update( self, billing_account_name: str, billing_profile_name: str, invoice_section_name: str, parameters: _models.InvoiceSection, *, content_type: str = "application/json", **kwargs: Any ) -> LROPoller[_models.InvoiceSection]: """Creates or updates an invoice section. The operation is supported only for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :param invoice_section_name: The ID that uniquely identifies an invoice section. Required. :type invoice_section_name: str :param parameters: The new or updated invoice section. Required. :type parameters: ~azure.mgmt.billing.models.InvoiceSection :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.PollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of LROPoller that returns either InvoiceSection or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.billing.models.InvoiceSection] :raises ~azure.core.exceptions.HttpResponseError: """ @overload def begin_create_or_update( self, billing_account_name: str, billing_profile_name: str, invoice_section_name: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any ) -> LROPoller[_models.InvoiceSection]: """Creates or updates an invoice section. The operation is supported only for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :param invoice_section_name: The ID that uniquely identifies an invoice section. Required. :type invoice_section_name: str :param parameters: The new or updated invoice section. Required. :type parameters: IO :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.PollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of LROPoller that returns either InvoiceSection or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.billing.models.InvoiceSection] :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace def begin_create_or_update( self, billing_account_name: str, billing_profile_name: str, invoice_section_name: str, parameters: Union[_models.InvoiceSection, IO], **kwargs: Any ) -> LROPoller[_models.InvoiceSection]: """Creates or updates an invoice section. The operation is supported only for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :param invoice_section_name: The ID that uniquely identifies an invoice section. Required. :type invoice_section_name: str :param parameters: The new or updated invoice section. Is either a model type or a IO type. Required. :type parameters: ~azure.mgmt.billing.models.InvoiceSection or IO :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. Default value is None. :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.PollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of LROPoller that returns either InvoiceSection or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.billing.models.InvoiceSection] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] cls = kwargs.pop("cls", None) # type: ClsType[_models.InvoiceSection] polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod] lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: raw_result = self._create_or_update_initial( # type: ignore billing_account_name=billing_account_name, billing_profile_name=billing_profile_name, invoice_section_name=invoice_section_name, parameters=parameters, api_version=api_version, content_type=content_type, cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): deserialized = self._deserialize("InvoiceSection", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized if polling is True: polling_method = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) # type: PollingMethod elif polling is False: polling_method = cast(PollingMethod, NoPolling()) else: polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) return LROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_create_or_update.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoiceSections/{invoiceSectionName}"} # type: ignore
azure-mgmt-billing
/azure_mgmt_billing-6.1.0b1-py3-none-any.whl/azure/mgmt/billing/operations/_invoice_sections_operations.py
_invoice_sections_operations.py
import sys from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, cast, overload from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, map_error, ) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse from azure.core.polling import LROPoller, NoPolling, PollingMethod from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.arm_polling import ARMPolling from .. import models as _models from .._serialization import Serializer from .._vendor import _convert_request, _format_url_section if sys.version_info >= (3, 8): from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports else: from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False def build_list_by_billing_profile_request( billing_account_name: str, billing_profile_name: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoiceSections", ) # pylint: disable=line-too-long path_format_arguments = { "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), "billingProfileName": _SERIALIZER.url("billing_profile_name", billing_profile_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_get_request( billing_account_name: str, billing_profile_name: str, invoice_section_name: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoiceSections/{invoiceSectionName}", ) # pylint: disable=line-too-long path_format_arguments = { "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), "billingProfileName": _SERIALIZER.url("billing_profile_name", billing_profile_name, "str"), "invoiceSectionName": _SERIALIZER.url("invoice_section_name", invoice_section_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_create_or_update_request( billing_account_name: str, billing_profile_name: str, invoice_section_name: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoiceSections/{invoiceSectionName}", ) # pylint: disable=line-too-long path_format_arguments = { "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), "billingProfileName": _SERIALIZER.url("billing_profile_name", billing_profile_name, "str"), "invoiceSectionName": _SERIALIZER.url("invoice_section_name", invoice_section_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers if content_type is not None: _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) class InvoiceSectionsOperations: """ .. warning:: **DO NOT** instantiate this class directly. Instead, you should access the following operations through :class:`~azure.mgmt.billing.BillingManagementClient`'s :attr:`invoice_sections` attribute. """ models = _models def __init__(self, *args, **kwargs): input_args = list(args) self._client = input_args.pop(0) if input_args else kwargs.pop("client") self._config = input_args.pop(0) if input_args else kwargs.pop("config") self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace def list_by_billing_profile( self, billing_account_name: str, billing_profile_name: str, **kwargs: Any ) -> Iterable["_models.InvoiceSection"]: """Lists the invoice sections that a user has access to. The operation is supported only for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either InvoiceSection or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billing.models.InvoiceSection] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.InvoiceSectionListResult] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_by_billing_profile_request( billing_account_name=billing_account_name, billing_profile_name=billing_profile_name, api_version=api_version, template_url=self.list_by_billing_profile.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore else: request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request def extract_data(pipeline_response): deserialized = self._deserialize("InvoiceSectionListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return ItemPaged(get_next, extract_data) list_by_billing_profile.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoiceSections"} # type: ignore @distributed_trace def get( self, billing_account_name: str, billing_profile_name: str, invoice_section_name: str, **kwargs: Any ) -> _models.InvoiceSection: """Gets an invoice section by its ID. The operation is supported only for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :param invoice_section_name: The ID that uniquely identifies an invoice section. Required. :type invoice_section_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: InvoiceSection or the result of cls(response) :rtype: ~azure.mgmt.billing.models.InvoiceSection :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.InvoiceSection] request = build_get_request( billing_account_name=billing_account_name, billing_profile_name=billing_profile_name, invoice_section_name=invoice_section_name, api_version=api_version, template_url=self.get.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize("InvoiceSection", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoiceSections/{invoiceSectionName}"} # type: ignore def _create_or_update_initial( self, billing_account_name: str, billing_profile_name: str, invoice_section_name: str, parameters: Union[_models.InvoiceSection, IO], **kwargs: Any ) -> Optional[_models.InvoiceSection]: error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.InvoiceSection]] content_type = content_type or "application/json" _json = None _content = None if isinstance(parameters, (IO, bytes)): _content = parameters else: _json = self._serialize.body(parameters, "InvoiceSection") request = build_create_or_update_request( billing_account_name=billing_account_name, billing_profile_name=billing_profile_name, invoice_section_name=invoice_section_name, api_version=api_version, content_type=content_type, json=_json, content=_content, template_url=self._create_or_update_initial.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = None response_headers = {} if response.status_code == 200: deserialized = self._deserialize("InvoiceSection", pipeline_response) if response.status_code == 202: response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) if cls: return cls(pipeline_response, deserialized, response_headers) return deserialized _create_or_update_initial.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoiceSections/{invoiceSectionName}"} # type: ignore @overload def begin_create_or_update( self, billing_account_name: str, billing_profile_name: str, invoice_section_name: str, parameters: _models.InvoiceSection, *, content_type: str = "application/json", **kwargs: Any ) -> LROPoller[_models.InvoiceSection]: """Creates or updates an invoice section. The operation is supported only for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :param invoice_section_name: The ID that uniquely identifies an invoice section. Required. :type invoice_section_name: str :param parameters: The new or updated invoice section. Required. :type parameters: ~azure.mgmt.billing.models.InvoiceSection :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.PollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of LROPoller that returns either InvoiceSection or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.billing.models.InvoiceSection] :raises ~azure.core.exceptions.HttpResponseError: """ @overload def begin_create_or_update( self, billing_account_name: str, billing_profile_name: str, invoice_section_name: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any ) -> LROPoller[_models.InvoiceSection]: """Creates or updates an invoice section. The operation is supported only for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :param invoice_section_name: The ID that uniquely identifies an invoice section. Required. :type invoice_section_name: str :param parameters: The new or updated invoice section. Required. :type parameters: IO :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.PollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of LROPoller that returns either InvoiceSection or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.billing.models.InvoiceSection] :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace def begin_create_or_update( self, billing_account_name: str, billing_profile_name: str, invoice_section_name: str, parameters: Union[_models.InvoiceSection, IO], **kwargs: Any ) -> LROPoller[_models.InvoiceSection]: """Creates or updates an invoice section. The operation is supported only for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :param invoice_section_name: The ID that uniquely identifies an invoice section. Required. :type invoice_section_name: str :param parameters: The new or updated invoice section. Is either a model type or a IO type. Required. :type parameters: ~azure.mgmt.billing.models.InvoiceSection or IO :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. Default value is None. :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.PollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of LROPoller that returns either InvoiceSection or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.billing.models.InvoiceSection] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] cls = kwargs.pop("cls", None) # type: ClsType[_models.InvoiceSection] polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod] lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: raw_result = self._create_or_update_initial( # type: ignore billing_account_name=billing_account_name, billing_profile_name=billing_profile_name, invoice_section_name=invoice_section_name, parameters=parameters, api_version=api_version, content_type=content_type, cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): deserialized = self._deserialize("InvoiceSection", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized if polling is True: polling_method = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) # type: PollingMethod elif polling is False: polling_method = cast(PollingMethod, NoPolling()) else: polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) return LROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_create_or_update.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoiceSections/{invoiceSectionName}"} # type: ignore
0.57523
0.08472
import sys from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, cast, overload from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, map_error, ) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse from azure.core.polling import LROPoller, NoPolling, PollingMethod from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.arm_polling import ARMPolling from .. import models as _models from .._serialization import Serializer from .._vendor import _convert_request, _format_url_section if sys.version_info >= (3, 8): from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports else: from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False def build_list_request(*, expand: Optional[str] = None, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop("template_url", "/providers/Microsoft.Billing/billingAccounts") # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if expand is not None: _params["$expand"] = _SERIALIZER.query("expand", expand, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_get_request(billing_account_name: str, *, expand: Optional[str] = None, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop("template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}") path_format_arguments = { "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if expand is not None: _params["$expand"] = _SERIALIZER.query("expand", expand, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_update_request(billing_account_name: str, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop("template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}") path_format_arguments = { "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers if content_type is not None: _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs) def build_list_invoice_sections_by_create_subscription_permission_request( billing_account_name: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/listInvoiceSectionsWithCreateSubscriptionPermission", ) # pylint: disable=line-too-long path_format_arguments = { "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) class BillingAccountsOperations: """ .. warning:: **DO NOT** instantiate this class directly. Instead, you should access the following operations through :class:`~azure.mgmt.billing.BillingManagementClient`'s :attr:`billing_accounts` attribute. """ models = _models def __init__(self, *args, **kwargs): input_args = list(args) self._client = input_args.pop(0) if input_args else kwargs.pop("client") self._config = input_args.pop(0) if input_args else kwargs.pop("config") self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace def list(self, expand: Optional[str] = None, **kwargs: Any) -> Iterable["_models.BillingAccount"]: """Lists the billing accounts that a user has access to. :param expand: May be used to expand the soldTo, invoice sections and billing profiles. Default value is None. :type expand: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either BillingAccount or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billing.models.BillingAccount] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingAccountListResult] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_request( expand=expand, api_version=api_version, template_url=self.list.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore else: request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request def extract_data(pipeline_response): deserialized = self._deserialize("BillingAccountListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return ItemPaged(get_next, extract_data) list.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts"} # type: ignore @distributed_trace def get(self, billing_account_name: str, expand: Optional[str] = None, **kwargs: Any) -> _models.BillingAccount: """Gets a billing account by its ID. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param expand: May be used to expand the soldTo, invoice sections and billing profiles. Default value is None. :type expand: str :keyword callable cls: A custom type or function that will be passed the direct response :return: BillingAccount or the result of cls(response) :rtype: ~azure.mgmt.billing.models.BillingAccount :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingAccount] request = build_get_request( billing_account_name=billing_account_name, expand=expand, api_version=api_version, template_url=self.get.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize("BillingAccount", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}"} # type: ignore def _update_initial( self, billing_account_name: str, parameters: Union[_models.BillingAccountUpdateRequest, IO], **kwargs: Any ) -> Optional[_models.BillingAccount]: error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.BillingAccount]] content_type = content_type or "application/json" _json = None _content = None if isinstance(parameters, (IO, bytes)): _content = parameters else: _json = self._serialize.body(parameters, "BillingAccountUpdateRequest") request = build_update_request( billing_account_name=billing_account_name, api_version=api_version, content_type=content_type, json=_json, content=_content, template_url=self._update_initial.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = None if response.status_code == 200: deserialized = self._deserialize("BillingAccount", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized _update_initial.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}"} # type: ignore @overload def begin_update( self, billing_account_name: str, parameters: _models.BillingAccountUpdateRequest, *, content_type: str = "application/json", **kwargs: Any ) -> LROPoller[_models.BillingAccount]: """Updates the properties of a billing account. Currently, displayName and address can be updated. The operation is supported only for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param parameters: Request parameters that are provided to the update billing account operation. Required. :type parameters: ~azure.mgmt.billing.models.BillingAccountUpdateRequest :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.PollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of LROPoller that returns either BillingAccount or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.billing.models.BillingAccount] :raises ~azure.core.exceptions.HttpResponseError: """ @overload def begin_update( self, billing_account_name: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any ) -> LROPoller[_models.BillingAccount]: """Updates the properties of a billing account. Currently, displayName and address can be updated. The operation is supported only for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param parameters: Request parameters that are provided to the update billing account operation. Required. :type parameters: IO :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.PollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of LROPoller that returns either BillingAccount or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.billing.models.BillingAccount] :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace def begin_update( self, billing_account_name: str, parameters: Union[_models.BillingAccountUpdateRequest, IO], **kwargs: Any ) -> LROPoller[_models.BillingAccount]: """Updates the properties of a billing account. Currently, displayName and address can be updated. The operation is supported only for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param parameters: Request parameters that are provided to the update billing account operation. Is either a model type or a IO type. Required. :type parameters: ~azure.mgmt.billing.models.BillingAccountUpdateRequest or IO :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. Default value is None. :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.PollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of LROPoller that returns either BillingAccount or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.billing.models.BillingAccount] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingAccount] polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod] lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: raw_result = self._update_initial( # type: ignore billing_account_name=billing_account_name, parameters=parameters, api_version=api_version, content_type=content_type, cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): deserialized = self._deserialize("BillingAccount", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized if polling is True: polling_method = cast( PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs) ) # type: PollingMethod elif polling is False: polling_method = cast(PollingMethod, NoPolling()) else: polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) return LROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_update.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}"} # type: ignore @distributed_trace def list_invoice_sections_by_create_subscription_permission( self, billing_account_name: str, **kwargs: Any ) -> Iterable["_models.InvoiceSectionWithCreateSubPermission"]: """Lists the invoice sections for which the user has permission to create Azure subscriptions. The operation is supported only for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either InvoiceSectionWithCreateSubPermission or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billing.models.InvoiceSectionWithCreateSubPermission] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.InvoiceSectionListWithCreateSubPermissionResult] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_invoice_sections_by_create_subscription_permission_request( billing_account_name=billing_account_name, api_version=api_version, template_url=self.list_invoice_sections_by_create_subscription_permission.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore else: request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request def extract_data(pipeline_response): deserialized = self._deserialize("InvoiceSectionListWithCreateSubPermissionResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return ItemPaged(get_next, extract_data) list_invoice_sections_by_create_subscription_permission.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/listInvoiceSectionsWithCreateSubscriptionPermission"} # type: ignore
azure-mgmt-billing
/azure_mgmt_billing-6.1.0b1-py3-none-any.whl/azure/mgmt/billing/operations/_billing_accounts_operations.py
_billing_accounts_operations.py
import sys from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, cast, overload from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, map_error, ) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse from azure.core.polling import LROPoller, NoPolling, PollingMethod from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.arm_polling import ARMPolling from .. import models as _models from .._serialization import Serializer from .._vendor import _convert_request, _format_url_section if sys.version_info >= (3, 8): from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports else: from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False def build_list_request(*, expand: Optional[str] = None, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop("template_url", "/providers/Microsoft.Billing/billingAccounts") # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if expand is not None: _params["$expand"] = _SERIALIZER.query("expand", expand, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_get_request(billing_account_name: str, *, expand: Optional[str] = None, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop("template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}") path_format_arguments = { "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if expand is not None: _params["$expand"] = _SERIALIZER.query("expand", expand, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_update_request(billing_account_name: str, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop("template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}") path_format_arguments = { "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers if content_type is not None: _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs) def build_list_invoice_sections_by_create_subscription_permission_request( billing_account_name: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/listInvoiceSectionsWithCreateSubscriptionPermission", ) # pylint: disable=line-too-long path_format_arguments = { "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) class BillingAccountsOperations: """ .. warning:: **DO NOT** instantiate this class directly. Instead, you should access the following operations through :class:`~azure.mgmt.billing.BillingManagementClient`'s :attr:`billing_accounts` attribute. """ models = _models def __init__(self, *args, **kwargs): input_args = list(args) self._client = input_args.pop(0) if input_args else kwargs.pop("client") self._config = input_args.pop(0) if input_args else kwargs.pop("config") self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace def list(self, expand: Optional[str] = None, **kwargs: Any) -> Iterable["_models.BillingAccount"]: """Lists the billing accounts that a user has access to. :param expand: May be used to expand the soldTo, invoice sections and billing profiles. Default value is None. :type expand: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either BillingAccount or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billing.models.BillingAccount] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingAccountListResult] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_request( expand=expand, api_version=api_version, template_url=self.list.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore else: request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request def extract_data(pipeline_response): deserialized = self._deserialize("BillingAccountListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return ItemPaged(get_next, extract_data) list.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts"} # type: ignore @distributed_trace def get(self, billing_account_name: str, expand: Optional[str] = None, **kwargs: Any) -> _models.BillingAccount: """Gets a billing account by its ID. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param expand: May be used to expand the soldTo, invoice sections and billing profiles. Default value is None. :type expand: str :keyword callable cls: A custom type or function that will be passed the direct response :return: BillingAccount or the result of cls(response) :rtype: ~azure.mgmt.billing.models.BillingAccount :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingAccount] request = build_get_request( billing_account_name=billing_account_name, expand=expand, api_version=api_version, template_url=self.get.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize("BillingAccount", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}"} # type: ignore def _update_initial( self, billing_account_name: str, parameters: Union[_models.BillingAccountUpdateRequest, IO], **kwargs: Any ) -> Optional[_models.BillingAccount]: error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.BillingAccount]] content_type = content_type or "application/json" _json = None _content = None if isinstance(parameters, (IO, bytes)): _content = parameters else: _json = self._serialize.body(parameters, "BillingAccountUpdateRequest") request = build_update_request( billing_account_name=billing_account_name, api_version=api_version, content_type=content_type, json=_json, content=_content, template_url=self._update_initial.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = None if response.status_code == 200: deserialized = self._deserialize("BillingAccount", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized _update_initial.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}"} # type: ignore @overload def begin_update( self, billing_account_name: str, parameters: _models.BillingAccountUpdateRequest, *, content_type: str = "application/json", **kwargs: Any ) -> LROPoller[_models.BillingAccount]: """Updates the properties of a billing account. Currently, displayName and address can be updated. The operation is supported only for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param parameters: Request parameters that are provided to the update billing account operation. Required. :type parameters: ~azure.mgmt.billing.models.BillingAccountUpdateRequest :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.PollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of LROPoller that returns either BillingAccount or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.billing.models.BillingAccount] :raises ~azure.core.exceptions.HttpResponseError: """ @overload def begin_update( self, billing_account_name: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any ) -> LROPoller[_models.BillingAccount]: """Updates the properties of a billing account. Currently, displayName and address can be updated. The operation is supported only for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param parameters: Request parameters that are provided to the update billing account operation. Required. :type parameters: IO :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.PollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of LROPoller that returns either BillingAccount or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.billing.models.BillingAccount] :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace def begin_update( self, billing_account_name: str, parameters: Union[_models.BillingAccountUpdateRequest, IO], **kwargs: Any ) -> LROPoller[_models.BillingAccount]: """Updates the properties of a billing account. Currently, displayName and address can be updated. The operation is supported only for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param parameters: Request parameters that are provided to the update billing account operation. Is either a model type or a IO type. Required. :type parameters: ~azure.mgmt.billing.models.BillingAccountUpdateRequest or IO :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. Default value is None. :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.PollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of LROPoller that returns either BillingAccount or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.billing.models.BillingAccount] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingAccount] polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod] lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: raw_result = self._update_initial( # type: ignore billing_account_name=billing_account_name, parameters=parameters, api_version=api_version, content_type=content_type, cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): deserialized = self._deserialize("BillingAccount", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized if polling is True: polling_method = cast( PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs) ) # type: PollingMethod elif polling is False: polling_method = cast(PollingMethod, NoPolling()) else: polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) return LROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_update.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}"} # type: ignore @distributed_trace def list_invoice_sections_by_create_subscription_permission( self, billing_account_name: str, **kwargs: Any ) -> Iterable["_models.InvoiceSectionWithCreateSubPermission"]: """Lists the invoice sections for which the user has permission to create Azure subscriptions. The operation is supported only for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either InvoiceSectionWithCreateSubPermission or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billing.models.InvoiceSectionWithCreateSubPermission] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.InvoiceSectionListWithCreateSubPermissionResult] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_invoice_sections_by_create_subscription_permission_request( billing_account_name=billing_account_name, api_version=api_version, template_url=self.list_invoice_sections_by_create_subscription_permission.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore else: request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request def extract_data(pipeline_response): deserialized = self._deserialize("InvoiceSectionListWithCreateSubPermissionResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return ItemPaged(get_next, extract_data) list_invoice_sections_by_create_subscription_permission.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/listInvoiceSectionsWithCreateSubscriptionPermission"} # type: ignore
0.621081
0.086942
import sys from typing import Any, Callable, Dict, Iterable, Optional, TypeVar from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, map_error, ) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models from .._serialization import Serializer from .._vendor import _convert_request, _format_url_section if sys.version_info >= (3, 8): from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports else: from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False def build_list_by_billing_profile_request( billing_account_name: str, billing_profile_name: str, *, search: Optional[str] = None, filter: Optional[str] = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/customers", ) # pylint: disable=line-too-long path_format_arguments = { "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), "billingProfileName": _SERIALIZER.url("billing_profile_name", billing_profile_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if search is not None: _params["$search"] = _SERIALIZER.query("search", search, "str") if filter is not None: _params["$filter"] = _SERIALIZER.query("filter", filter, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_list_by_billing_account_request( billing_account_name: str, *, search: Optional[str] = None, filter: Optional[str] = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop("template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/customers") path_format_arguments = { "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if search is not None: _params["$search"] = _SERIALIZER.query("search", search, "str") if filter is not None: _params["$filter"] = _SERIALIZER.query("filter", filter, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_get_request( billing_account_name: str, customer_name: str, *, expand: Optional[str] = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/customers/{customerName}" ) # pylint: disable=line-too-long path_format_arguments = { "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), "customerName": _SERIALIZER.url("customer_name", customer_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if expand is not None: _params["$expand"] = _SERIALIZER.query("expand", expand, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) class CustomersOperations: """ .. warning:: **DO NOT** instantiate this class directly. Instead, you should access the following operations through :class:`~azure.mgmt.billing.BillingManagementClient`'s :attr:`customers` attribute. """ models = _models def __init__(self, *args, **kwargs): input_args = list(args) self._client = input_args.pop(0) if input_args else kwargs.pop("client") self._config = input_args.pop(0) if input_args else kwargs.pop("config") self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace def list_by_billing_profile( self, billing_account_name: str, billing_profile_name: str, search: Optional[str] = None, filter: Optional[str] = None, **kwargs: Any ) -> Iterable["_models.Customer"]: """Lists the customers that are billed to a billing profile. The operation is supported only for billing accounts with agreement type Microsoft Partner Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :param search: Used for searching customers by their name. Any customer with name containing the search text will be included in the response. Default value is None. :type search: str :param filter: May be used to filter the list of customers. Default value is None. :type filter: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either Customer or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billing.models.Customer] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.CustomerListResult] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_by_billing_profile_request( billing_account_name=billing_account_name, billing_profile_name=billing_profile_name, search=search, filter=filter, api_version=api_version, template_url=self.list_by_billing_profile.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore else: request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request def extract_data(pipeline_response): deserialized = self._deserialize("CustomerListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return ItemPaged(get_next, extract_data) list_by_billing_profile.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/customers"} # type: ignore @distributed_trace def list_by_billing_account( self, billing_account_name: str, search: Optional[str] = None, filter: Optional[str] = None, **kwargs: Any ) -> Iterable["_models.Customer"]: """Lists the customers that are billed to a billing account. The operation is supported only for billing accounts with agreement type Microsoft Partner Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param search: Used for searching customers by their name. Any customer with name containing the search text will be included in the response. Default value is None. :type search: str :param filter: May be used to filter the list of customers. Default value is None. :type filter: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either Customer or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billing.models.Customer] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.CustomerListResult] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_by_billing_account_request( billing_account_name=billing_account_name, search=search, filter=filter, api_version=api_version, template_url=self.list_by_billing_account.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore else: request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request def extract_data(pipeline_response): deserialized = self._deserialize("CustomerListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return ItemPaged(get_next, extract_data) list_by_billing_account.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/customers"} # type: ignore @distributed_trace def get( self, billing_account_name: str, customer_name: str, expand: Optional[str] = None, **kwargs: Any ) -> _models.Customer: """Gets a customer by its ID. The operation is supported only for billing accounts with agreement type Microsoft Partner Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param customer_name: The ID that uniquely identifies a customer. Required. :type customer_name: str :param expand: May be used to expand enabledAzurePlans and resellers. Default value is None. :type expand: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Customer or the result of cls(response) :rtype: ~azure.mgmt.billing.models.Customer :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.Customer] request = build_get_request( billing_account_name=billing_account_name, customer_name=customer_name, expand=expand, api_version=api_version, template_url=self.get.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize("Customer", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/customers/{customerName}"} # type: ignore
azure-mgmt-billing
/azure_mgmt_billing-6.1.0b1-py3-none-any.whl/azure/mgmt/billing/operations/_customers_operations.py
_customers_operations.py
import sys from typing import Any, Callable, Dict, Iterable, Optional, TypeVar from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, map_error, ) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models from .._serialization import Serializer from .._vendor import _convert_request, _format_url_section if sys.version_info >= (3, 8): from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports else: from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False def build_list_by_billing_profile_request( billing_account_name: str, billing_profile_name: str, *, search: Optional[str] = None, filter: Optional[str] = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/customers", ) # pylint: disable=line-too-long path_format_arguments = { "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), "billingProfileName": _SERIALIZER.url("billing_profile_name", billing_profile_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if search is not None: _params["$search"] = _SERIALIZER.query("search", search, "str") if filter is not None: _params["$filter"] = _SERIALIZER.query("filter", filter, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_list_by_billing_account_request( billing_account_name: str, *, search: Optional[str] = None, filter: Optional[str] = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop("template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/customers") path_format_arguments = { "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if search is not None: _params["$search"] = _SERIALIZER.query("search", search, "str") if filter is not None: _params["$filter"] = _SERIALIZER.query("filter", filter, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_get_request( billing_account_name: str, customer_name: str, *, expand: Optional[str] = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/customers/{customerName}" ) # pylint: disable=line-too-long path_format_arguments = { "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), "customerName": _SERIALIZER.url("customer_name", customer_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if expand is not None: _params["$expand"] = _SERIALIZER.query("expand", expand, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) class CustomersOperations: """ .. warning:: **DO NOT** instantiate this class directly. Instead, you should access the following operations through :class:`~azure.mgmt.billing.BillingManagementClient`'s :attr:`customers` attribute. """ models = _models def __init__(self, *args, **kwargs): input_args = list(args) self._client = input_args.pop(0) if input_args else kwargs.pop("client") self._config = input_args.pop(0) if input_args else kwargs.pop("config") self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace def list_by_billing_profile( self, billing_account_name: str, billing_profile_name: str, search: Optional[str] = None, filter: Optional[str] = None, **kwargs: Any ) -> Iterable["_models.Customer"]: """Lists the customers that are billed to a billing profile. The operation is supported only for billing accounts with agreement type Microsoft Partner Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :param search: Used for searching customers by their name. Any customer with name containing the search text will be included in the response. Default value is None. :type search: str :param filter: May be used to filter the list of customers. Default value is None. :type filter: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either Customer or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billing.models.Customer] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.CustomerListResult] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_by_billing_profile_request( billing_account_name=billing_account_name, billing_profile_name=billing_profile_name, search=search, filter=filter, api_version=api_version, template_url=self.list_by_billing_profile.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore else: request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request def extract_data(pipeline_response): deserialized = self._deserialize("CustomerListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return ItemPaged(get_next, extract_data) list_by_billing_profile.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/customers"} # type: ignore @distributed_trace def list_by_billing_account( self, billing_account_name: str, search: Optional[str] = None, filter: Optional[str] = None, **kwargs: Any ) -> Iterable["_models.Customer"]: """Lists the customers that are billed to a billing account. The operation is supported only for billing accounts with agreement type Microsoft Partner Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param search: Used for searching customers by their name. Any customer with name containing the search text will be included in the response. Default value is None. :type search: str :param filter: May be used to filter the list of customers. Default value is None. :type filter: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either Customer or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billing.models.Customer] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.CustomerListResult] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_by_billing_account_request( billing_account_name=billing_account_name, search=search, filter=filter, api_version=api_version, template_url=self.list_by_billing_account.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore else: request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request def extract_data(pipeline_response): deserialized = self._deserialize("CustomerListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return ItemPaged(get_next, extract_data) list_by_billing_account.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/customers"} # type: ignore @distributed_trace def get( self, billing_account_name: str, customer_name: str, expand: Optional[str] = None, **kwargs: Any ) -> _models.Customer: """Gets a customer by its ID. The operation is supported only for billing accounts with agreement type Microsoft Partner Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param customer_name: The ID that uniquely identifies a customer. Required. :type customer_name: str :param expand: May be used to expand enabledAzurePlans and resellers. Default value is None. :type expand: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Customer or the result of cls(response) :rtype: ~azure.mgmt.billing.models.Customer :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.Customer] request = build_get_request( billing_account_name=billing_account_name, customer_name=customer_name, expand=expand, api_version=api_version, template_url=self.get.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize("Customer", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/customers/{customerName}"} # type: ignore
0.604866
0.082438
import sys from typing import Any, Callable, Dict, Iterable, Optional, TypeVar from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, map_error, ) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models from .._serialization import Serializer from .._vendor import _convert_request, _format_url_section if sys.version_info >= (3, 8): from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports else: from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False def build_get_by_billing_account_request( billing_account_name: str, billing_role_assignment_name: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingRoleAssignments/{billingRoleAssignmentName}", ) # pylint: disable=line-too-long path_format_arguments = { "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), "billingRoleAssignmentName": _SERIALIZER.url( "billing_role_assignment_name", billing_role_assignment_name, "str" ), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_delete_by_billing_account_request( billing_account_name: str, billing_role_assignment_name: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingRoleAssignments/{billingRoleAssignmentName}", ) # pylint: disable=line-too-long path_format_arguments = { "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), "billingRoleAssignmentName": _SERIALIZER.url( "billing_role_assignment_name", billing_role_assignment_name, "str" ), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) def build_get_by_invoice_section_request( billing_account_name: str, billing_profile_name: str, invoice_section_name: str, billing_role_assignment_name: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoiceSections/{invoiceSectionName}/billingRoleAssignments/{billingRoleAssignmentName}", ) # pylint: disable=line-too-long path_format_arguments = { "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), "billingProfileName": _SERIALIZER.url("billing_profile_name", billing_profile_name, "str"), "invoiceSectionName": _SERIALIZER.url("invoice_section_name", invoice_section_name, "str"), "billingRoleAssignmentName": _SERIALIZER.url( "billing_role_assignment_name", billing_role_assignment_name, "str" ), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_delete_by_invoice_section_request( billing_account_name: str, billing_profile_name: str, invoice_section_name: str, billing_role_assignment_name: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoiceSections/{invoiceSectionName}/billingRoleAssignments/{billingRoleAssignmentName}", ) # pylint: disable=line-too-long path_format_arguments = { "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), "billingProfileName": _SERIALIZER.url("billing_profile_name", billing_profile_name, "str"), "invoiceSectionName": _SERIALIZER.url("invoice_section_name", invoice_section_name, "str"), "billingRoleAssignmentName": _SERIALIZER.url( "billing_role_assignment_name", billing_role_assignment_name, "str" ), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) def build_get_by_billing_profile_request( billing_account_name: str, billing_profile_name: str, billing_role_assignment_name: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/billingRoleAssignments/{billingRoleAssignmentName}", ) # pylint: disable=line-too-long path_format_arguments = { "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), "billingProfileName": _SERIALIZER.url("billing_profile_name", billing_profile_name, "str"), "billingRoleAssignmentName": _SERIALIZER.url( "billing_role_assignment_name", billing_role_assignment_name, "str" ), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_delete_by_billing_profile_request( billing_account_name: str, billing_profile_name: str, billing_role_assignment_name: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/billingRoleAssignments/{billingRoleAssignmentName}", ) # pylint: disable=line-too-long path_format_arguments = { "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), "billingProfileName": _SERIALIZER.url("billing_profile_name", billing_profile_name, "str"), "billingRoleAssignmentName": _SERIALIZER.url( "billing_role_assignment_name", billing_role_assignment_name, "str" ), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) def build_list_by_billing_account_request(billing_account_name: str, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingRoleAssignments" ) # pylint: disable=line-too-long path_format_arguments = { "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_list_by_invoice_section_request( billing_account_name: str, billing_profile_name: str, invoice_section_name: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoiceSections/{invoiceSectionName}/billingRoleAssignments", ) # pylint: disable=line-too-long path_format_arguments = { "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), "billingProfileName": _SERIALIZER.url("billing_profile_name", billing_profile_name, "str"), "invoiceSectionName": _SERIALIZER.url("invoice_section_name", invoice_section_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_list_by_billing_profile_request( billing_account_name: str, billing_profile_name: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/billingRoleAssignments", ) # pylint: disable=line-too-long path_format_arguments = { "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), "billingProfileName": _SERIALIZER.url("billing_profile_name", billing_profile_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) class BillingRoleAssignmentsOperations: """ .. warning:: **DO NOT** instantiate this class directly. Instead, you should access the following operations through :class:`~azure.mgmt.billing.BillingManagementClient`'s :attr:`billing_role_assignments` attribute. """ models = _models def __init__(self, *args, **kwargs): input_args = list(args) self._client = input_args.pop(0) if input_args else kwargs.pop("client") self._config = input_args.pop(0) if input_args else kwargs.pop("config") self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace def get_by_billing_account( self, billing_account_name: str, billing_role_assignment_name: str, **kwargs: Any ) -> _models.BillingRoleAssignment: """Gets a role assignment for the caller on a billing account. The operation is supported for billing accounts with agreement type Microsoft Partner Agreement or Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_role_assignment_name: The ID that uniquely identifies a role assignment. Required. :type billing_role_assignment_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: BillingRoleAssignment or the result of cls(response) :rtype: ~azure.mgmt.billing.models.BillingRoleAssignment :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingRoleAssignment] request = build_get_by_billing_account_request( billing_account_name=billing_account_name, billing_role_assignment_name=billing_role_assignment_name, api_version=api_version, template_url=self.get_by_billing_account.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize("BillingRoleAssignment", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get_by_billing_account.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingRoleAssignments/{billingRoleAssignmentName}"} # type: ignore @distributed_trace def delete_by_billing_account( self, billing_account_name: str, billing_role_assignment_name: str, **kwargs: Any ) -> _models.BillingRoleAssignment: """Deletes a role assignment for the caller on a billing account. The operation is supported for billing accounts with agreement type Microsoft Partner Agreement or Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_role_assignment_name: The ID that uniquely identifies a role assignment. Required. :type billing_role_assignment_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: BillingRoleAssignment or the result of cls(response) :rtype: ~azure.mgmt.billing.models.BillingRoleAssignment :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingRoleAssignment] request = build_delete_by_billing_account_request( billing_account_name=billing_account_name, billing_role_assignment_name=billing_role_assignment_name, api_version=api_version, template_url=self.delete_by_billing_account.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize("BillingRoleAssignment", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized delete_by_billing_account.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingRoleAssignments/{billingRoleAssignmentName}"} # type: ignore @distributed_trace def get_by_invoice_section( self, billing_account_name: str, billing_profile_name: str, invoice_section_name: str, billing_role_assignment_name: str, **kwargs: Any ) -> _models.BillingRoleAssignment: """Gets a role assignment for the caller on an invoice section. The operation is supported for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :param invoice_section_name: The ID that uniquely identifies an invoice section. Required. :type invoice_section_name: str :param billing_role_assignment_name: The ID that uniquely identifies a role assignment. Required. :type billing_role_assignment_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: BillingRoleAssignment or the result of cls(response) :rtype: ~azure.mgmt.billing.models.BillingRoleAssignment :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingRoleAssignment] request = build_get_by_invoice_section_request( billing_account_name=billing_account_name, billing_profile_name=billing_profile_name, invoice_section_name=invoice_section_name, billing_role_assignment_name=billing_role_assignment_name, api_version=api_version, template_url=self.get_by_invoice_section.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize("BillingRoleAssignment", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get_by_invoice_section.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoiceSections/{invoiceSectionName}/billingRoleAssignments/{billingRoleAssignmentName}"} # type: ignore @distributed_trace def delete_by_invoice_section( self, billing_account_name: str, billing_profile_name: str, invoice_section_name: str, billing_role_assignment_name: str, **kwargs: Any ) -> _models.BillingRoleAssignment: """Deletes a role assignment for the caller on an invoice section. The operation is supported for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :param invoice_section_name: The ID that uniquely identifies an invoice section. Required. :type invoice_section_name: str :param billing_role_assignment_name: The ID that uniquely identifies a role assignment. Required. :type billing_role_assignment_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: BillingRoleAssignment or the result of cls(response) :rtype: ~azure.mgmt.billing.models.BillingRoleAssignment :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingRoleAssignment] request = build_delete_by_invoice_section_request( billing_account_name=billing_account_name, billing_profile_name=billing_profile_name, invoice_section_name=invoice_section_name, billing_role_assignment_name=billing_role_assignment_name, api_version=api_version, template_url=self.delete_by_invoice_section.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize("BillingRoleAssignment", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized delete_by_invoice_section.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoiceSections/{invoiceSectionName}/billingRoleAssignments/{billingRoleAssignmentName}"} # type: ignore @distributed_trace def get_by_billing_profile( self, billing_account_name: str, billing_profile_name: str, billing_role_assignment_name: str, **kwargs: Any ) -> _models.BillingRoleAssignment: """Gets a role assignment for the caller on a billing profile. The operation is supported for billing accounts with agreement type Microsoft Partner Agreement or Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :param billing_role_assignment_name: The ID that uniquely identifies a role assignment. Required. :type billing_role_assignment_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: BillingRoleAssignment or the result of cls(response) :rtype: ~azure.mgmt.billing.models.BillingRoleAssignment :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingRoleAssignment] request = build_get_by_billing_profile_request( billing_account_name=billing_account_name, billing_profile_name=billing_profile_name, billing_role_assignment_name=billing_role_assignment_name, api_version=api_version, template_url=self.get_by_billing_profile.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize("BillingRoleAssignment", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get_by_billing_profile.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/billingRoleAssignments/{billingRoleAssignmentName}"} # type: ignore @distributed_trace def delete_by_billing_profile( self, billing_account_name: str, billing_profile_name: str, billing_role_assignment_name: str, **kwargs: Any ) -> _models.BillingRoleAssignment: """Deletes a role assignment for the caller on a billing profile. The operation is supported for billing accounts with agreement type Microsoft Partner Agreement or Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :param billing_role_assignment_name: The ID that uniquely identifies a role assignment. Required. :type billing_role_assignment_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: BillingRoleAssignment or the result of cls(response) :rtype: ~azure.mgmt.billing.models.BillingRoleAssignment :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingRoleAssignment] request = build_delete_by_billing_profile_request( billing_account_name=billing_account_name, billing_profile_name=billing_profile_name, billing_role_assignment_name=billing_role_assignment_name, api_version=api_version, template_url=self.delete_by_billing_profile.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize("BillingRoleAssignment", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized delete_by_billing_profile.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/billingRoleAssignments/{billingRoleAssignmentName}"} # type: ignore @distributed_trace def list_by_billing_account( self, billing_account_name: str, **kwargs: Any ) -> Iterable["_models.BillingRoleAssignment"]: """Lists the role assignments for the caller on a billing account. The operation is supported for billing accounts with agreement type Microsoft Partner Agreement or Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either BillingRoleAssignment or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billing.models.BillingRoleAssignment] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingRoleAssignmentListResult] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_by_billing_account_request( billing_account_name=billing_account_name, api_version=api_version, template_url=self.list_by_billing_account.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore else: request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request def extract_data(pipeline_response): deserialized = self._deserialize("BillingRoleAssignmentListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return ItemPaged(get_next, extract_data) list_by_billing_account.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingRoleAssignments"} # type: ignore @distributed_trace def list_by_invoice_section( self, billing_account_name: str, billing_profile_name: str, invoice_section_name: str, **kwargs: Any ) -> Iterable["_models.BillingRoleAssignment"]: """Lists the role assignments for the caller on an invoice section. The operation is supported for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :param invoice_section_name: The ID that uniquely identifies an invoice section. Required. :type invoice_section_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either BillingRoleAssignment or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billing.models.BillingRoleAssignment] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingRoleAssignmentListResult] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_by_invoice_section_request( billing_account_name=billing_account_name, billing_profile_name=billing_profile_name, invoice_section_name=invoice_section_name, api_version=api_version, template_url=self.list_by_invoice_section.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore else: request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request def extract_data(pipeline_response): deserialized = self._deserialize("BillingRoleAssignmentListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return ItemPaged(get_next, extract_data) list_by_invoice_section.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoiceSections/{invoiceSectionName}/billingRoleAssignments"} # type: ignore @distributed_trace def list_by_billing_profile( self, billing_account_name: str, billing_profile_name: str, **kwargs: Any ) -> Iterable["_models.BillingRoleAssignment"]: """Lists the role assignments for the caller on a billing profile. The operation is supported for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either BillingRoleAssignment or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billing.models.BillingRoleAssignment] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingRoleAssignmentListResult] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_by_billing_profile_request( billing_account_name=billing_account_name, billing_profile_name=billing_profile_name, api_version=api_version, template_url=self.list_by_billing_profile.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore else: request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request def extract_data(pipeline_response): deserialized = self._deserialize("BillingRoleAssignmentListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return ItemPaged(get_next, extract_data) list_by_billing_profile.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/billingRoleAssignments"} # type: ignore
azure-mgmt-billing
/azure_mgmt_billing-6.1.0b1-py3-none-any.whl/azure/mgmt/billing/operations/_billing_role_assignments_operations.py
_billing_role_assignments_operations.py
import sys from typing import Any, Callable, Dict, Iterable, Optional, TypeVar from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, map_error, ) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models from .._serialization import Serializer from .._vendor import _convert_request, _format_url_section if sys.version_info >= (3, 8): from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports else: from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False def build_get_by_billing_account_request( billing_account_name: str, billing_role_assignment_name: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingRoleAssignments/{billingRoleAssignmentName}", ) # pylint: disable=line-too-long path_format_arguments = { "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), "billingRoleAssignmentName": _SERIALIZER.url( "billing_role_assignment_name", billing_role_assignment_name, "str" ), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_delete_by_billing_account_request( billing_account_name: str, billing_role_assignment_name: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingRoleAssignments/{billingRoleAssignmentName}", ) # pylint: disable=line-too-long path_format_arguments = { "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), "billingRoleAssignmentName": _SERIALIZER.url( "billing_role_assignment_name", billing_role_assignment_name, "str" ), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) def build_get_by_invoice_section_request( billing_account_name: str, billing_profile_name: str, invoice_section_name: str, billing_role_assignment_name: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoiceSections/{invoiceSectionName}/billingRoleAssignments/{billingRoleAssignmentName}", ) # pylint: disable=line-too-long path_format_arguments = { "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), "billingProfileName": _SERIALIZER.url("billing_profile_name", billing_profile_name, "str"), "invoiceSectionName": _SERIALIZER.url("invoice_section_name", invoice_section_name, "str"), "billingRoleAssignmentName": _SERIALIZER.url( "billing_role_assignment_name", billing_role_assignment_name, "str" ), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_delete_by_invoice_section_request( billing_account_name: str, billing_profile_name: str, invoice_section_name: str, billing_role_assignment_name: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoiceSections/{invoiceSectionName}/billingRoleAssignments/{billingRoleAssignmentName}", ) # pylint: disable=line-too-long path_format_arguments = { "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), "billingProfileName": _SERIALIZER.url("billing_profile_name", billing_profile_name, "str"), "invoiceSectionName": _SERIALIZER.url("invoice_section_name", invoice_section_name, "str"), "billingRoleAssignmentName": _SERIALIZER.url( "billing_role_assignment_name", billing_role_assignment_name, "str" ), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) def build_get_by_billing_profile_request( billing_account_name: str, billing_profile_name: str, billing_role_assignment_name: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/billingRoleAssignments/{billingRoleAssignmentName}", ) # pylint: disable=line-too-long path_format_arguments = { "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), "billingProfileName": _SERIALIZER.url("billing_profile_name", billing_profile_name, "str"), "billingRoleAssignmentName": _SERIALIZER.url( "billing_role_assignment_name", billing_role_assignment_name, "str" ), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_delete_by_billing_profile_request( billing_account_name: str, billing_profile_name: str, billing_role_assignment_name: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/billingRoleAssignments/{billingRoleAssignmentName}", ) # pylint: disable=line-too-long path_format_arguments = { "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), "billingProfileName": _SERIALIZER.url("billing_profile_name", billing_profile_name, "str"), "billingRoleAssignmentName": _SERIALIZER.url( "billing_role_assignment_name", billing_role_assignment_name, "str" ), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) def build_list_by_billing_account_request(billing_account_name: str, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingRoleAssignments" ) # pylint: disable=line-too-long path_format_arguments = { "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_list_by_invoice_section_request( billing_account_name: str, billing_profile_name: str, invoice_section_name: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoiceSections/{invoiceSectionName}/billingRoleAssignments", ) # pylint: disable=line-too-long path_format_arguments = { "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), "billingProfileName": _SERIALIZER.url("billing_profile_name", billing_profile_name, "str"), "invoiceSectionName": _SERIALIZER.url("invoice_section_name", invoice_section_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_list_by_billing_profile_request( billing_account_name: str, billing_profile_name: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/billingRoleAssignments", ) # pylint: disable=line-too-long path_format_arguments = { "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), "billingProfileName": _SERIALIZER.url("billing_profile_name", billing_profile_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) class BillingRoleAssignmentsOperations: """ .. warning:: **DO NOT** instantiate this class directly. Instead, you should access the following operations through :class:`~azure.mgmt.billing.BillingManagementClient`'s :attr:`billing_role_assignments` attribute. """ models = _models def __init__(self, *args, **kwargs): input_args = list(args) self._client = input_args.pop(0) if input_args else kwargs.pop("client") self._config = input_args.pop(0) if input_args else kwargs.pop("config") self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace def get_by_billing_account( self, billing_account_name: str, billing_role_assignment_name: str, **kwargs: Any ) -> _models.BillingRoleAssignment: """Gets a role assignment for the caller on a billing account. The operation is supported for billing accounts with agreement type Microsoft Partner Agreement or Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_role_assignment_name: The ID that uniquely identifies a role assignment. Required. :type billing_role_assignment_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: BillingRoleAssignment or the result of cls(response) :rtype: ~azure.mgmt.billing.models.BillingRoleAssignment :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingRoleAssignment] request = build_get_by_billing_account_request( billing_account_name=billing_account_name, billing_role_assignment_name=billing_role_assignment_name, api_version=api_version, template_url=self.get_by_billing_account.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize("BillingRoleAssignment", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get_by_billing_account.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingRoleAssignments/{billingRoleAssignmentName}"} # type: ignore @distributed_trace def delete_by_billing_account( self, billing_account_name: str, billing_role_assignment_name: str, **kwargs: Any ) -> _models.BillingRoleAssignment: """Deletes a role assignment for the caller on a billing account. The operation is supported for billing accounts with agreement type Microsoft Partner Agreement or Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_role_assignment_name: The ID that uniquely identifies a role assignment. Required. :type billing_role_assignment_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: BillingRoleAssignment or the result of cls(response) :rtype: ~azure.mgmt.billing.models.BillingRoleAssignment :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingRoleAssignment] request = build_delete_by_billing_account_request( billing_account_name=billing_account_name, billing_role_assignment_name=billing_role_assignment_name, api_version=api_version, template_url=self.delete_by_billing_account.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize("BillingRoleAssignment", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized delete_by_billing_account.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingRoleAssignments/{billingRoleAssignmentName}"} # type: ignore @distributed_trace def get_by_invoice_section( self, billing_account_name: str, billing_profile_name: str, invoice_section_name: str, billing_role_assignment_name: str, **kwargs: Any ) -> _models.BillingRoleAssignment: """Gets a role assignment for the caller on an invoice section. The operation is supported for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :param invoice_section_name: The ID that uniquely identifies an invoice section. Required. :type invoice_section_name: str :param billing_role_assignment_name: The ID that uniquely identifies a role assignment. Required. :type billing_role_assignment_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: BillingRoleAssignment or the result of cls(response) :rtype: ~azure.mgmt.billing.models.BillingRoleAssignment :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingRoleAssignment] request = build_get_by_invoice_section_request( billing_account_name=billing_account_name, billing_profile_name=billing_profile_name, invoice_section_name=invoice_section_name, billing_role_assignment_name=billing_role_assignment_name, api_version=api_version, template_url=self.get_by_invoice_section.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize("BillingRoleAssignment", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get_by_invoice_section.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoiceSections/{invoiceSectionName}/billingRoleAssignments/{billingRoleAssignmentName}"} # type: ignore @distributed_trace def delete_by_invoice_section( self, billing_account_name: str, billing_profile_name: str, invoice_section_name: str, billing_role_assignment_name: str, **kwargs: Any ) -> _models.BillingRoleAssignment: """Deletes a role assignment for the caller on an invoice section. The operation is supported for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :param invoice_section_name: The ID that uniquely identifies an invoice section. Required. :type invoice_section_name: str :param billing_role_assignment_name: The ID that uniquely identifies a role assignment. Required. :type billing_role_assignment_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: BillingRoleAssignment or the result of cls(response) :rtype: ~azure.mgmt.billing.models.BillingRoleAssignment :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingRoleAssignment] request = build_delete_by_invoice_section_request( billing_account_name=billing_account_name, billing_profile_name=billing_profile_name, invoice_section_name=invoice_section_name, billing_role_assignment_name=billing_role_assignment_name, api_version=api_version, template_url=self.delete_by_invoice_section.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize("BillingRoleAssignment", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized delete_by_invoice_section.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoiceSections/{invoiceSectionName}/billingRoleAssignments/{billingRoleAssignmentName}"} # type: ignore @distributed_trace def get_by_billing_profile( self, billing_account_name: str, billing_profile_name: str, billing_role_assignment_name: str, **kwargs: Any ) -> _models.BillingRoleAssignment: """Gets a role assignment for the caller on a billing profile. The operation is supported for billing accounts with agreement type Microsoft Partner Agreement or Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :param billing_role_assignment_name: The ID that uniquely identifies a role assignment. Required. :type billing_role_assignment_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: BillingRoleAssignment or the result of cls(response) :rtype: ~azure.mgmt.billing.models.BillingRoleAssignment :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingRoleAssignment] request = build_get_by_billing_profile_request( billing_account_name=billing_account_name, billing_profile_name=billing_profile_name, billing_role_assignment_name=billing_role_assignment_name, api_version=api_version, template_url=self.get_by_billing_profile.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize("BillingRoleAssignment", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get_by_billing_profile.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/billingRoleAssignments/{billingRoleAssignmentName}"} # type: ignore @distributed_trace def delete_by_billing_profile( self, billing_account_name: str, billing_profile_name: str, billing_role_assignment_name: str, **kwargs: Any ) -> _models.BillingRoleAssignment: """Deletes a role assignment for the caller on a billing profile. The operation is supported for billing accounts with agreement type Microsoft Partner Agreement or Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :param billing_role_assignment_name: The ID that uniquely identifies a role assignment. Required. :type billing_role_assignment_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: BillingRoleAssignment or the result of cls(response) :rtype: ~azure.mgmt.billing.models.BillingRoleAssignment :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingRoleAssignment] request = build_delete_by_billing_profile_request( billing_account_name=billing_account_name, billing_profile_name=billing_profile_name, billing_role_assignment_name=billing_role_assignment_name, api_version=api_version, template_url=self.delete_by_billing_profile.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize("BillingRoleAssignment", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized delete_by_billing_profile.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/billingRoleAssignments/{billingRoleAssignmentName}"} # type: ignore @distributed_trace def list_by_billing_account( self, billing_account_name: str, **kwargs: Any ) -> Iterable["_models.BillingRoleAssignment"]: """Lists the role assignments for the caller on a billing account. The operation is supported for billing accounts with agreement type Microsoft Partner Agreement or Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either BillingRoleAssignment or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billing.models.BillingRoleAssignment] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingRoleAssignmentListResult] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_by_billing_account_request( billing_account_name=billing_account_name, api_version=api_version, template_url=self.list_by_billing_account.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore else: request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request def extract_data(pipeline_response): deserialized = self._deserialize("BillingRoleAssignmentListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return ItemPaged(get_next, extract_data) list_by_billing_account.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingRoleAssignments"} # type: ignore @distributed_trace def list_by_invoice_section( self, billing_account_name: str, billing_profile_name: str, invoice_section_name: str, **kwargs: Any ) -> Iterable["_models.BillingRoleAssignment"]: """Lists the role assignments for the caller on an invoice section. The operation is supported for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :param invoice_section_name: The ID that uniquely identifies an invoice section. Required. :type invoice_section_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either BillingRoleAssignment or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billing.models.BillingRoleAssignment] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingRoleAssignmentListResult] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_by_invoice_section_request( billing_account_name=billing_account_name, billing_profile_name=billing_profile_name, invoice_section_name=invoice_section_name, api_version=api_version, template_url=self.list_by_invoice_section.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore else: request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request def extract_data(pipeline_response): deserialized = self._deserialize("BillingRoleAssignmentListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return ItemPaged(get_next, extract_data) list_by_invoice_section.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoiceSections/{invoiceSectionName}/billingRoleAssignments"} # type: ignore @distributed_trace def list_by_billing_profile( self, billing_account_name: str, billing_profile_name: str, **kwargs: Any ) -> Iterable["_models.BillingRoleAssignment"]: """Lists the role assignments for the caller on a billing profile. The operation is supported for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either BillingRoleAssignment or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billing.models.BillingRoleAssignment] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingRoleAssignmentListResult] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_by_billing_profile_request( billing_account_name=billing_account_name, billing_profile_name=billing_profile_name, api_version=api_version, template_url=self.list_by_billing_profile.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore else: request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request def extract_data(pipeline_response): deserialized = self._deserialize("BillingRoleAssignmentListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return ItemPaged(get_next, extract_data) list_by_billing_profile.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/billingRoleAssignments"} # type: ignore
0.503174
0.078784
import sys from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, overload from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, map_error, ) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models from .._serialization import Serializer from .._vendor import _convert_request, _format_url_section if sys.version_info >= (3, 8): from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports else: from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False def build_list_by_customer_request(billing_account_name: str, customer_name: str, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/customers/{customerName}/products", ) # pylint: disable=line-too-long path_format_arguments = { "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), "customerName": _SERIALIZER.url("customer_name", customer_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_list_by_billing_account_request( billing_account_name: str, *, filter: Optional[str] = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop("template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/products") path_format_arguments = { "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if filter is not None: _params["$filter"] = _SERIALIZER.query("filter", filter, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_list_by_billing_profile_request( billing_account_name: str, billing_profile_name: str, *, filter: Optional[str] = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/products", ) # pylint: disable=line-too-long path_format_arguments = { "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), "billingProfileName": _SERIALIZER.url("billing_profile_name", billing_profile_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if filter is not None: _params["$filter"] = _SERIALIZER.query("filter", filter, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_list_by_invoice_section_request( billing_account_name: str, billing_profile_name: str, invoice_section_name: str, *, filter: Optional[str] = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoiceSections/{invoiceSectionName}/products", ) # pylint: disable=line-too-long path_format_arguments = { "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), "billingProfileName": _SERIALIZER.url("billing_profile_name", billing_profile_name, "str"), "invoiceSectionName": _SERIALIZER.url("invoice_section_name", invoice_section_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if filter is not None: _params["$filter"] = _SERIALIZER.query("filter", filter, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_get_request(billing_account_name: str, product_name: str, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/products/{productName}" ) # pylint: disable=line-too-long path_format_arguments = { "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), "productName": _SERIALIZER.url("product_name", product_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_update_request(billing_account_name: str, product_name: str, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/products/{productName}" ) # pylint: disable=line-too-long path_format_arguments = { "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), "productName": _SERIALIZER.url("product_name", product_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers if content_type is not None: _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs) def build_move_request(billing_account_name: str, product_name: str, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/products/{productName}/move" ) # pylint: disable=line-too-long path_format_arguments = { "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), "productName": _SERIALIZER.url("product_name", product_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers if content_type is not None: _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) def build_validate_move_request(billing_account_name: str, product_name: str, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/products/{productName}/validateMoveEligibility", ) # pylint: disable=line-too-long path_format_arguments = { "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), "productName": _SERIALIZER.url("product_name", product_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers if content_type is not None: _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) class ProductsOperations: """ .. warning:: **DO NOT** instantiate this class directly. Instead, you should access the following operations through :class:`~azure.mgmt.billing.BillingManagementClient`'s :attr:`products` attribute. """ models = _models def __init__(self, *args, **kwargs): input_args = list(args) self._client = input_args.pop(0) if input_args else kwargs.pop("client") self._config = input_args.pop(0) if input_args else kwargs.pop("config") self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace def list_by_customer( self, billing_account_name: str, customer_name: str, **kwargs: Any ) -> Iterable["_models.Product"]: """Lists the products for a customer. These don't include products billed based on usage.The operation is supported only for billing accounts with agreement type Microsoft Partner Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param customer_name: The ID that uniquely identifies a customer. Required. :type customer_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either Product or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billing.models.Product] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.ProductsListResult] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_by_customer_request( billing_account_name=billing_account_name, customer_name=customer_name, api_version=api_version, template_url=self.list_by_customer.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore else: request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request def extract_data(pipeline_response): deserialized = self._deserialize("ProductsListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return ItemPaged(get_next, extract_data) list_by_customer.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/customers/{customerName}/products"} # type: ignore @distributed_trace def list_by_billing_account( self, billing_account_name: str, filter: Optional[str] = None, **kwargs: Any ) -> Iterable["_models.Product"]: """Lists the products for a billing account. These don't include products billed based on usage. The operation is supported for billing accounts with agreement type Microsoft Customer Agreement or Microsoft Partner Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param filter: May be used to filter by product type. The filter supports 'eq', 'lt', 'gt', 'le', 'ge', and 'and'. It does not currently support 'ne', 'or', or 'not'. Tag filter is a key value pair string where key and value are separated by a colon (:). Default value is None. :type filter: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either Product or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billing.models.Product] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.ProductsListResult] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_by_billing_account_request( billing_account_name=billing_account_name, filter=filter, api_version=api_version, template_url=self.list_by_billing_account.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore else: request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request def extract_data(pipeline_response): deserialized = self._deserialize("ProductsListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return ItemPaged(get_next, extract_data) list_by_billing_account.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/products"} # type: ignore @distributed_trace def list_by_billing_profile( self, billing_account_name: str, billing_profile_name: str, filter: Optional[str] = None, **kwargs: Any ) -> Iterable["_models.Product"]: """Lists the products for a billing profile. These don't include products billed based on usage. The operation is supported for billing accounts with agreement type Microsoft Customer Agreement or Microsoft Partner Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :param filter: May be used to filter by product type. The filter supports 'eq', 'lt', 'gt', 'le', 'ge', and 'and'. It does not currently support 'ne', 'or', or 'not'. Tag filter is a key value pair string where key and value are separated by a colon (:). Default value is None. :type filter: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either Product or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billing.models.Product] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.ProductsListResult] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_by_billing_profile_request( billing_account_name=billing_account_name, billing_profile_name=billing_profile_name, filter=filter, api_version=api_version, template_url=self.list_by_billing_profile.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore else: request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request def extract_data(pipeline_response): deserialized = self._deserialize("ProductsListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return ItemPaged(get_next, extract_data) list_by_billing_profile.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/products"} # type: ignore @distributed_trace def list_by_invoice_section( self, billing_account_name: str, billing_profile_name: str, invoice_section_name: str, filter: Optional[str] = None, **kwargs: Any ) -> Iterable["_models.Product"]: """Lists the products for an invoice section. These don't include products billed based on usage. The operation is supported only for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :param invoice_section_name: The ID that uniquely identifies an invoice section. Required. :type invoice_section_name: str :param filter: May be used to filter by product type. The filter supports 'eq', 'lt', 'gt', 'le', 'ge', and 'and'. It does not currently support 'ne', 'or', or 'not'. Tag filter is a key value pair string where key and value are separated by a colon (:). Default value is None. :type filter: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either Product or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billing.models.Product] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.ProductsListResult] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_by_invoice_section_request( billing_account_name=billing_account_name, billing_profile_name=billing_profile_name, invoice_section_name=invoice_section_name, filter=filter, api_version=api_version, template_url=self.list_by_invoice_section.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore else: request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request def extract_data(pipeline_response): deserialized = self._deserialize("ProductsListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return ItemPaged(get_next, extract_data) list_by_invoice_section.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoiceSections/{invoiceSectionName}/products"} # type: ignore @distributed_trace def get(self, billing_account_name: str, product_name: str, **kwargs: Any) -> _models.Product: """Gets a product by ID. The operation is supported only for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param product_name: The ID that uniquely identifies a product. Required. :type product_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Product or the result of cls(response) :rtype: ~azure.mgmt.billing.models.Product :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.Product] request = build_get_request( billing_account_name=billing_account_name, product_name=product_name, api_version=api_version, template_url=self.get.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize("Product", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/products/{productName}"} # type: ignore @overload def update( self, billing_account_name: str, product_name: str, parameters: _models.Product, *, content_type: str = "application/json", **kwargs: Any ) -> _models.Product: """Updates the properties of a Product. Currently, auto renew can be updated. The operation is supported only for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param product_name: The ID that uniquely identifies a product. Required. :type product_name: str :param parameters: Request parameters that are provided to the update product operation. Required. :type parameters: ~azure.mgmt.billing.models.Product :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Product or the result of cls(response) :rtype: ~azure.mgmt.billing.models.Product :raises ~azure.core.exceptions.HttpResponseError: """ @overload def update( self, billing_account_name: str, product_name: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any ) -> _models.Product: """Updates the properties of a Product. Currently, auto renew can be updated. The operation is supported only for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param product_name: The ID that uniquely identifies a product. Required. :type product_name: str :param parameters: Request parameters that are provided to the update product operation. Required. :type parameters: IO :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Product or the result of cls(response) :rtype: ~azure.mgmt.billing.models.Product :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace def update( self, billing_account_name: str, product_name: str, parameters: Union[_models.Product, IO], **kwargs: Any ) -> _models.Product: """Updates the properties of a Product. Currently, auto renew can be updated. The operation is supported only for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param product_name: The ID that uniquely identifies a product. Required. :type product_name: str :param parameters: Request parameters that are provided to the update product operation. Is either a model type or a IO type. Required. :type parameters: ~azure.mgmt.billing.models.Product or IO :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. Default value is None. :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Product or the result of cls(response) :rtype: ~azure.mgmt.billing.models.Product :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] cls = kwargs.pop("cls", None) # type: ClsType[_models.Product] content_type = content_type or "application/json" _json = None _content = None if isinstance(parameters, (IO, bytes)): _content = parameters else: _json = self._serialize.body(parameters, "Product") request = build_update_request( billing_account_name=billing_account_name, product_name=product_name, api_version=api_version, content_type=content_type, json=_json, content=_content, template_url=self.update.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize("Product", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized update.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/products/{productName}"} # type: ignore @overload def move( self, billing_account_name: str, product_name: str, parameters: _models.TransferProductRequestProperties, *, content_type: str = "application/json", **kwargs: Any ) -> Optional[_models.Product]: """Moves a product's charges to a new invoice section. The new invoice section must belong to the same billing profile as the existing invoice section. This operation is supported only for products that are purchased with a recurring charge and for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param product_name: The ID that uniquely identifies a product. Required. :type product_name: str :param parameters: Request parameters that are provided to the move product operation. Required. :type parameters: ~azure.mgmt.billing.models.TransferProductRequestProperties :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Product or None or the result of cls(response) :rtype: ~azure.mgmt.billing.models.Product or None :raises ~azure.core.exceptions.HttpResponseError: """ @overload def move( self, billing_account_name: str, product_name: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any ) -> Optional[_models.Product]: """Moves a product's charges to a new invoice section. The new invoice section must belong to the same billing profile as the existing invoice section. This operation is supported only for products that are purchased with a recurring charge and for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param product_name: The ID that uniquely identifies a product. Required. :type product_name: str :param parameters: Request parameters that are provided to the move product operation. Required. :type parameters: IO :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Product or None or the result of cls(response) :rtype: ~azure.mgmt.billing.models.Product or None :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace def move( self, billing_account_name: str, product_name: str, parameters: Union[_models.TransferProductRequestProperties, IO], **kwargs: Any ) -> Optional[_models.Product]: """Moves a product's charges to a new invoice section. The new invoice section must belong to the same billing profile as the existing invoice section. This operation is supported only for products that are purchased with a recurring charge and for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param product_name: The ID that uniquely identifies a product. Required. :type product_name: str :param parameters: Request parameters that are provided to the move product operation. Is either a model type or a IO type. Required. :type parameters: ~azure.mgmt.billing.models.TransferProductRequestProperties or IO :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. Default value is None. :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Product or None or the result of cls(response) :rtype: ~azure.mgmt.billing.models.Product or None :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.Product]] content_type = content_type or "application/json" _json = None _content = None if isinstance(parameters, (IO, bytes)): _content = parameters else: _json = self._serialize.body(parameters, "TransferProductRequestProperties") request = build_move_request( billing_account_name=billing_account_name, product_name=product_name, api_version=api_version, content_type=content_type, json=_json, content=_content, template_url=self.move.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = None response_headers = {} if response.status_code == 200: deserialized = self._deserialize("Product", pipeline_response) if response.status_code == 202: response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) if cls: return cls(pipeline_response, deserialized, response_headers) return deserialized move.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/products/{productName}/move"} # type: ignore @overload def validate_move( self, billing_account_name: str, product_name: str, parameters: _models.TransferProductRequestProperties, *, content_type: str = "application/json", **kwargs: Any ) -> _models.ValidateProductTransferEligibilityResult: """Validates if a product's charges can be moved to a new invoice section. This operation is supported only for products that are purchased with a recurring charge and for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param product_name: The ID that uniquely identifies a product. Required. :type product_name: str :param parameters: Request parameters that are provided to the validate move eligibility operation. Required. :type parameters: ~azure.mgmt.billing.models.TransferProductRequestProperties :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: ValidateProductTransferEligibilityResult or the result of cls(response) :rtype: ~azure.mgmt.billing.models.ValidateProductTransferEligibilityResult :raises ~azure.core.exceptions.HttpResponseError: """ @overload def validate_move( self, billing_account_name: str, product_name: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any ) -> _models.ValidateProductTransferEligibilityResult: """Validates if a product's charges can be moved to a new invoice section. This operation is supported only for products that are purchased with a recurring charge and for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param product_name: The ID that uniquely identifies a product. Required. :type product_name: str :param parameters: Request parameters that are provided to the validate move eligibility operation. Required. :type parameters: IO :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: ValidateProductTransferEligibilityResult or the result of cls(response) :rtype: ~azure.mgmt.billing.models.ValidateProductTransferEligibilityResult :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace def validate_move( self, billing_account_name: str, product_name: str, parameters: Union[_models.TransferProductRequestProperties, IO], **kwargs: Any ) -> _models.ValidateProductTransferEligibilityResult: """Validates if a product's charges can be moved to a new invoice section. This operation is supported only for products that are purchased with a recurring charge and for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param product_name: The ID that uniquely identifies a product. Required. :type product_name: str :param parameters: Request parameters that are provided to the validate move eligibility operation. Is either a model type or a IO type. Required. :type parameters: ~azure.mgmt.billing.models.TransferProductRequestProperties or IO :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. Default value is None. :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: ValidateProductTransferEligibilityResult or the result of cls(response) :rtype: ~azure.mgmt.billing.models.ValidateProductTransferEligibilityResult :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] cls = kwargs.pop("cls", None) # type: ClsType[_models.ValidateProductTransferEligibilityResult] content_type = content_type or "application/json" _json = None _content = None if isinstance(parameters, (IO, bytes)): _content = parameters else: _json = self._serialize.body(parameters, "TransferProductRequestProperties") request = build_validate_move_request( billing_account_name=billing_account_name, product_name=product_name, api_version=api_version, content_type=content_type, json=_json, content=_content, template_url=self.validate_move.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize("ValidateProductTransferEligibilityResult", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized validate_move.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/products/{productName}/validateMoveEligibility"} # type: ignore
azure-mgmt-billing
/azure_mgmt_billing-6.1.0b1-py3-none-any.whl/azure/mgmt/billing/operations/_products_operations.py
_products_operations.py
import sys from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, overload from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, map_error, ) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models from .._serialization import Serializer from .._vendor import _convert_request, _format_url_section if sys.version_info >= (3, 8): from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports else: from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False def build_list_by_customer_request(billing_account_name: str, customer_name: str, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/customers/{customerName}/products", ) # pylint: disable=line-too-long path_format_arguments = { "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), "customerName": _SERIALIZER.url("customer_name", customer_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_list_by_billing_account_request( billing_account_name: str, *, filter: Optional[str] = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop("template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/products") path_format_arguments = { "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if filter is not None: _params["$filter"] = _SERIALIZER.query("filter", filter, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_list_by_billing_profile_request( billing_account_name: str, billing_profile_name: str, *, filter: Optional[str] = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/products", ) # pylint: disable=line-too-long path_format_arguments = { "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), "billingProfileName": _SERIALIZER.url("billing_profile_name", billing_profile_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if filter is not None: _params["$filter"] = _SERIALIZER.query("filter", filter, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_list_by_invoice_section_request( billing_account_name: str, billing_profile_name: str, invoice_section_name: str, *, filter: Optional[str] = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoiceSections/{invoiceSectionName}/products", ) # pylint: disable=line-too-long path_format_arguments = { "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), "billingProfileName": _SERIALIZER.url("billing_profile_name", billing_profile_name, "str"), "invoiceSectionName": _SERIALIZER.url("invoice_section_name", invoice_section_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if filter is not None: _params["$filter"] = _SERIALIZER.query("filter", filter, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_get_request(billing_account_name: str, product_name: str, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/products/{productName}" ) # pylint: disable=line-too-long path_format_arguments = { "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), "productName": _SERIALIZER.url("product_name", product_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_update_request(billing_account_name: str, product_name: str, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/products/{productName}" ) # pylint: disable=line-too-long path_format_arguments = { "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), "productName": _SERIALIZER.url("product_name", product_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers if content_type is not None: _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs) def build_move_request(billing_account_name: str, product_name: str, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/products/{productName}/move" ) # pylint: disable=line-too-long path_format_arguments = { "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), "productName": _SERIALIZER.url("product_name", product_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers if content_type is not None: _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) def build_validate_move_request(billing_account_name: str, product_name: str, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/products/{productName}/validateMoveEligibility", ) # pylint: disable=line-too-long path_format_arguments = { "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), "productName": _SERIALIZER.url("product_name", product_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers if content_type is not None: _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) class ProductsOperations: """ .. warning:: **DO NOT** instantiate this class directly. Instead, you should access the following operations through :class:`~azure.mgmt.billing.BillingManagementClient`'s :attr:`products` attribute. """ models = _models def __init__(self, *args, **kwargs): input_args = list(args) self._client = input_args.pop(0) if input_args else kwargs.pop("client") self._config = input_args.pop(0) if input_args else kwargs.pop("config") self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace def list_by_customer( self, billing_account_name: str, customer_name: str, **kwargs: Any ) -> Iterable["_models.Product"]: """Lists the products for a customer. These don't include products billed based on usage.The operation is supported only for billing accounts with agreement type Microsoft Partner Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param customer_name: The ID that uniquely identifies a customer. Required. :type customer_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either Product or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billing.models.Product] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.ProductsListResult] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_by_customer_request( billing_account_name=billing_account_name, customer_name=customer_name, api_version=api_version, template_url=self.list_by_customer.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore else: request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request def extract_data(pipeline_response): deserialized = self._deserialize("ProductsListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return ItemPaged(get_next, extract_data) list_by_customer.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/customers/{customerName}/products"} # type: ignore @distributed_trace def list_by_billing_account( self, billing_account_name: str, filter: Optional[str] = None, **kwargs: Any ) -> Iterable["_models.Product"]: """Lists the products for a billing account. These don't include products billed based on usage. The operation is supported for billing accounts with agreement type Microsoft Customer Agreement or Microsoft Partner Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param filter: May be used to filter by product type. The filter supports 'eq', 'lt', 'gt', 'le', 'ge', and 'and'. It does not currently support 'ne', 'or', or 'not'. Tag filter is a key value pair string where key and value are separated by a colon (:). Default value is None. :type filter: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either Product or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billing.models.Product] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.ProductsListResult] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_by_billing_account_request( billing_account_name=billing_account_name, filter=filter, api_version=api_version, template_url=self.list_by_billing_account.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore else: request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request def extract_data(pipeline_response): deserialized = self._deserialize("ProductsListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return ItemPaged(get_next, extract_data) list_by_billing_account.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/products"} # type: ignore @distributed_trace def list_by_billing_profile( self, billing_account_name: str, billing_profile_name: str, filter: Optional[str] = None, **kwargs: Any ) -> Iterable["_models.Product"]: """Lists the products for a billing profile. These don't include products billed based on usage. The operation is supported for billing accounts with agreement type Microsoft Customer Agreement or Microsoft Partner Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :param filter: May be used to filter by product type. The filter supports 'eq', 'lt', 'gt', 'le', 'ge', and 'and'. It does not currently support 'ne', 'or', or 'not'. Tag filter is a key value pair string where key and value are separated by a colon (:). Default value is None. :type filter: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either Product or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billing.models.Product] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.ProductsListResult] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_by_billing_profile_request( billing_account_name=billing_account_name, billing_profile_name=billing_profile_name, filter=filter, api_version=api_version, template_url=self.list_by_billing_profile.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore else: request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request def extract_data(pipeline_response): deserialized = self._deserialize("ProductsListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return ItemPaged(get_next, extract_data) list_by_billing_profile.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/products"} # type: ignore @distributed_trace def list_by_invoice_section( self, billing_account_name: str, billing_profile_name: str, invoice_section_name: str, filter: Optional[str] = None, **kwargs: Any ) -> Iterable["_models.Product"]: """Lists the products for an invoice section. These don't include products billed based on usage. The operation is supported only for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :param invoice_section_name: The ID that uniquely identifies an invoice section. Required. :type invoice_section_name: str :param filter: May be used to filter by product type. The filter supports 'eq', 'lt', 'gt', 'le', 'ge', and 'and'. It does not currently support 'ne', 'or', or 'not'. Tag filter is a key value pair string where key and value are separated by a colon (:). Default value is None. :type filter: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either Product or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billing.models.Product] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.ProductsListResult] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_by_invoice_section_request( billing_account_name=billing_account_name, billing_profile_name=billing_profile_name, invoice_section_name=invoice_section_name, filter=filter, api_version=api_version, template_url=self.list_by_invoice_section.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore else: request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request def extract_data(pipeline_response): deserialized = self._deserialize("ProductsListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return ItemPaged(get_next, extract_data) list_by_invoice_section.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoiceSections/{invoiceSectionName}/products"} # type: ignore @distributed_trace def get(self, billing_account_name: str, product_name: str, **kwargs: Any) -> _models.Product: """Gets a product by ID. The operation is supported only for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param product_name: The ID that uniquely identifies a product. Required. :type product_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Product or the result of cls(response) :rtype: ~azure.mgmt.billing.models.Product :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.Product] request = build_get_request( billing_account_name=billing_account_name, product_name=product_name, api_version=api_version, template_url=self.get.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize("Product", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/products/{productName}"} # type: ignore @overload def update( self, billing_account_name: str, product_name: str, parameters: _models.Product, *, content_type: str = "application/json", **kwargs: Any ) -> _models.Product: """Updates the properties of a Product. Currently, auto renew can be updated. The operation is supported only for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param product_name: The ID that uniquely identifies a product. Required. :type product_name: str :param parameters: Request parameters that are provided to the update product operation. Required. :type parameters: ~azure.mgmt.billing.models.Product :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Product or the result of cls(response) :rtype: ~azure.mgmt.billing.models.Product :raises ~azure.core.exceptions.HttpResponseError: """ @overload def update( self, billing_account_name: str, product_name: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any ) -> _models.Product: """Updates the properties of a Product. Currently, auto renew can be updated. The operation is supported only for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param product_name: The ID that uniquely identifies a product. Required. :type product_name: str :param parameters: Request parameters that are provided to the update product operation. Required. :type parameters: IO :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Product or the result of cls(response) :rtype: ~azure.mgmt.billing.models.Product :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace def update( self, billing_account_name: str, product_name: str, parameters: Union[_models.Product, IO], **kwargs: Any ) -> _models.Product: """Updates the properties of a Product. Currently, auto renew can be updated. The operation is supported only for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param product_name: The ID that uniquely identifies a product. Required. :type product_name: str :param parameters: Request parameters that are provided to the update product operation. Is either a model type or a IO type. Required. :type parameters: ~azure.mgmt.billing.models.Product or IO :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. Default value is None. :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Product or the result of cls(response) :rtype: ~azure.mgmt.billing.models.Product :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] cls = kwargs.pop("cls", None) # type: ClsType[_models.Product] content_type = content_type or "application/json" _json = None _content = None if isinstance(parameters, (IO, bytes)): _content = parameters else: _json = self._serialize.body(parameters, "Product") request = build_update_request( billing_account_name=billing_account_name, product_name=product_name, api_version=api_version, content_type=content_type, json=_json, content=_content, template_url=self.update.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize("Product", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized update.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/products/{productName}"} # type: ignore @overload def move( self, billing_account_name: str, product_name: str, parameters: _models.TransferProductRequestProperties, *, content_type: str = "application/json", **kwargs: Any ) -> Optional[_models.Product]: """Moves a product's charges to a new invoice section. The new invoice section must belong to the same billing profile as the existing invoice section. This operation is supported only for products that are purchased with a recurring charge and for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param product_name: The ID that uniquely identifies a product. Required. :type product_name: str :param parameters: Request parameters that are provided to the move product operation. Required. :type parameters: ~azure.mgmt.billing.models.TransferProductRequestProperties :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Product or None or the result of cls(response) :rtype: ~azure.mgmt.billing.models.Product or None :raises ~azure.core.exceptions.HttpResponseError: """ @overload def move( self, billing_account_name: str, product_name: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any ) -> Optional[_models.Product]: """Moves a product's charges to a new invoice section. The new invoice section must belong to the same billing profile as the existing invoice section. This operation is supported only for products that are purchased with a recurring charge and for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param product_name: The ID that uniquely identifies a product. Required. :type product_name: str :param parameters: Request parameters that are provided to the move product operation. Required. :type parameters: IO :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Product or None or the result of cls(response) :rtype: ~azure.mgmt.billing.models.Product or None :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace def move( self, billing_account_name: str, product_name: str, parameters: Union[_models.TransferProductRequestProperties, IO], **kwargs: Any ) -> Optional[_models.Product]: """Moves a product's charges to a new invoice section. The new invoice section must belong to the same billing profile as the existing invoice section. This operation is supported only for products that are purchased with a recurring charge and for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param product_name: The ID that uniquely identifies a product. Required. :type product_name: str :param parameters: Request parameters that are provided to the move product operation. Is either a model type or a IO type. Required. :type parameters: ~azure.mgmt.billing.models.TransferProductRequestProperties or IO :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. Default value is None. :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Product or None or the result of cls(response) :rtype: ~azure.mgmt.billing.models.Product or None :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.Product]] content_type = content_type or "application/json" _json = None _content = None if isinstance(parameters, (IO, bytes)): _content = parameters else: _json = self._serialize.body(parameters, "TransferProductRequestProperties") request = build_move_request( billing_account_name=billing_account_name, product_name=product_name, api_version=api_version, content_type=content_type, json=_json, content=_content, template_url=self.move.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = None response_headers = {} if response.status_code == 200: deserialized = self._deserialize("Product", pipeline_response) if response.status_code == 202: response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) if cls: return cls(pipeline_response, deserialized, response_headers) return deserialized move.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/products/{productName}/move"} # type: ignore @overload def validate_move( self, billing_account_name: str, product_name: str, parameters: _models.TransferProductRequestProperties, *, content_type: str = "application/json", **kwargs: Any ) -> _models.ValidateProductTransferEligibilityResult: """Validates if a product's charges can be moved to a new invoice section. This operation is supported only for products that are purchased with a recurring charge and for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param product_name: The ID that uniquely identifies a product. Required. :type product_name: str :param parameters: Request parameters that are provided to the validate move eligibility operation. Required. :type parameters: ~azure.mgmt.billing.models.TransferProductRequestProperties :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: ValidateProductTransferEligibilityResult or the result of cls(response) :rtype: ~azure.mgmt.billing.models.ValidateProductTransferEligibilityResult :raises ~azure.core.exceptions.HttpResponseError: """ @overload def validate_move( self, billing_account_name: str, product_name: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any ) -> _models.ValidateProductTransferEligibilityResult: """Validates if a product's charges can be moved to a new invoice section. This operation is supported only for products that are purchased with a recurring charge and for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param product_name: The ID that uniquely identifies a product. Required. :type product_name: str :param parameters: Request parameters that are provided to the validate move eligibility operation. Required. :type parameters: IO :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: ValidateProductTransferEligibilityResult or the result of cls(response) :rtype: ~azure.mgmt.billing.models.ValidateProductTransferEligibilityResult :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace def validate_move( self, billing_account_name: str, product_name: str, parameters: Union[_models.TransferProductRequestProperties, IO], **kwargs: Any ) -> _models.ValidateProductTransferEligibilityResult: """Validates if a product's charges can be moved to a new invoice section. This operation is supported only for products that are purchased with a recurring charge and for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param product_name: The ID that uniquely identifies a product. Required. :type product_name: str :param parameters: Request parameters that are provided to the validate move eligibility operation. Is either a model type or a IO type. Required. :type parameters: ~azure.mgmt.billing.models.TransferProductRequestProperties or IO :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. Default value is None. :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: ValidateProductTransferEligibilityResult or the result of cls(response) :rtype: ~azure.mgmt.billing.models.ValidateProductTransferEligibilityResult :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] cls = kwargs.pop("cls", None) # type: ClsType[_models.ValidateProductTransferEligibilityResult] content_type = content_type or "application/json" _json = None _content = None if isinstance(parameters, (IO, bytes)): _content = parameters else: _json = self._serialize.body(parameters, "TransferProductRequestProperties") request = build_validate_move_request( billing_account_name=billing_account_name, product_name=product_name, api_version=api_version, content_type=content_type, json=_json, content=_content, template_url=self.validate_move.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize("ValidateProductTransferEligibilityResult", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized validate_move.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/products/{productName}/validateMoveEligibility"} # type: ignore
0.573201
0.08698
import sys from typing import Any, Callable, Dict, Iterable, Optional, TypeVar from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, map_error, ) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models from .._serialization import Serializer from .._vendor import _convert_request, _format_url_section if sys.version_info >= (3, 8): from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports else: from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False def build_get_by_billing_account_request( billing_account_name: str, billing_role_definition_name: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingRoleDefinitions/{billingRoleDefinitionName}", ) # pylint: disable=line-too-long path_format_arguments = { "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), "billingRoleDefinitionName": _SERIALIZER.url( "billing_role_definition_name", billing_role_definition_name, "str" ), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_get_by_invoice_section_request( billing_account_name: str, billing_profile_name: str, invoice_section_name: str, billing_role_definition_name: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoiceSections/{invoiceSectionName}/billingRoleDefinitions/{billingRoleDefinitionName}", ) # pylint: disable=line-too-long path_format_arguments = { "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), "billingProfileName": _SERIALIZER.url("billing_profile_name", billing_profile_name, "str"), "invoiceSectionName": _SERIALIZER.url("invoice_section_name", invoice_section_name, "str"), "billingRoleDefinitionName": _SERIALIZER.url( "billing_role_definition_name", billing_role_definition_name, "str" ), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_get_by_billing_profile_request( billing_account_name: str, billing_profile_name: str, billing_role_definition_name: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/billingRoleDefinitions/{billingRoleDefinitionName}", ) # pylint: disable=line-too-long path_format_arguments = { "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), "billingProfileName": _SERIALIZER.url("billing_profile_name", billing_profile_name, "str"), "billingRoleDefinitionName": _SERIALIZER.url( "billing_role_definition_name", billing_role_definition_name, "str" ), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_list_by_billing_account_request(billing_account_name: str, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingRoleDefinitions" ) # pylint: disable=line-too-long path_format_arguments = { "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_list_by_invoice_section_request( billing_account_name: str, billing_profile_name: str, invoice_section_name: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoiceSections/{invoiceSectionName}/billingRoleDefinitions", ) # pylint: disable=line-too-long path_format_arguments = { "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), "billingProfileName": _SERIALIZER.url("billing_profile_name", billing_profile_name, "str"), "invoiceSectionName": _SERIALIZER.url("invoice_section_name", invoice_section_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_list_by_billing_profile_request( billing_account_name: str, billing_profile_name: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/billingRoleDefinitions", ) # pylint: disable=line-too-long path_format_arguments = { "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), "billingProfileName": _SERIALIZER.url("billing_profile_name", billing_profile_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) class BillingRoleDefinitionsOperations: """ .. warning:: **DO NOT** instantiate this class directly. Instead, you should access the following operations through :class:`~azure.mgmt.billing.BillingManagementClient`'s :attr:`billing_role_definitions` attribute. """ models = _models def __init__(self, *args, **kwargs): input_args = list(args) self._client = input_args.pop(0) if input_args else kwargs.pop("client") self._config = input_args.pop(0) if input_args else kwargs.pop("config") self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace def get_by_billing_account( self, billing_account_name: str, billing_role_definition_name: str, **kwargs: Any ) -> _models.BillingRoleDefinition: """Gets the definition for a role on a billing account. The operation is supported for billing accounts with agreement type Microsoft Partner Agreement or Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_role_definition_name: The ID that uniquely identifies a role definition. Required. :type billing_role_definition_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: BillingRoleDefinition or the result of cls(response) :rtype: ~azure.mgmt.billing.models.BillingRoleDefinition :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingRoleDefinition] request = build_get_by_billing_account_request( billing_account_name=billing_account_name, billing_role_definition_name=billing_role_definition_name, api_version=api_version, template_url=self.get_by_billing_account.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize("BillingRoleDefinition", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get_by_billing_account.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingRoleDefinitions/{billingRoleDefinitionName}"} # type: ignore @distributed_trace def get_by_invoice_section( self, billing_account_name: str, billing_profile_name: str, invoice_section_name: str, billing_role_definition_name: str, **kwargs: Any ) -> _models.BillingRoleDefinition: """Gets the definition for a role on an invoice section. The operation is supported only for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :param invoice_section_name: The ID that uniquely identifies an invoice section. Required. :type invoice_section_name: str :param billing_role_definition_name: The ID that uniquely identifies a role definition. Required. :type billing_role_definition_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: BillingRoleDefinition or the result of cls(response) :rtype: ~azure.mgmt.billing.models.BillingRoleDefinition :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingRoleDefinition] request = build_get_by_invoice_section_request( billing_account_name=billing_account_name, billing_profile_name=billing_profile_name, invoice_section_name=invoice_section_name, billing_role_definition_name=billing_role_definition_name, api_version=api_version, template_url=self.get_by_invoice_section.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize("BillingRoleDefinition", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get_by_invoice_section.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoiceSections/{invoiceSectionName}/billingRoleDefinitions/{billingRoleDefinitionName}"} # type: ignore @distributed_trace def get_by_billing_profile( self, billing_account_name: str, billing_profile_name: str, billing_role_definition_name: str, **kwargs: Any ) -> _models.BillingRoleDefinition: """Gets the definition for a role on a billing profile. The operation is supported for billing accounts with agreement type Microsoft Partner Agreement or Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :param billing_role_definition_name: The ID that uniquely identifies a role definition. Required. :type billing_role_definition_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: BillingRoleDefinition or the result of cls(response) :rtype: ~azure.mgmt.billing.models.BillingRoleDefinition :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingRoleDefinition] request = build_get_by_billing_profile_request( billing_account_name=billing_account_name, billing_profile_name=billing_profile_name, billing_role_definition_name=billing_role_definition_name, api_version=api_version, template_url=self.get_by_billing_profile.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize("BillingRoleDefinition", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get_by_billing_profile.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/billingRoleDefinitions/{billingRoleDefinitionName}"} # type: ignore @distributed_trace def list_by_billing_account( self, billing_account_name: str, **kwargs: Any ) -> Iterable["_models.BillingRoleDefinition"]: """Lists the role definitions for a billing account. The operation is supported for billing accounts with agreement type Microsoft Partner Agreement or Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either BillingRoleDefinition or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billing.models.BillingRoleDefinition] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingRoleDefinitionListResult] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_by_billing_account_request( billing_account_name=billing_account_name, api_version=api_version, template_url=self.list_by_billing_account.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore else: request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request def extract_data(pipeline_response): deserialized = self._deserialize("BillingRoleDefinitionListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return ItemPaged(get_next, extract_data) list_by_billing_account.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingRoleDefinitions"} # type: ignore @distributed_trace def list_by_invoice_section( self, billing_account_name: str, billing_profile_name: str, invoice_section_name: str, **kwargs: Any ) -> Iterable["_models.BillingRoleDefinition"]: """Lists the role definitions for an invoice section. The operation is supported for billing accounts with agreement type Microsoft Partner Agreement or Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :param invoice_section_name: The ID that uniquely identifies an invoice section. Required. :type invoice_section_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either BillingRoleDefinition or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billing.models.BillingRoleDefinition] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingRoleDefinitionListResult] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_by_invoice_section_request( billing_account_name=billing_account_name, billing_profile_name=billing_profile_name, invoice_section_name=invoice_section_name, api_version=api_version, template_url=self.list_by_invoice_section.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore else: request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request def extract_data(pipeline_response): deserialized = self._deserialize("BillingRoleDefinitionListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return ItemPaged(get_next, extract_data) list_by_invoice_section.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoiceSections/{invoiceSectionName}/billingRoleDefinitions"} # type: ignore @distributed_trace def list_by_billing_profile( self, billing_account_name: str, billing_profile_name: str, **kwargs: Any ) -> Iterable["_models.BillingRoleDefinition"]: """Lists the role definitions for a billing profile. The operation is supported for billing accounts with agreement type Microsoft Partner Agreement or Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either BillingRoleDefinition or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billing.models.BillingRoleDefinition] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingRoleDefinitionListResult] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_by_billing_profile_request( billing_account_name=billing_account_name, billing_profile_name=billing_profile_name, api_version=api_version, template_url=self.list_by_billing_profile.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore else: request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request def extract_data(pipeline_response): deserialized = self._deserialize("BillingRoleDefinitionListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return ItemPaged(get_next, extract_data) list_by_billing_profile.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/billingRoleDefinitions"} # type: ignore
azure-mgmt-billing
/azure_mgmt_billing-6.1.0b1-py3-none-any.whl/azure/mgmt/billing/operations/_billing_role_definitions_operations.py
_billing_role_definitions_operations.py
import sys from typing import Any, Callable, Dict, Iterable, Optional, TypeVar from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, map_error, ) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models from .._serialization import Serializer from .._vendor import _convert_request, _format_url_section if sys.version_info >= (3, 8): from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports else: from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False def build_get_by_billing_account_request( billing_account_name: str, billing_role_definition_name: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingRoleDefinitions/{billingRoleDefinitionName}", ) # pylint: disable=line-too-long path_format_arguments = { "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), "billingRoleDefinitionName": _SERIALIZER.url( "billing_role_definition_name", billing_role_definition_name, "str" ), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_get_by_invoice_section_request( billing_account_name: str, billing_profile_name: str, invoice_section_name: str, billing_role_definition_name: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoiceSections/{invoiceSectionName}/billingRoleDefinitions/{billingRoleDefinitionName}", ) # pylint: disable=line-too-long path_format_arguments = { "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), "billingProfileName": _SERIALIZER.url("billing_profile_name", billing_profile_name, "str"), "invoiceSectionName": _SERIALIZER.url("invoice_section_name", invoice_section_name, "str"), "billingRoleDefinitionName": _SERIALIZER.url( "billing_role_definition_name", billing_role_definition_name, "str" ), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_get_by_billing_profile_request( billing_account_name: str, billing_profile_name: str, billing_role_definition_name: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/billingRoleDefinitions/{billingRoleDefinitionName}", ) # pylint: disable=line-too-long path_format_arguments = { "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), "billingProfileName": _SERIALIZER.url("billing_profile_name", billing_profile_name, "str"), "billingRoleDefinitionName": _SERIALIZER.url( "billing_role_definition_name", billing_role_definition_name, "str" ), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_list_by_billing_account_request(billing_account_name: str, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingRoleDefinitions" ) # pylint: disable=line-too-long path_format_arguments = { "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_list_by_invoice_section_request( billing_account_name: str, billing_profile_name: str, invoice_section_name: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoiceSections/{invoiceSectionName}/billingRoleDefinitions", ) # pylint: disable=line-too-long path_format_arguments = { "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), "billingProfileName": _SERIALIZER.url("billing_profile_name", billing_profile_name, "str"), "invoiceSectionName": _SERIALIZER.url("invoice_section_name", invoice_section_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_list_by_billing_profile_request( billing_account_name: str, billing_profile_name: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/billingRoleDefinitions", ) # pylint: disable=line-too-long path_format_arguments = { "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), "billingProfileName": _SERIALIZER.url("billing_profile_name", billing_profile_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) class BillingRoleDefinitionsOperations: """ .. warning:: **DO NOT** instantiate this class directly. Instead, you should access the following operations through :class:`~azure.mgmt.billing.BillingManagementClient`'s :attr:`billing_role_definitions` attribute. """ models = _models def __init__(self, *args, **kwargs): input_args = list(args) self._client = input_args.pop(0) if input_args else kwargs.pop("client") self._config = input_args.pop(0) if input_args else kwargs.pop("config") self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace def get_by_billing_account( self, billing_account_name: str, billing_role_definition_name: str, **kwargs: Any ) -> _models.BillingRoleDefinition: """Gets the definition for a role on a billing account. The operation is supported for billing accounts with agreement type Microsoft Partner Agreement or Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_role_definition_name: The ID that uniquely identifies a role definition. Required. :type billing_role_definition_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: BillingRoleDefinition or the result of cls(response) :rtype: ~azure.mgmt.billing.models.BillingRoleDefinition :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingRoleDefinition] request = build_get_by_billing_account_request( billing_account_name=billing_account_name, billing_role_definition_name=billing_role_definition_name, api_version=api_version, template_url=self.get_by_billing_account.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize("BillingRoleDefinition", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get_by_billing_account.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingRoleDefinitions/{billingRoleDefinitionName}"} # type: ignore @distributed_trace def get_by_invoice_section( self, billing_account_name: str, billing_profile_name: str, invoice_section_name: str, billing_role_definition_name: str, **kwargs: Any ) -> _models.BillingRoleDefinition: """Gets the definition for a role on an invoice section. The operation is supported only for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :param invoice_section_name: The ID that uniquely identifies an invoice section. Required. :type invoice_section_name: str :param billing_role_definition_name: The ID that uniquely identifies a role definition. Required. :type billing_role_definition_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: BillingRoleDefinition or the result of cls(response) :rtype: ~azure.mgmt.billing.models.BillingRoleDefinition :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingRoleDefinition] request = build_get_by_invoice_section_request( billing_account_name=billing_account_name, billing_profile_name=billing_profile_name, invoice_section_name=invoice_section_name, billing_role_definition_name=billing_role_definition_name, api_version=api_version, template_url=self.get_by_invoice_section.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize("BillingRoleDefinition", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get_by_invoice_section.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoiceSections/{invoiceSectionName}/billingRoleDefinitions/{billingRoleDefinitionName}"} # type: ignore @distributed_trace def get_by_billing_profile( self, billing_account_name: str, billing_profile_name: str, billing_role_definition_name: str, **kwargs: Any ) -> _models.BillingRoleDefinition: """Gets the definition for a role on a billing profile. The operation is supported for billing accounts with agreement type Microsoft Partner Agreement or Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :param billing_role_definition_name: The ID that uniquely identifies a role definition. Required. :type billing_role_definition_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: BillingRoleDefinition or the result of cls(response) :rtype: ~azure.mgmt.billing.models.BillingRoleDefinition :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingRoleDefinition] request = build_get_by_billing_profile_request( billing_account_name=billing_account_name, billing_profile_name=billing_profile_name, billing_role_definition_name=billing_role_definition_name, api_version=api_version, template_url=self.get_by_billing_profile.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize("BillingRoleDefinition", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get_by_billing_profile.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/billingRoleDefinitions/{billingRoleDefinitionName}"} # type: ignore @distributed_trace def list_by_billing_account( self, billing_account_name: str, **kwargs: Any ) -> Iterable["_models.BillingRoleDefinition"]: """Lists the role definitions for a billing account. The operation is supported for billing accounts with agreement type Microsoft Partner Agreement or Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either BillingRoleDefinition or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billing.models.BillingRoleDefinition] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingRoleDefinitionListResult] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_by_billing_account_request( billing_account_name=billing_account_name, api_version=api_version, template_url=self.list_by_billing_account.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore else: request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request def extract_data(pipeline_response): deserialized = self._deserialize("BillingRoleDefinitionListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return ItemPaged(get_next, extract_data) list_by_billing_account.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingRoleDefinitions"} # type: ignore @distributed_trace def list_by_invoice_section( self, billing_account_name: str, billing_profile_name: str, invoice_section_name: str, **kwargs: Any ) -> Iterable["_models.BillingRoleDefinition"]: """Lists the role definitions for an invoice section. The operation is supported for billing accounts with agreement type Microsoft Partner Agreement or Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :param invoice_section_name: The ID that uniquely identifies an invoice section. Required. :type invoice_section_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either BillingRoleDefinition or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billing.models.BillingRoleDefinition] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingRoleDefinitionListResult] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_by_invoice_section_request( billing_account_name=billing_account_name, billing_profile_name=billing_profile_name, invoice_section_name=invoice_section_name, api_version=api_version, template_url=self.list_by_invoice_section.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore else: request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request def extract_data(pipeline_response): deserialized = self._deserialize("BillingRoleDefinitionListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return ItemPaged(get_next, extract_data) list_by_invoice_section.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoiceSections/{invoiceSectionName}/billingRoleDefinitions"} # type: ignore @distributed_trace def list_by_billing_profile( self, billing_account_name: str, billing_profile_name: str, **kwargs: Any ) -> Iterable["_models.BillingRoleDefinition"]: """Lists the role definitions for a billing profile. The operation is supported for billing accounts with agreement type Microsoft Partner Agreement or Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either BillingRoleDefinition or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billing.models.BillingRoleDefinition] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingRoleDefinitionListResult] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_by_billing_profile_request( billing_account_name=billing_account_name, billing_profile_name=billing_profile_name, api_version=api_version, template_url=self.list_by_billing_profile.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore else: request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request def extract_data(pipeline_response): deserialized = self._deserialize("BillingRoleDefinitionListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return ItemPaged(get_next, extract_data) list_by_billing_profile.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/billingRoleDefinitions"} # type: ignore
0.493409
0.10079
import sys from typing import Any, Callable, Dict, Iterable, Optional, TypeVar from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, map_error, ) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models from .._serialization import Serializer from .._vendor import _convert_request, _format_url_section if sys.version_info >= (3, 8): from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports else: from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False def build_list_by_invoice_request(billing_account_name: str, invoice_name: str, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/invoices/{invoiceName}/transactions", ) # pylint: disable=line-too-long path_format_arguments = { "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), "invoiceName": _SERIALIZER.url("invoice_name", invoice_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) class TransactionsOperations: """ .. warning:: **DO NOT** instantiate this class directly. Instead, you should access the following operations through :class:`~azure.mgmt.billing.BillingManagementClient`'s :attr:`transactions` attribute. """ models = _models def __init__(self, *args, **kwargs): input_args = list(args) self._client = input_args.pop(0) if input_args else kwargs.pop("client") self._config = input_args.pop(0) if input_args else kwargs.pop("config") self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace def list_by_invoice( self, billing_account_name: str, invoice_name: str, **kwargs: Any ) -> Iterable["_models.Transaction"]: """Lists the transactions for an invoice. Transactions include purchases, refunds and Azure usage charges. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param invoice_name: The ID that uniquely identifies an invoice. Required. :type invoice_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either Transaction or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billing.models.Transaction] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.TransactionListResult] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_by_invoice_request( billing_account_name=billing_account_name, invoice_name=invoice_name, api_version=api_version, template_url=self.list_by_invoice.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore else: request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request def extract_data(pipeline_response): deserialized = self._deserialize("TransactionListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return ItemPaged(get_next, extract_data) list_by_invoice.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/invoices/{invoiceName}/transactions"} # type: ignore
azure-mgmt-billing
/azure_mgmt_billing-6.1.0b1-py3-none-any.whl/azure/mgmt/billing/operations/_transactions_operations.py
_transactions_operations.py
import sys from typing import Any, Callable, Dict, Iterable, Optional, TypeVar from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, map_error, ) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models from .._serialization import Serializer from .._vendor import _convert_request, _format_url_section if sys.version_info >= (3, 8): from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports else: from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False def build_list_by_invoice_request(billing_account_name: str, invoice_name: str, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/invoices/{invoiceName}/transactions", ) # pylint: disable=line-too-long path_format_arguments = { "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), "invoiceName": _SERIALIZER.url("invoice_name", invoice_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) class TransactionsOperations: """ .. warning:: **DO NOT** instantiate this class directly. Instead, you should access the following operations through :class:`~azure.mgmt.billing.BillingManagementClient`'s :attr:`transactions` attribute. """ models = _models def __init__(self, *args, **kwargs): input_args = list(args) self._client = input_args.pop(0) if input_args else kwargs.pop("client") self._config = input_args.pop(0) if input_args else kwargs.pop("config") self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace def list_by_invoice( self, billing_account_name: str, invoice_name: str, **kwargs: Any ) -> Iterable["_models.Transaction"]: """Lists the transactions for an invoice. Transactions include purchases, refunds and Azure usage charges. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param invoice_name: The ID that uniquely identifies an invoice. Required. :type invoice_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either Transaction or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billing.models.Transaction] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.TransactionListResult] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_by_invoice_request( billing_account_name=billing_account_name, invoice_name=invoice_name, api_version=api_version, template_url=self.list_by_invoice.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore else: request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request def extract_data(pipeline_response): deserialized = self._deserialize("TransactionListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return ItemPaged(get_next, extract_data) list_by_invoice.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/invoices/{invoiceName}/transactions"} # type: ignore
0.622689
0.081923
import sys from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, cast, overload from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, map_error, ) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse from azure.core.polling import LROPoller, NoPolling, PollingMethod from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.arm_polling import ARMPolling from .. import models as _models from .._serialization import Serializer from .._vendor import _convert_request, _format_url_section if sys.version_info >= (3, 8): from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports else: from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False def build_list_by_customer_request(billing_account_name: str, customer_name: str, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/customers/{customerName}/billingSubscriptions", ) # pylint: disable=line-too-long path_format_arguments = { "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), "customerName": _SERIALIZER.url("customer_name", customer_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_list_by_billing_account_request(billing_account_name: str, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingSubscriptions" ) # pylint: disable=line-too-long path_format_arguments = { "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_list_by_billing_profile_request( billing_account_name: str, billing_profile_name: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/billingSubscriptions", ) # pylint: disable=line-too-long path_format_arguments = { "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), "billingProfileName": _SERIALIZER.url("billing_profile_name", billing_profile_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_list_by_invoice_section_request( billing_account_name: str, billing_profile_name: str, invoice_section_name: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoiceSections/{invoiceSectionName}/billingSubscriptions", ) # pylint: disable=line-too-long path_format_arguments = { "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), "billingProfileName": _SERIALIZER.url("billing_profile_name", billing_profile_name, "str"), "invoiceSectionName": _SERIALIZER.url("invoice_section_name", invoice_section_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_get_request(billing_account_name: str, subscription_id: str, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingSubscriptions/{subscriptionId}", ) # pylint: disable=line-too-long path_format_arguments = { "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_update_request(billing_account_name: str, subscription_id: str, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingSubscriptions/{subscriptionId}", ) # pylint: disable=line-too-long path_format_arguments = { "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers if content_type is not None: _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs) def build_move_request(billing_account_name: str, subscription_id: str, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingSubscriptions/{subscriptionId}/move", ) # pylint: disable=line-too-long path_format_arguments = { "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers if content_type is not None: _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) def build_validate_move_request(billing_account_name: str, subscription_id: str, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingSubscriptions/{subscriptionId}/validateMoveEligibility", ) # pylint: disable=line-too-long path_format_arguments = { "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers if content_type is not None: _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) class BillingSubscriptionsOperations: """ .. warning:: **DO NOT** instantiate this class directly. Instead, you should access the following operations through :class:`~azure.mgmt.billing.BillingManagementClient`'s :attr:`billing_subscriptions` attribute. """ models = _models def __init__(self, *args, **kwargs): input_args = list(args) self._client = input_args.pop(0) if input_args else kwargs.pop("client") self._config = input_args.pop(0) if input_args else kwargs.pop("config") self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace def list_by_customer( self, billing_account_name: str, customer_name: str, **kwargs: Any ) -> Iterable["_models.BillingSubscription"]: """Lists the subscriptions for a customer. The operation is supported only for billing accounts with agreement type Microsoft Partner Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param customer_name: The ID that uniquely identifies a customer. Required. :type customer_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either BillingSubscription or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billing.models.BillingSubscription] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingSubscriptionsListResult] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_by_customer_request( billing_account_name=billing_account_name, customer_name=customer_name, api_version=api_version, template_url=self.list_by_customer.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore else: request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request def extract_data(pipeline_response): deserialized = self._deserialize("BillingSubscriptionsListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return ItemPaged(get_next, extract_data) list_by_customer.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/customers/{customerName}/billingSubscriptions"} # type: ignore @distributed_trace def list_by_billing_account( self, billing_account_name: str, **kwargs: Any ) -> Iterable["_models.BillingSubscription"]: """Lists the subscriptions for a billing account. The operation is supported for billing accounts with agreement type Microsoft Customer Agreement or Microsoft Partner Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either BillingSubscription or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billing.models.BillingSubscription] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingSubscriptionsListResult] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_by_billing_account_request( billing_account_name=billing_account_name, api_version=api_version, template_url=self.list_by_billing_account.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore else: request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request def extract_data(pipeline_response): deserialized = self._deserialize("BillingSubscriptionsListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return ItemPaged(get_next, extract_data) list_by_billing_account.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingSubscriptions"} # type: ignore @distributed_trace def list_by_billing_profile( self, billing_account_name: str, billing_profile_name: str, **kwargs: Any ) -> Iterable["_models.BillingSubscription"]: """Lists the subscriptions that are billed to a billing profile. The operation is supported for billing accounts with agreement type Microsoft Customer Agreement or Microsoft Partner Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either BillingSubscription or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billing.models.BillingSubscription] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingSubscriptionsListResult] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_by_billing_profile_request( billing_account_name=billing_account_name, billing_profile_name=billing_profile_name, api_version=api_version, template_url=self.list_by_billing_profile.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore else: request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request def extract_data(pipeline_response): deserialized = self._deserialize("BillingSubscriptionsListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return ItemPaged(get_next, extract_data) list_by_billing_profile.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/billingSubscriptions"} # type: ignore @distributed_trace def list_by_invoice_section( self, billing_account_name: str, billing_profile_name: str, invoice_section_name: str, **kwargs: Any ) -> Iterable["_models.BillingSubscription"]: """Lists the subscriptions that are billed to an invoice section. The operation is supported only for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :param invoice_section_name: The ID that uniquely identifies an invoice section. Required. :type invoice_section_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either BillingSubscription or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billing.models.BillingSubscription] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingSubscriptionsListResult] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_by_invoice_section_request( billing_account_name=billing_account_name, billing_profile_name=billing_profile_name, invoice_section_name=invoice_section_name, api_version=api_version, template_url=self.list_by_invoice_section.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore else: request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request def extract_data(pipeline_response): deserialized = self._deserialize("BillingSubscriptionsListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return ItemPaged(get_next, extract_data) list_by_invoice_section.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoiceSections/{invoiceSectionName}/billingSubscriptions"} # type: ignore @distributed_trace def get(self, billing_account_name: str, **kwargs: Any) -> _models.BillingSubscription: """Gets a subscription by its ID. The operation is supported for billing accounts with agreement type Microsoft Customer Agreement and Microsoft Partner Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: BillingSubscription or the result of cls(response) :rtype: ~azure.mgmt.billing.models.BillingSubscription :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingSubscription] request = build_get_request( billing_account_name=billing_account_name, subscription_id=self._config.subscription_id, api_version=api_version, template_url=self.get.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize("BillingSubscription", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingSubscriptions/{subscriptionId}"} # type: ignore @overload def update( self, billing_account_name: str, parameters: _models.BillingSubscription, *, content_type: str = "application/json", **kwargs: Any ) -> _models.BillingSubscription: """Updates the properties of a billing subscription. Currently, cost center can be updated. The operation is supported only for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param parameters: Request parameters that are provided to the update billing subscription operation. Required. :type parameters: ~azure.mgmt.billing.models.BillingSubscription :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: BillingSubscription or the result of cls(response) :rtype: ~azure.mgmt.billing.models.BillingSubscription :raises ~azure.core.exceptions.HttpResponseError: """ @overload def update( self, billing_account_name: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any ) -> _models.BillingSubscription: """Updates the properties of a billing subscription. Currently, cost center can be updated. The operation is supported only for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param parameters: Request parameters that are provided to the update billing subscription operation. Required. :type parameters: IO :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: BillingSubscription or the result of cls(response) :rtype: ~azure.mgmt.billing.models.BillingSubscription :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace def update( self, billing_account_name: str, parameters: Union[_models.BillingSubscription, IO], **kwargs: Any ) -> _models.BillingSubscription: """Updates the properties of a billing subscription. Currently, cost center can be updated. The operation is supported only for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param parameters: Request parameters that are provided to the update billing subscription operation. Is either a model type or a IO type. Required. :type parameters: ~azure.mgmt.billing.models.BillingSubscription or IO :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. Default value is None. :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: BillingSubscription or the result of cls(response) :rtype: ~azure.mgmt.billing.models.BillingSubscription :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingSubscription] content_type = content_type or "application/json" _json = None _content = None if isinstance(parameters, (IO, bytes)): _content = parameters else: _json = self._serialize.body(parameters, "BillingSubscription") request = build_update_request( billing_account_name=billing_account_name, subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, content=_content, template_url=self.update.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize("BillingSubscription", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized update.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingSubscriptions/{subscriptionId}"} # type: ignore def _move_initial( self, billing_account_name: str, parameters: Union[_models.TransferBillingSubscriptionRequestProperties, IO], **kwargs: Any ) -> Optional[_models.BillingSubscription]: error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.BillingSubscription]] content_type = content_type or "application/json" _json = None _content = None if isinstance(parameters, (IO, bytes)): _content = parameters else: _json = self._serialize.body(parameters, "TransferBillingSubscriptionRequestProperties") request = build_move_request( billing_account_name=billing_account_name, subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, content=_content, template_url=self._move_initial.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = None response_headers = {} if response.status_code == 200: deserialized = self._deserialize("BillingSubscription", pipeline_response) if response.status_code == 202: response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) if cls: return cls(pipeline_response, deserialized, response_headers) return deserialized _move_initial.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingSubscriptions/{subscriptionId}/move"} # type: ignore @overload def begin_move( self, billing_account_name: str, parameters: _models.TransferBillingSubscriptionRequestProperties, *, content_type: str = "application/json", **kwargs: Any ) -> LROPoller[_models.BillingSubscription]: """Moves a subscription's charges to a new invoice section. The new invoice section must belong to the same billing profile as the existing invoice section. This operation is supported for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param parameters: Request parameters that are provided to the move subscription operation. Required. :type parameters: ~azure.mgmt.billing.models.TransferBillingSubscriptionRequestProperties :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.PollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of LROPoller that returns either BillingSubscription or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.billing.models.BillingSubscription] :raises ~azure.core.exceptions.HttpResponseError: """ @overload def begin_move( self, billing_account_name: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any ) -> LROPoller[_models.BillingSubscription]: """Moves a subscription's charges to a new invoice section. The new invoice section must belong to the same billing profile as the existing invoice section. This operation is supported for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param parameters: Request parameters that are provided to the move subscription operation. Required. :type parameters: IO :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.PollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of LROPoller that returns either BillingSubscription or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.billing.models.BillingSubscription] :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace def begin_move( self, billing_account_name: str, parameters: Union[_models.TransferBillingSubscriptionRequestProperties, IO], **kwargs: Any ) -> LROPoller[_models.BillingSubscription]: """Moves a subscription's charges to a new invoice section. The new invoice section must belong to the same billing profile as the existing invoice section. This operation is supported for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param parameters: Request parameters that are provided to the move subscription operation. Is either a model type or a IO type. Required. :type parameters: ~azure.mgmt.billing.models.TransferBillingSubscriptionRequestProperties or IO :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. Default value is None. :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.PollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of LROPoller that returns either BillingSubscription or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.billing.models.BillingSubscription] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingSubscription] polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod] lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: raw_result = self._move_initial( # type: ignore billing_account_name=billing_account_name, parameters=parameters, api_version=api_version, content_type=content_type, cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): deserialized = self._deserialize("BillingSubscription", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized if polling is True: polling_method = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) # type: PollingMethod elif polling is False: polling_method = cast(PollingMethod, NoPolling()) else: polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) return LROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_move.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingSubscriptions/{subscriptionId}/move"} # type: ignore @overload def validate_move( self, billing_account_name: str, parameters: _models.TransferBillingSubscriptionRequestProperties, *, content_type: str = "application/json", **kwargs: Any ) -> _models.ValidateSubscriptionTransferEligibilityResult: """Validates if a subscription's charges can be moved to a new invoice section. This operation is supported for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param parameters: Request parameters that are provided to the validate move eligibility operation. Required. :type parameters: ~azure.mgmt.billing.models.TransferBillingSubscriptionRequestProperties :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: ValidateSubscriptionTransferEligibilityResult or the result of cls(response) :rtype: ~azure.mgmt.billing.models.ValidateSubscriptionTransferEligibilityResult :raises ~azure.core.exceptions.HttpResponseError: """ @overload def validate_move( self, billing_account_name: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any ) -> _models.ValidateSubscriptionTransferEligibilityResult: """Validates if a subscription's charges can be moved to a new invoice section. This operation is supported for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param parameters: Request parameters that are provided to the validate move eligibility operation. Required. :type parameters: IO :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: ValidateSubscriptionTransferEligibilityResult or the result of cls(response) :rtype: ~azure.mgmt.billing.models.ValidateSubscriptionTransferEligibilityResult :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace def validate_move( self, billing_account_name: str, parameters: Union[_models.TransferBillingSubscriptionRequestProperties, IO], **kwargs: Any ) -> _models.ValidateSubscriptionTransferEligibilityResult: """Validates if a subscription's charges can be moved to a new invoice section. This operation is supported for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param parameters: Request parameters that are provided to the validate move eligibility operation. Is either a model type or a IO type. Required. :type parameters: ~azure.mgmt.billing.models.TransferBillingSubscriptionRequestProperties or IO :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. Default value is None. :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: ValidateSubscriptionTransferEligibilityResult or the result of cls(response) :rtype: ~azure.mgmt.billing.models.ValidateSubscriptionTransferEligibilityResult :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] cls = kwargs.pop("cls", None) # type: ClsType[_models.ValidateSubscriptionTransferEligibilityResult] content_type = content_type or "application/json" _json = None _content = None if isinstance(parameters, (IO, bytes)): _content = parameters else: _json = self._serialize.body(parameters, "TransferBillingSubscriptionRequestProperties") request = build_validate_move_request( billing_account_name=billing_account_name, subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, content=_content, template_url=self.validate_move.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize("ValidateSubscriptionTransferEligibilityResult", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized validate_move.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingSubscriptions/{subscriptionId}/validateMoveEligibility"} # type: ignore
azure-mgmt-billing
/azure_mgmt_billing-6.1.0b1-py3-none-any.whl/azure/mgmt/billing/operations/_billing_subscriptions_operations.py
_billing_subscriptions_operations.py
import sys from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, cast, overload from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, map_error, ) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse from azure.core.polling import LROPoller, NoPolling, PollingMethod from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.arm_polling import ARMPolling from .. import models as _models from .._serialization import Serializer from .._vendor import _convert_request, _format_url_section if sys.version_info >= (3, 8): from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports else: from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False def build_list_by_customer_request(billing_account_name: str, customer_name: str, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/customers/{customerName}/billingSubscriptions", ) # pylint: disable=line-too-long path_format_arguments = { "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), "customerName": _SERIALIZER.url("customer_name", customer_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_list_by_billing_account_request(billing_account_name: str, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingSubscriptions" ) # pylint: disable=line-too-long path_format_arguments = { "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_list_by_billing_profile_request( billing_account_name: str, billing_profile_name: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/billingSubscriptions", ) # pylint: disable=line-too-long path_format_arguments = { "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), "billingProfileName": _SERIALIZER.url("billing_profile_name", billing_profile_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_list_by_invoice_section_request( billing_account_name: str, billing_profile_name: str, invoice_section_name: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoiceSections/{invoiceSectionName}/billingSubscriptions", ) # pylint: disable=line-too-long path_format_arguments = { "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), "billingProfileName": _SERIALIZER.url("billing_profile_name", billing_profile_name, "str"), "invoiceSectionName": _SERIALIZER.url("invoice_section_name", invoice_section_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_get_request(billing_account_name: str, subscription_id: str, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingSubscriptions/{subscriptionId}", ) # pylint: disable=line-too-long path_format_arguments = { "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_update_request(billing_account_name: str, subscription_id: str, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingSubscriptions/{subscriptionId}", ) # pylint: disable=line-too-long path_format_arguments = { "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers if content_type is not None: _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs) def build_move_request(billing_account_name: str, subscription_id: str, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingSubscriptions/{subscriptionId}/move", ) # pylint: disable=line-too-long path_format_arguments = { "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers if content_type is not None: _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) def build_validate_move_request(billing_account_name: str, subscription_id: str, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingSubscriptions/{subscriptionId}/validateMoveEligibility", ) # pylint: disable=line-too-long path_format_arguments = { "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers if content_type is not None: _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) class BillingSubscriptionsOperations: """ .. warning:: **DO NOT** instantiate this class directly. Instead, you should access the following operations through :class:`~azure.mgmt.billing.BillingManagementClient`'s :attr:`billing_subscriptions` attribute. """ models = _models def __init__(self, *args, **kwargs): input_args = list(args) self._client = input_args.pop(0) if input_args else kwargs.pop("client") self._config = input_args.pop(0) if input_args else kwargs.pop("config") self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace def list_by_customer( self, billing_account_name: str, customer_name: str, **kwargs: Any ) -> Iterable["_models.BillingSubscription"]: """Lists the subscriptions for a customer. The operation is supported only for billing accounts with agreement type Microsoft Partner Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param customer_name: The ID that uniquely identifies a customer. Required. :type customer_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either BillingSubscription or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billing.models.BillingSubscription] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingSubscriptionsListResult] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_by_customer_request( billing_account_name=billing_account_name, customer_name=customer_name, api_version=api_version, template_url=self.list_by_customer.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore else: request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request def extract_data(pipeline_response): deserialized = self._deserialize("BillingSubscriptionsListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return ItemPaged(get_next, extract_data) list_by_customer.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/customers/{customerName}/billingSubscriptions"} # type: ignore @distributed_trace def list_by_billing_account( self, billing_account_name: str, **kwargs: Any ) -> Iterable["_models.BillingSubscription"]: """Lists the subscriptions for a billing account. The operation is supported for billing accounts with agreement type Microsoft Customer Agreement or Microsoft Partner Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either BillingSubscription or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billing.models.BillingSubscription] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingSubscriptionsListResult] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_by_billing_account_request( billing_account_name=billing_account_name, api_version=api_version, template_url=self.list_by_billing_account.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore else: request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request def extract_data(pipeline_response): deserialized = self._deserialize("BillingSubscriptionsListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return ItemPaged(get_next, extract_data) list_by_billing_account.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingSubscriptions"} # type: ignore @distributed_trace def list_by_billing_profile( self, billing_account_name: str, billing_profile_name: str, **kwargs: Any ) -> Iterable["_models.BillingSubscription"]: """Lists the subscriptions that are billed to a billing profile. The operation is supported for billing accounts with agreement type Microsoft Customer Agreement or Microsoft Partner Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either BillingSubscription or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billing.models.BillingSubscription] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingSubscriptionsListResult] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_by_billing_profile_request( billing_account_name=billing_account_name, billing_profile_name=billing_profile_name, api_version=api_version, template_url=self.list_by_billing_profile.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore else: request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request def extract_data(pipeline_response): deserialized = self._deserialize("BillingSubscriptionsListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return ItemPaged(get_next, extract_data) list_by_billing_profile.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/billingSubscriptions"} # type: ignore @distributed_trace def list_by_invoice_section( self, billing_account_name: str, billing_profile_name: str, invoice_section_name: str, **kwargs: Any ) -> Iterable["_models.BillingSubscription"]: """Lists the subscriptions that are billed to an invoice section. The operation is supported only for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :param invoice_section_name: The ID that uniquely identifies an invoice section. Required. :type invoice_section_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either BillingSubscription or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billing.models.BillingSubscription] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingSubscriptionsListResult] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_by_invoice_section_request( billing_account_name=billing_account_name, billing_profile_name=billing_profile_name, invoice_section_name=invoice_section_name, api_version=api_version, template_url=self.list_by_invoice_section.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore else: request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request def extract_data(pipeline_response): deserialized = self._deserialize("BillingSubscriptionsListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return ItemPaged(get_next, extract_data) list_by_invoice_section.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoiceSections/{invoiceSectionName}/billingSubscriptions"} # type: ignore @distributed_trace def get(self, billing_account_name: str, **kwargs: Any) -> _models.BillingSubscription: """Gets a subscription by its ID. The operation is supported for billing accounts with agreement type Microsoft Customer Agreement and Microsoft Partner Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: BillingSubscription or the result of cls(response) :rtype: ~azure.mgmt.billing.models.BillingSubscription :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingSubscription] request = build_get_request( billing_account_name=billing_account_name, subscription_id=self._config.subscription_id, api_version=api_version, template_url=self.get.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize("BillingSubscription", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingSubscriptions/{subscriptionId}"} # type: ignore @overload def update( self, billing_account_name: str, parameters: _models.BillingSubscription, *, content_type: str = "application/json", **kwargs: Any ) -> _models.BillingSubscription: """Updates the properties of a billing subscription. Currently, cost center can be updated. The operation is supported only for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param parameters: Request parameters that are provided to the update billing subscription operation. Required. :type parameters: ~azure.mgmt.billing.models.BillingSubscription :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: BillingSubscription or the result of cls(response) :rtype: ~azure.mgmt.billing.models.BillingSubscription :raises ~azure.core.exceptions.HttpResponseError: """ @overload def update( self, billing_account_name: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any ) -> _models.BillingSubscription: """Updates the properties of a billing subscription. Currently, cost center can be updated. The operation is supported only for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param parameters: Request parameters that are provided to the update billing subscription operation. Required. :type parameters: IO :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: BillingSubscription or the result of cls(response) :rtype: ~azure.mgmt.billing.models.BillingSubscription :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace def update( self, billing_account_name: str, parameters: Union[_models.BillingSubscription, IO], **kwargs: Any ) -> _models.BillingSubscription: """Updates the properties of a billing subscription. Currently, cost center can be updated. The operation is supported only for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param parameters: Request parameters that are provided to the update billing subscription operation. Is either a model type or a IO type. Required. :type parameters: ~azure.mgmt.billing.models.BillingSubscription or IO :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. Default value is None. :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: BillingSubscription or the result of cls(response) :rtype: ~azure.mgmt.billing.models.BillingSubscription :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingSubscription] content_type = content_type or "application/json" _json = None _content = None if isinstance(parameters, (IO, bytes)): _content = parameters else: _json = self._serialize.body(parameters, "BillingSubscription") request = build_update_request( billing_account_name=billing_account_name, subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, content=_content, template_url=self.update.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize("BillingSubscription", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized update.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingSubscriptions/{subscriptionId}"} # type: ignore def _move_initial( self, billing_account_name: str, parameters: Union[_models.TransferBillingSubscriptionRequestProperties, IO], **kwargs: Any ) -> Optional[_models.BillingSubscription]: error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.BillingSubscription]] content_type = content_type or "application/json" _json = None _content = None if isinstance(parameters, (IO, bytes)): _content = parameters else: _json = self._serialize.body(parameters, "TransferBillingSubscriptionRequestProperties") request = build_move_request( billing_account_name=billing_account_name, subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, content=_content, template_url=self._move_initial.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = None response_headers = {} if response.status_code == 200: deserialized = self._deserialize("BillingSubscription", pipeline_response) if response.status_code == 202: response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) if cls: return cls(pipeline_response, deserialized, response_headers) return deserialized _move_initial.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingSubscriptions/{subscriptionId}/move"} # type: ignore @overload def begin_move( self, billing_account_name: str, parameters: _models.TransferBillingSubscriptionRequestProperties, *, content_type: str = "application/json", **kwargs: Any ) -> LROPoller[_models.BillingSubscription]: """Moves a subscription's charges to a new invoice section. The new invoice section must belong to the same billing profile as the existing invoice section. This operation is supported for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param parameters: Request parameters that are provided to the move subscription operation. Required. :type parameters: ~azure.mgmt.billing.models.TransferBillingSubscriptionRequestProperties :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.PollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of LROPoller that returns either BillingSubscription or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.billing.models.BillingSubscription] :raises ~azure.core.exceptions.HttpResponseError: """ @overload def begin_move( self, billing_account_name: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any ) -> LROPoller[_models.BillingSubscription]: """Moves a subscription's charges to a new invoice section. The new invoice section must belong to the same billing profile as the existing invoice section. This operation is supported for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param parameters: Request parameters that are provided to the move subscription operation. Required. :type parameters: IO :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.PollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of LROPoller that returns either BillingSubscription or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.billing.models.BillingSubscription] :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace def begin_move( self, billing_account_name: str, parameters: Union[_models.TransferBillingSubscriptionRequestProperties, IO], **kwargs: Any ) -> LROPoller[_models.BillingSubscription]: """Moves a subscription's charges to a new invoice section. The new invoice section must belong to the same billing profile as the existing invoice section. This operation is supported for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param parameters: Request parameters that are provided to the move subscription operation. Is either a model type or a IO type. Required. :type parameters: ~azure.mgmt.billing.models.TransferBillingSubscriptionRequestProperties or IO :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. Default value is None. :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.PollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of LROPoller that returns either BillingSubscription or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.billing.models.BillingSubscription] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingSubscription] polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod] lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: raw_result = self._move_initial( # type: ignore billing_account_name=billing_account_name, parameters=parameters, api_version=api_version, content_type=content_type, cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): deserialized = self._deserialize("BillingSubscription", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized if polling is True: polling_method = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) # type: PollingMethod elif polling is False: polling_method = cast(PollingMethod, NoPolling()) else: polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) return LROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_move.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingSubscriptions/{subscriptionId}/move"} # type: ignore @overload def validate_move( self, billing_account_name: str, parameters: _models.TransferBillingSubscriptionRequestProperties, *, content_type: str = "application/json", **kwargs: Any ) -> _models.ValidateSubscriptionTransferEligibilityResult: """Validates if a subscription's charges can be moved to a new invoice section. This operation is supported for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param parameters: Request parameters that are provided to the validate move eligibility operation. Required. :type parameters: ~azure.mgmt.billing.models.TransferBillingSubscriptionRequestProperties :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: ValidateSubscriptionTransferEligibilityResult or the result of cls(response) :rtype: ~azure.mgmt.billing.models.ValidateSubscriptionTransferEligibilityResult :raises ~azure.core.exceptions.HttpResponseError: """ @overload def validate_move( self, billing_account_name: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any ) -> _models.ValidateSubscriptionTransferEligibilityResult: """Validates if a subscription's charges can be moved to a new invoice section. This operation is supported for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param parameters: Request parameters that are provided to the validate move eligibility operation. Required. :type parameters: IO :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: ValidateSubscriptionTransferEligibilityResult or the result of cls(response) :rtype: ~azure.mgmt.billing.models.ValidateSubscriptionTransferEligibilityResult :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace def validate_move( self, billing_account_name: str, parameters: Union[_models.TransferBillingSubscriptionRequestProperties, IO], **kwargs: Any ) -> _models.ValidateSubscriptionTransferEligibilityResult: """Validates if a subscription's charges can be moved to a new invoice section. This operation is supported for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param parameters: Request parameters that are provided to the validate move eligibility operation. Is either a model type or a IO type. Required. :type parameters: ~azure.mgmt.billing.models.TransferBillingSubscriptionRequestProperties or IO :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. Default value is None. :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: ValidateSubscriptionTransferEligibilityResult or the result of cls(response) :rtype: ~azure.mgmt.billing.models.ValidateSubscriptionTransferEligibilityResult :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] cls = kwargs.pop("cls", None) # type: ClsType[_models.ValidateSubscriptionTransferEligibilityResult] content_type = content_type or "application/json" _json = None _content = None if isinstance(parameters, (IO, bytes)): _content = parameters else: _json = self._serialize.body(parameters, "TransferBillingSubscriptionRequestProperties") request = build_validate_move_request( billing_account_name=billing_account_name, subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, content=_content, template_url=self.validate_move.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize("ValidateSubscriptionTransferEligibilityResult", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized validate_move.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingSubscriptions/{subscriptionId}/validateMoveEligibility"} # type: ignore
0.518302
0.080394
import sys from typing import Any, Callable, Dict, Iterable, Optional, TypeVar from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, map_error, ) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models from .._serialization import Serializer from .._vendor import _convert_request, _format_url_section if sys.version_info >= (3, 8): from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports else: from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False def build_list_by_billing_account_request( billing_account_name: str, *, filter: Optional[str] = None, orderby: Optional[str] = None, refresh_summary: Optional[str] = None, selected_state: Optional[str] = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop("template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/reservations") path_format_arguments = { "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if filter is not None: _params["$filter"] = _SERIALIZER.query("filter", filter, "str") if orderby is not None: _params["$orderby"] = _SERIALIZER.query("orderby", orderby, "str") if refresh_summary is not None: _params["refreshSummary"] = _SERIALIZER.query("refresh_summary", refresh_summary, "str") if selected_state is not None: _params["selectedState"] = _SERIALIZER.query("selected_state", selected_state, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_list_by_billing_profile_request( billing_account_name: str, billing_profile_name: str, *, filter: Optional[str] = None, orderby: Optional[str] = None, refresh_summary: Optional[str] = None, selected_state: Optional[str] = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/reservations", ) # pylint: disable=line-too-long path_format_arguments = { "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), "billingProfileName": _SERIALIZER.url("billing_profile_name", billing_profile_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if filter is not None: _params["$filter"] = _SERIALIZER.query("filter", filter, "str") if orderby is not None: _params["$orderby"] = _SERIALIZER.query("orderby", orderby, "str") if refresh_summary is not None: _params["refreshSummary"] = _SERIALIZER.query("refresh_summary", refresh_summary, "str") if selected_state is not None: _params["selectedState"] = _SERIALIZER.query("selected_state", selected_state, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) class ReservationsOperations: """ .. warning:: **DO NOT** instantiate this class directly. Instead, you should access the following operations through :class:`~azure.mgmt.billing.BillingManagementClient`'s :attr:`reservations` attribute. """ models = _models def __init__(self, *args, **kwargs): input_args = list(args) self._client = input_args.pop(0) if input_args else kwargs.pop("client") self._config = input_args.pop(0) if input_args else kwargs.pop("config") self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace def list_by_billing_account( self, billing_account_name: str, filter: Optional[str] = None, orderby: Optional[str] = None, refresh_summary: Optional[str] = None, selected_state: Optional[str] = None, **kwargs: Any ) -> Iterable["_models.Reservation"]: """Lists the reservations for a billing account and the roll up counts of reservations group by provisioning states. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param filter: May be used to filter by reservation properties. The filter supports 'eq', 'or', and 'and'. It does not currently support 'ne', 'gt', 'le', 'ge', or 'not'. Default value is None. :type filter: str :param orderby: May be used to sort order by reservation properties. Default value is None. :type orderby: str :param refresh_summary: To indicate whether to refresh the roll up counts of the reservations group by provisioning states. Default value is None. :type refresh_summary: str :param selected_state: The selected provisioning state. Default value is None. :type selected_state: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either Reservation or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billing.models.Reservation] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.ReservationsListResult] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_by_billing_account_request( billing_account_name=billing_account_name, filter=filter, orderby=orderby, refresh_summary=refresh_summary, selected_state=selected_state, api_version=api_version, template_url=self.list_by_billing_account.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore else: request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request def extract_data(pipeline_response): deserialized = self._deserialize("ReservationsListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return ItemPaged(get_next, extract_data) list_by_billing_account.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/reservations"} # type: ignore @distributed_trace def list_by_billing_profile( self, billing_account_name: str, billing_profile_name: str, filter: Optional[str] = None, orderby: Optional[str] = None, refresh_summary: Optional[str] = None, selected_state: Optional[str] = None, **kwargs: Any ) -> Iterable["_models.Reservation"]: """Lists the reservations for a billing profile and the roll up counts of reservations group by provisioning state. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :param filter: May be used to filter by reservation properties. The filter supports 'eq', 'or', and 'and'. It does not currently support 'ne', 'gt', 'le', 'ge', or 'not'. Default value is None. :type filter: str :param orderby: May be used to sort order by reservation properties. Default value is None. :type orderby: str :param refresh_summary: To indicate whether to refresh the roll up counts of the reservations group by provisioning state. Default value is None. :type refresh_summary: str :param selected_state: The selected provisioning state. Default value is None. :type selected_state: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either Reservation or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billing.models.Reservation] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.ReservationsListResult] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_by_billing_profile_request( billing_account_name=billing_account_name, billing_profile_name=billing_profile_name, filter=filter, orderby=orderby, refresh_summary=refresh_summary, selected_state=selected_state, api_version=api_version, template_url=self.list_by_billing_profile.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore else: request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request def extract_data(pipeline_response): deserialized = self._deserialize("ReservationsListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return ItemPaged(get_next, extract_data) list_by_billing_profile.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/reservations"} # type: ignore
azure-mgmt-billing
/azure_mgmt_billing-6.1.0b1-py3-none-any.whl/azure/mgmt/billing/operations/_reservations_operations.py
_reservations_operations.py
import sys from typing import Any, Callable, Dict, Iterable, Optional, TypeVar from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, map_error, ) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models from .._serialization import Serializer from .._vendor import _convert_request, _format_url_section if sys.version_info >= (3, 8): from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports else: from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False def build_list_by_billing_account_request( billing_account_name: str, *, filter: Optional[str] = None, orderby: Optional[str] = None, refresh_summary: Optional[str] = None, selected_state: Optional[str] = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop("template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/reservations") path_format_arguments = { "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if filter is not None: _params["$filter"] = _SERIALIZER.query("filter", filter, "str") if orderby is not None: _params["$orderby"] = _SERIALIZER.query("orderby", orderby, "str") if refresh_summary is not None: _params["refreshSummary"] = _SERIALIZER.query("refresh_summary", refresh_summary, "str") if selected_state is not None: _params["selectedState"] = _SERIALIZER.query("selected_state", selected_state, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_list_by_billing_profile_request( billing_account_name: str, billing_profile_name: str, *, filter: Optional[str] = None, orderby: Optional[str] = None, refresh_summary: Optional[str] = None, selected_state: Optional[str] = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/reservations", ) # pylint: disable=line-too-long path_format_arguments = { "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), "billingProfileName": _SERIALIZER.url("billing_profile_name", billing_profile_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if filter is not None: _params["$filter"] = _SERIALIZER.query("filter", filter, "str") if orderby is not None: _params["$orderby"] = _SERIALIZER.query("orderby", orderby, "str") if refresh_summary is not None: _params["refreshSummary"] = _SERIALIZER.query("refresh_summary", refresh_summary, "str") if selected_state is not None: _params["selectedState"] = _SERIALIZER.query("selected_state", selected_state, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) class ReservationsOperations: """ .. warning:: **DO NOT** instantiate this class directly. Instead, you should access the following operations through :class:`~azure.mgmt.billing.BillingManagementClient`'s :attr:`reservations` attribute. """ models = _models def __init__(self, *args, **kwargs): input_args = list(args) self._client = input_args.pop(0) if input_args else kwargs.pop("client") self._config = input_args.pop(0) if input_args else kwargs.pop("config") self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace def list_by_billing_account( self, billing_account_name: str, filter: Optional[str] = None, orderby: Optional[str] = None, refresh_summary: Optional[str] = None, selected_state: Optional[str] = None, **kwargs: Any ) -> Iterable["_models.Reservation"]: """Lists the reservations for a billing account and the roll up counts of reservations group by provisioning states. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param filter: May be used to filter by reservation properties. The filter supports 'eq', 'or', and 'and'. It does not currently support 'ne', 'gt', 'le', 'ge', or 'not'. Default value is None. :type filter: str :param orderby: May be used to sort order by reservation properties. Default value is None. :type orderby: str :param refresh_summary: To indicate whether to refresh the roll up counts of the reservations group by provisioning states. Default value is None. :type refresh_summary: str :param selected_state: The selected provisioning state. Default value is None. :type selected_state: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either Reservation or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billing.models.Reservation] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.ReservationsListResult] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_by_billing_account_request( billing_account_name=billing_account_name, filter=filter, orderby=orderby, refresh_summary=refresh_summary, selected_state=selected_state, api_version=api_version, template_url=self.list_by_billing_account.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore else: request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request def extract_data(pipeline_response): deserialized = self._deserialize("ReservationsListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return ItemPaged(get_next, extract_data) list_by_billing_account.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/reservations"} # type: ignore @distributed_trace def list_by_billing_profile( self, billing_account_name: str, billing_profile_name: str, filter: Optional[str] = None, orderby: Optional[str] = None, refresh_summary: Optional[str] = None, selected_state: Optional[str] = None, **kwargs: Any ) -> Iterable["_models.Reservation"]: """Lists the reservations for a billing profile and the roll up counts of reservations group by provisioning state. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :param filter: May be used to filter by reservation properties. The filter supports 'eq', 'or', and 'and'. It does not currently support 'ne', 'gt', 'le', 'ge', or 'not'. Default value is None. :type filter: str :param orderby: May be used to sort order by reservation properties. Default value is None. :type orderby: str :param refresh_summary: To indicate whether to refresh the roll up counts of the reservations group by provisioning state. Default value is None. :type refresh_summary: str :param selected_state: The selected provisioning state. Default value is None. :type selected_state: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either Reservation or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billing.models.Reservation] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.ReservationsListResult] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_by_billing_profile_request( billing_account_name=billing_account_name, billing_profile_name=billing_profile_name, filter=filter, orderby=orderby, refresh_summary=refresh_summary, selected_state=selected_state, api_version=api_version, template_url=self.list_by_billing_profile.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore else: request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request def extract_data(pipeline_response): deserialized = self._deserialize("ReservationsListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return ItemPaged(get_next, extract_data) list_by_billing_profile.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/reservations"} # type: ignore
0.674908
0.086516
import sys from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, overload from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, map_error, ) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models from .._serialization import Serializer from .._vendor import _convert_request, _format_url_section if sys.version_info >= (3, 8): from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports else: from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False def build_get_request(subscription_id: str, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Billing/billingProperty/default" ) path_format_arguments = { "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_update_request(subscription_id: str, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Billing/billingProperty/default" ) path_format_arguments = { "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers if content_type is not None: _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs) class BillingPropertyOperations: """ .. warning:: **DO NOT** instantiate this class directly. Instead, you should access the following operations through :class:`~azure.mgmt.billing.BillingManagementClient`'s :attr:`billing_property` attribute. """ models = _models def __init__(self, *args, **kwargs): input_args = list(args) self._client = input_args.pop(0) if input_args else kwargs.pop("client") self._config = input_args.pop(0) if input_args else kwargs.pop("config") self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace def get(self, **kwargs: Any) -> _models.BillingProperty: """Get the billing properties for a subscription. This operation is not supported for billing accounts with agreement type Enterprise Agreement. :keyword callable cls: A custom type or function that will be passed the direct response :return: BillingProperty or the result of cls(response) :rtype: ~azure.mgmt.billing.models.BillingProperty :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingProperty] request = build_get_request( subscription_id=self._config.subscription_id, api_version=api_version, template_url=self.get.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize("BillingProperty", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Billing/billingProperty/default"} # type: ignore @overload def update( self, parameters: _models.BillingProperty, *, content_type: str = "application/json", **kwargs: Any ) -> _models.BillingProperty: """Updates the billing property of a subscription. Currently, cost center can be updated. The operation is supported only for billing accounts with agreement type Microsoft Customer Agreement. :param parameters: Request parameters that are provided to the update billing property operation. Required. :type parameters: ~azure.mgmt.billing.models.BillingProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: BillingProperty or the result of cls(response) :rtype: ~azure.mgmt.billing.models.BillingProperty :raises ~azure.core.exceptions.HttpResponseError: """ @overload def update( self, parameters: IO, *, content_type: str = "application/json", **kwargs: Any ) -> _models.BillingProperty: """Updates the billing property of a subscription. Currently, cost center can be updated. The operation is supported only for billing accounts with agreement type Microsoft Customer Agreement. :param parameters: Request parameters that are provided to the update billing property operation. Required. :type parameters: IO :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: BillingProperty or the result of cls(response) :rtype: ~azure.mgmt.billing.models.BillingProperty :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace def update(self, parameters: Union[_models.BillingProperty, IO], **kwargs: Any) -> _models.BillingProperty: """Updates the billing property of a subscription. Currently, cost center can be updated. The operation is supported only for billing accounts with agreement type Microsoft Customer Agreement. :param parameters: Request parameters that are provided to the update billing property operation. Is either a model type or a IO type. Required. :type parameters: ~azure.mgmt.billing.models.BillingProperty or IO :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. Default value is None. :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: BillingProperty or the result of cls(response) :rtype: ~azure.mgmt.billing.models.BillingProperty :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingProperty] content_type = content_type or "application/json" _json = None _content = None if isinstance(parameters, (IO, bytes)): _content = parameters else: _json = self._serialize.body(parameters, "BillingProperty") request = build_update_request( subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, content=_content, template_url=self.update.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize("BillingProperty", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized update.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Billing/billingProperty/default"} # type: ignore
azure-mgmt-billing
/azure_mgmt_billing-6.1.0b1-py3-none-any.whl/azure/mgmt/billing/operations/_billing_property_operations.py
_billing_property_operations.py
import sys from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, overload from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, map_error, ) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models from .._serialization import Serializer from .._vendor import _convert_request, _format_url_section if sys.version_info >= (3, 8): from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports else: from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False def build_get_request(subscription_id: str, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Billing/billingProperty/default" ) path_format_arguments = { "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_update_request(subscription_id: str, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Billing/billingProperty/default" ) path_format_arguments = { "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers if content_type is not None: _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs) class BillingPropertyOperations: """ .. warning:: **DO NOT** instantiate this class directly. Instead, you should access the following operations through :class:`~azure.mgmt.billing.BillingManagementClient`'s :attr:`billing_property` attribute. """ models = _models def __init__(self, *args, **kwargs): input_args = list(args) self._client = input_args.pop(0) if input_args else kwargs.pop("client") self._config = input_args.pop(0) if input_args else kwargs.pop("config") self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace def get(self, **kwargs: Any) -> _models.BillingProperty: """Get the billing properties for a subscription. This operation is not supported for billing accounts with agreement type Enterprise Agreement. :keyword callable cls: A custom type or function that will be passed the direct response :return: BillingProperty or the result of cls(response) :rtype: ~azure.mgmt.billing.models.BillingProperty :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingProperty] request = build_get_request( subscription_id=self._config.subscription_id, api_version=api_version, template_url=self.get.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize("BillingProperty", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Billing/billingProperty/default"} # type: ignore @overload def update( self, parameters: _models.BillingProperty, *, content_type: str = "application/json", **kwargs: Any ) -> _models.BillingProperty: """Updates the billing property of a subscription. Currently, cost center can be updated. The operation is supported only for billing accounts with agreement type Microsoft Customer Agreement. :param parameters: Request parameters that are provided to the update billing property operation. Required. :type parameters: ~azure.mgmt.billing.models.BillingProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: BillingProperty or the result of cls(response) :rtype: ~azure.mgmt.billing.models.BillingProperty :raises ~azure.core.exceptions.HttpResponseError: """ @overload def update( self, parameters: IO, *, content_type: str = "application/json", **kwargs: Any ) -> _models.BillingProperty: """Updates the billing property of a subscription. Currently, cost center can be updated. The operation is supported only for billing accounts with agreement type Microsoft Customer Agreement. :param parameters: Request parameters that are provided to the update billing property operation. Required. :type parameters: IO :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: BillingProperty or the result of cls(response) :rtype: ~azure.mgmt.billing.models.BillingProperty :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace def update(self, parameters: Union[_models.BillingProperty, IO], **kwargs: Any) -> _models.BillingProperty: """Updates the billing property of a subscription. Currently, cost center can be updated. The operation is supported only for billing accounts with agreement type Microsoft Customer Agreement. :param parameters: Request parameters that are provided to the update billing property operation. Is either a model type or a IO type. Required. :type parameters: ~azure.mgmt.billing.models.BillingProperty or IO :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. Default value is None. :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: BillingProperty or the result of cls(response) :rtype: ~azure.mgmt.billing.models.BillingProperty :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingProperty] content_type = content_type or "application/json" _json = None _content = None if isinstance(parameters, (IO, bytes)): _content = parameters else: _json = self._serialize.body(parameters, "BillingProperty") request = build_update_request( subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, content=_content, template_url=self.update.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize("BillingProperty", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized update.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Billing/billingProperty/default"} # type: ignore
0.639061
0.079104
import sys from typing import Any, Callable, Dict, Iterable, Optional, TypeVar from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, map_error, ) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models from .._serialization import Serializer from .._vendor import _convert_request if sys.version_info >= (3, 8): from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports else: from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False def build_list_request(**kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop("template_url", "/providers/Microsoft.Billing/operations") # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) class Operations: """ .. warning:: **DO NOT** instantiate this class directly. Instead, you should access the following operations through :class:`~azure.mgmt.billing.BillingManagementClient`'s :attr:`operations` attribute. """ models = _models def __init__(self, *args, **kwargs): input_args = list(args) self._client = input_args.pop(0) if input_args else kwargs.pop("client") self._config = input_args.pop(0) if input_args else kwargs.pop("config") self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace def list(self, **kwargs: Any) -> Iterable["_models.Operation"]: """Lists the available billing REST API operations. :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either Operation or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billing.models.Operation] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.OperationListResult] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_request( api_version=api_version, template_url=self.list.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore else: request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request def extract_data(pipeline_response): deserialized = self._deserialize("OperationListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.OperationsErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return ItemPaged(get_next, extract_data) list.metadata = {"url": "/providers/Microsoft.Billing/operations"} # type: ignore
azure-mgmt-billing
/azure_mgmt_billing-6.1.0b1-py3-none-any.whl/azure/mgmt/billing/operations/_operations.py
_operations.py
import sys from typing import Any, Callable, Dict, Iterable, Optional, TypeVar from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, map_error, ) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models from .._serialization import Serializer from .._vendor import _convert_request if sys.version_info >= (3, 8): from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports else: from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False def build_list_request(**kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop("template_url", "/providers/Microsoft.Billing/operations") # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) class Operations: """ .. warning:: **DO NOT** instantiate this class directly. Instead, you should access the following operations through :class:`~azure.mgmt.billing.BillingManagementClient`'s :attr:`operations` attribute. """ models = _models def __init__(self, *args, **kwargs): input_args = list(args) self._client = input_args.pop(0) if input_args else kwargs.pop("client") self._config = input_args.pop(0) if input_args else kwargs.pop("config") self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace def list(self, **kwargs: Any) -> Iterable["_models.Operation"]: """Lists the available billing REST API operations. :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either Operation or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billing.models.Operation] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.OperationListResult] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_request( api_version=api_version, template_url=self.list.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore else: request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request def extract_data(pipeline_response): deserialized = self._deserialize("OperationListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.OperationsErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return ItemPaged(get_next, extract_data) list.metadata = {"url": "/providers/Microsoft.Billing/operations"} # type: ignore
0.635788
0.077727
from ._billing_accounts_operations import BillingAccountsOperations from ._address_operations import AddressOperations from ._available_balances_operations import AvailableBalancesOperations from ._instructions_operations import InstructionsOperations from ._billing_profiles_operations import BillingProfilesOperations from ._customers_operations import CustomersOperations from ._invoice_sections_operations import InvoiceSectionsOperations from ._billing_permissions_operations import BillingPermissionsOperations from ._billing_subscriptions_operations import BillingSubscriptionsOperations from ._products_operations import ProductsOperations from ._invoices_operations import InvoicesOperations from ._transactions_operations import TransactionsOperations from ._policies_operations import PoliciesOperations from ._billing_property_operations import BillingPropertyOperations from ._billing_role_definitions_operations import BillingRoleDefinitionsOperations from ._billing_role_assignments_operations import BillingRoleAssignmentsOperations from ._agreements_operations import AgreementsOperations from ._reservations_operations import ReservationsOperations from ._enrollment_accounts_operations import EnrollmentAccountsOperations from ._billing_periods_operations import BillingPeriodsOperations from ._operations import Operations from ._patch import __all__ as _patch_all from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import from ._patch import patch_sdk as _patch_sdk __all__ = [ "BillingAccountsOperations", "AddressOperations", "AvailableBalancesOperations", "InstructionsOperations", "BillingProfilesOperations", "CustomersOperations", "InvoiceSectionsOperations", "BillingPermissionsOperations", "BillingSubscriptionsOperations", "ProductsOperations", "InvoicesOperations", "TransactionsOperations", "PoliciesOperations", "BillingPropertyOperations", "BillingRoleDefinitionsOperations", "BillingRoleAssignmentsOperations", "AgreementsOperations", "ReservationsOperations", "EnrollmentAccountsOperations", "BillingPeriodsOperations", "Operations", ] __all__.extend([p for p in _patch_all if p not in __all__]) _patch_sdk()
azure-mgmt-billing
/azure_mgmt_billing-6.1.0b1-py3-none-any.whl/azure/mgmt/billing/operations/__init__.py
__init__.py
from ._billing_accounts_operations import BillingAccountsOperations from ._address_operations import AddressOperations from ._available_balances_operations import AvailableBalancesOperations from ._instructions_operations import InstructionsOperations from ._billing_profiles_operations import BillingProfilesOperations from ._customers_operations import CustomersOperations from ._invoice_sections_operations import InvoiceSectionsOperations from ._billing_permissions_operations import BillingPermissionsOperations from ._billing_subscriptions_operations import BillingSubscriptionsOperations from ._products_operations import ProductsOperations from ._invoices_operations import InvoicesOperations from ._transactions_operations import TransactionsOperations from ._policies_operations import PoliciesOperations from ._billing_property_operations import BillingPropertyOperations from ._billing_role_definitions_operations import BillingRoleDefinitionsOperations from ._billing_role_assignments_operations import BillingRoleAssignmentsOperations from ._agreements_operations import AgreementsOperations from ._reservations_operations import ReservationsOperations from ._enrollment_accounts_operations import EnrollmentAccountsOperations from ._billing_periods_operations import BillingPeriodsOperations from ._operations import Operations from ._patch import __all__ as _patch_all from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import from ._patch import patch_sdk as _patch_sdk __all__ = [ "BillingAccountsOperations", "AddressOperations", "AvailableBalancesOperations", "InstructionsOperations", "BillingProfilesOperations", "CustomersOperations", "InvoiceSectionsOperations", "BillingPermissionsOperations", "BillingSubscriptionsOperations", "ProductsOperations", "InvoicesOperations", "TransactionsOperations", "PoliciesOperations", "BillingPropertyOperations", "BillingRoleDefinitionsOperations", "BillingRoleAssignmentsOperations", "AgreementsOperations", "ReservationsOperations", "EnrollmentAccountsOperations", "BillingPeriodsOperations", "Operations", ] __all__.extend([p for p in _patch_all if p not in __all__]) _patch_sdk()
0.437824
0.066448
import sys from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, cast, overload from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, map_error, ) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse from azure.core.polling import LROPoller, NoPolling, PollingMethod from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.arm_polling import ARMPolling from .. import models as _models from .._serialization import Serializer from .._vendor import _convert_request, _format_url_section if sys.version_info >= (3, 8): from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports else: from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False def build_list_by_billing_account_request( billing_account_name: str, *, expand: Optional[str] = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles" ) path_format_arguments = { "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if expand is not None: _params["$expand"] = _SERIALIZER.query("expand", expand, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_get_request( billing_account_name: str, billing_profile_name: str, *, expand: Optional[str] = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}", ) # pylint: disable=line-too-long path_format_arguments = { "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), "billingProfileName": _SERIALIZER.url("billing_profile_name", billing_profile_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if expand is not None: _params["$expand"] = _SERIALIZER.query("expand", expand, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_create_or_update_request(billing_account_name: str, billing_profile_name: str, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}", ) # pylint: disable=line-too-long path_format_arguments = { "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), "billingProfileName": _SERIALIZER.url("billing_profile_name", billing_profile_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers if content_type is not None: _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) class BillingProfilesOperations: """ .. warning:: **DO NOT** instantiate this class directly. Instead, you should access the following operations through :class:`~azure.mgmt.billing.BillingManagementClient`'s :attr:`billing_profiles` attribute. """ models = _models def __init__(self, *args, **kwargs): input_args = list(args) self._client = input_args.pop(0) if input_args else kwargs.pop("client") self._config = input_args.pop(0) if input_args else kwargs.pop("config") self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace def list_by_billing_account( self, billing_account_name: str, expand: Optional[str] = None, **kwargs: Any ) -> Iterable["_models.BillingProfile"]: """Lists the billing profiles that a user has access to. The operation is supported for billing accounts with agreement type Microsoft Customer Agreement or Microsoft Partner Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param expand: May be used to expand the invoice sections. Default value is None. :type expand: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either BillingProfile or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billing.models.BillingProfile] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingProfileListResult] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_by_billing_account_request( billing_account_name=billing_account_name, expand=expand, api_version=api_version, template_url=self.list_by_billing_account.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore else: request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request def extract_data(pipeline_response): deserialized = self._deserialize("BillingProfileListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return ItemPaged(get_next, extract_data) list_by_billing_account.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles"} # type: ignore @distributed_trace def get( self, billing_account_name: str, billing_profile_name: str, expand: Optional[str] = None, **kwargs: Any ) -> _models.BillingProfile: """Gets a billing profile by its ID. The operation is supported for billing accounts with agreement type Microsoft Customer Agreement or Microsoft Partner Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :param expand: May be used to expand the invoice sections. Default value is None. :type expand: str :keyword callable cls: A custom type or function that will be passed the direct response :return: BillingProfile or the result of cls(response) :rtype: ~azure.mgmt.billing.models.BillingProfile :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingProfile] request = build_get_request( billing_account_name=billing_account_name, billing_profile_name=billing_profile_name, expand=expand, api_version=api_version, template_url=self.get.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize("BillingProfile", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}"} # type: ignore def _create_or_update_initial( self, billing_account_name: str, billing_profile_name: str, parameters: Union[_models.BillingProfile, IO], **kwargs: Any ) -> Optional[_models.BillingProfile]: error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.BillingProfile]] content_type = content_type or "application/json" _json = None _content = None if isinstance(parameters, (IO, bytes)): _content = parameters else: _json = self._serialize.body(parameters, "BillingProfile") request = build_create_or_update_request( billing_account_name=billing_account_name, billing_profile_name=billing_profile_name, api_version=api_version, content_type=content_type, json=_json, content=_content, template_url=self._create_or_update_initial.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = None response_headers = {} if response.status_code == 200: deserialized = self._deserialize("BillingProfile", pipeline_response) if response.status_code == 202: response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) if cls: return cls(pipeline_response, deserialized, response_headers) return deserialized _create_or_update_initial.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}"} # type: ignore @overload def begin_create_or_update( self, billing_account_name: str, billing_profile_name: str, parameters: _models.BillingProfile, *, content_type: str = "application/json", **kwargs: Any ) -> LROPoller[_models.BillingProfile]: """Creates or updates a billing profile. The operation is supported for billing accounts with agreement type Microsoft Customer Agreement or Microsoft Partner Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :param parameters: The new or updated billing profile. Required. :type parameters: ~azure.mgmt.billing.models.BillingProfile :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.PollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of LROPoller that returns either BillingProfile or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.billing.models.BillingProfile] :raises ~azure.core.exceptions.HttpResponseError: """ @overload def begin_create_or_update( self, billing_account_name: str, billing_profile_name: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any ) -> LROPoller[_models.BillingProfile]: """Creates or updates a billing profile. The operation is supported for billing accounts with agreement type Microsoft Customer Agreement or Microsoft Partner Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :param parameters: The new or updated billing profile. Required. :type parameters: IO :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.PollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of LROPoller that returns either BillingProfile or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.billing.models.BillingProfile] :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace def begin_create_or_update( self, billing_account_name: str, billing_profile_name: str, parameters: Union[_models.BillingProfile, IO], **kwargs: Any ) -> LROPoller[_models.BillingProfile]: """Creates or updates a billing profile. The operation is supported for billing accounts with agreement type Microsoft Customer Agreement or Microsoft Partner Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :param parameters: The new or updated billing profile. Is either a model type or a IO type. Required. :type parameters: ~azure.mgmt.billing.models.BillingProfile or IO :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. Default value is None. :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.PollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of LROPoller that returns either BillingProfile or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.billing.models.BillingProfile] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingProfile] polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod] lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: raw_result = self._create_or_update_initial( # type: ignore billing_account_name=billing_account_name, billing_profile_name=billing_profile_name, parameters=parameters, api_version=api_version, content_type=content_type, cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): deserialized = self._deserialize("BillingProfile", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized if polling is True: polling_method = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) # type: PollingMethod elif polling is False: polling_method = cast(PollingMethod, NoPolling()) else: polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) return LROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_create_or_update.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}"} # type: ignore
azure-mgmt-billing
/azure_mgmt_billing-6.1.0b1-py3-none-any.whl/azure/mgmt/billing/operations/_billing_profiles_operations.py
_billing_profiles_operations.py
import sys from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, cast, overload from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, map_error, ) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse from azure.core.polling import LROPoller, NoPolling, PollingMethod from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.arm_polling import ARMPolling from .. import models as _models from .._serialization import Serializer from .._vendor import _convert_request, _format_url_section if sys.version_info >= (3, 8): from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports else: from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False def build_list_by_billing_account_request( billing_account_name: str, *, expand: Optional[str] = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles" ) path_format_arguments = { "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if expand is not None: _params["$expand"] = _SERIALIZER.query("expand", expand, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_get_request( billing_account_name: str, billing_profile_name: str, *, expand: Optional[str] = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}", ) # pylint: disable=line-too-long path_format_arguments = { "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), "billingProfileName": _SERIALIZER.url("billing_profile_name", billing_profile_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if expand is not None: _params["$expand"] = _SERIALIZER.query("expand", expand, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_create_or_update_request(billing_account_name: str, billing_profile_name: str, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}", ) # pylint: disable=line-too-long path_format_arguments = { "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), "billingProfileName": _SERIALIZER.url("billing_profile_name", billing_profile_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers if content_type is not None: _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) class BillingProfilesOperations: """ .. warning:: **DO NOT** instantiate this class directly. Instead, you should access the following operations through :class:`~azure.mgmt.billing.BillingManagementClient`'s :attr:`billing_profiles` attribute. """ models = _models def __init__(self, *args, **kwargs): input_args = list(args) self._client = input_args.pop(0) if input_args else kwargs.pop("client") self._config = input_args.pop(0) if input_args else kwargs.pop("config") self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace def list_by_billing_account( self, billing_account_name: str, expand: Optional[str] = None, **kwargs: Any ) -> Iterable["_models.BillingProfile"]: """Lists the billing profiles that a user has access to. The operation is supported for billing accounts with agreement type Microsoft Customer Agreement or Microsoft Partner Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param expand: May be used to expand the invoice sections. Default value is None. :type expand: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either BillingProfile or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billing.models.BillingProfile] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingProfileListResult] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_by_billing_account_request( billing_account_name=billing_account_name, expand=expand, api_version=api_version, template_url=self.list_by_billing_account.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore else: request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request def extract_data(pipeline_response): deserialized = self._deserialize("BillingProfileListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return ItemPaged(get_next, extract_data) list_by_billing_account.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles"} # type: ignore @distributed_trace def get( self, billing_account_name: str, billing_profile_name: str, expand: Optional[str] = None, **kwargs: Any ) -> _models.BillingProfile: """Gets a billing profile by its ID. The operation is supported for billing accounts with agreement type Microsoft Customer Agreement or Microsoft Partner Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :param expand: May be used to expand the invoice sections. Default value is None. :type expand: str :keyword callable cls: A custom type or function that will be passed the direct response :return: BillingProfile or the result of cls(response) :rtype: ~azure.mgmt.billing.models.BillingProfile :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingProfile] request = build_get_request( billing_account_name=billing_account_name, billing_profile_name=billing_profile_name, expand=expand, api_version=api_version, template_url=self.get.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize("BillingProfile", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}"} # type: ignore def _create_or_update_initial( self, billing_account_name: str, billing_profile_name: str, parameters: Union[_models.BillingProfile, IO], **kwargs: Any ) -> Optional[_models.BillingProfile]: error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.BillingProfile]] content_type = content_type or "application/json" _json = None _content = None if isinstance(parameters, (IO, bytes)): _content = parameters else: _json = self._serialize.body(parameters, "BillingProfile") request = build_create_or_update_request( billing_account_name=billing_account_name, billing_profile_name=billing_profile_name, api_version=api_version, content_type=content_type, json=_json, content=_content, template_url=self._create_or_update_initial.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = None response_headers = {} if response.status_code == 200: deserialized = self._deserialize("BillingProfile", pipeline_response) if response.status_code == 202: response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) if cls: return cls(pipeline_response, deserialized, response_headers) return deserialized _create_or_update_initial.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}"} # type: ignore @overload def begin_create_or_update( self, billing_account_name: str, billing_profile_name: str, parameters: _models.BillingProfile, *, content_type: str = "application/json", **kwargs: Any ) -> LROPoller[_models.BillingProfile]: """Creates or updates a billing profile. The operation is supported for billing accounts with agreement type Microsoft Customer Agreement or Microsoft Partner Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :param parameters: The new or updated billing profile. Required. :type parameters: ~azure.mgmt.billing.models.BillingProfile :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.PollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of LROPoller that returns either BillingProfile or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.billing.models.BillingProfile] :raises ~azure.core.exceptions.HttpResponseError: """ @overload def begin_create_or_update( self, billing_account_name: str, billing_profile_name: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any ) -> LROPoller[_models.BillingProfile]: """Creates or updates a billing profile. The operation is supported for billing accounts with agreement type Microsoft Customer Agreement or Microsoft Partner Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :param parameters: The new or updated billing profile. Required. :type parameters: IO :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.PollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of LROPoller that returns either BillingProfile or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.billing.models.BillingProfile] :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace def begin_create_or_update( self, billing_account_name: str, billing_profile_name: str, parameters: Union[_models.BillingProfile, IO], **kwargs: Any ) -> LROPoller[_models.BillingProfile]: """Creates or updates a billing profile. The operation is supported for billing accounts with agreement type Microsoft Customer Agreement or Microsoft Partner Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :param parameters: The new or updated billing profile. Is either a model type or a IO type. Required. :type parameters: ~azure.mgmt.billing.models.BillingProfile or IO :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. Default value is None. :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.PollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of LROPoller that returns either BillingProfile or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.billing.models.BillingProfile] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingProfile] polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod] lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: raw_result = self._create_or_update_initial( # type: ignore billing_account_name=billing_account_name, billing_profile_name=billing_profile_name, parameters=parameters, api_version=api_version, content_type=content_type, cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): deserialized = self._deserialize("BillingProfile", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized if polling is True: polling_method = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) # type: PollingMethod elif polling is False: polling_method = cast(PollingMethod, NoPolling()) else: polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) return LROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_create_or_update.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}"} # type: ignore
0.595375
0.087798
import sys from typing import Any, Callable, Dict, Optional, TypeVar from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, map_error, ) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models from .._serialization import Serializer from .._vendor import _convert_request, _format_url_section if sys.version_info >= (3, 8): from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports else: from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False def build_get_request(billing_account_name: str, billing_profile_name: str, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/availableBalance/default", ) # pylint: disable=line-too-long path_format_arguments = { "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), "billingProfileName": _SERIALIZER.url("billing_profile_name", billing_profile_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) class AvailableBalancesOperations: """ .. warning:: **DO NOT** instantiate this class directly. Instead, you should access the following operations through :class:`~azure.mgmt.billing.BillingManagementClient`'s :attr:`available_balances` attribute. """ models = _models def __init__(self, *args, **kwargs): input_args = list(args) self._client = input_args.pop(0) if input_args else kwargs.pop("client") self._config = input_args.pop(0) if input_args else kwargs.pop("config") self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace def get(self, billing_account_name: str, billing_profile_name: str, **kwargs: Any) -> _models.AvailableBalance: """The available credit balance for a billing profile. This is the balance that can be used for pay now to settle due or past due invoices. The operation is supported only for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: AvailableBalance or the result of cls(response) :rtype: ~azure.mgmt.billing.models.AvailableBalance :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.AvailableBalance] request = build_get_request( billing_account_name=billing_account_name, billing_profile_name=billing_profile_name, api_version=api_version, template_url=self.get.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize("AvailableBalance", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/availableBalance/default"} # type: ignore
azure-mgmt-billing
/azure_mgmt_billing-6.1.0b1-py3-none-any.whl/azure/mgmt/billing/operations/_available_balances_operations.py
_available_balances_operations.py
import sys from typing import Any, Callable, Dict, Optional, TypeVar from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, map_error, ) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models from .._serialization import Serializer from .._vendor import _convert_request, _format_url_section if sys.version_info >= (3, 8): from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports else: from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False def build_get_request(billing_account_name: str, billing_profile_name: str, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/availableBalance/default", ) # pylint: disable=line-too-long path_format_arguments = { "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), "billingProfileName": _SERIALIZER.url("billing_profile_name", billing_profile_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) class AvailableBalancesOperations: """ .. warning:: **DO NOT** instantiate this class directly. Instead, you should access the following operations through :class:`~azure.mgmt.billing.BillingManagementClient`'s :attr:`available_balances` attribute. """ models = _models def __init__(self, *args, **kwargs): input_args = list(args) self._client = input_args.pop(0) if input_args else kwargs.pop("client") self._config = input_args.pop(0) if input_args else kwargs.pop("config") self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace def get(self, billing_account_name: str, billing_profile_name: str, **kwargs: Any) -> _models.AvailableBalance: """The available credit balance for a billing profile. This is the balance that can be used for pay now to settle due or past due invoices. The operation is supported only for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: AvailableBalance or the result of cls(response) :rtype: ~azure.mgmt.billing.models.AvailableBalance :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.AvailableBalance] request = build_get_request( billing_account_name=billing_account_name, billing_profile_name=billing_profile_name, api_version=api_version, template_url=self.get.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize("AvailableBalance", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/availableBalance/default"} # type: ignore
0.622
0.081666
import sys from typing import Any, Callable, Dict, IO, Iterable, List, Optional, TypeVar, Union, cast, overload from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, map_error, ) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse from azure.core.polling import LROPoller, NoPolling, PollingMethod from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.arm_polling import ARMPolling from .. import models as _models from .._serialization import Serializer from .._vendor import _convert_request, _format_url_section if sys.version_info >= (3, 8): from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports else: from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False def build_list_by_billing_account_request( billing_account_name: str, *, period_start_date: str, period_end_date: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop("template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/invoices") path_format_arguments = { "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") _params["periodStartDate"] = _SERIALIZER.query("period_start_date", period_start_date, "str") _params["periodEndDate"] = _SERIALIZER.query("period_end_date", period_end_date, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_list_by_billing_profile_request( billing_account_name: str, billing_profile_name: str, *, period_start_date: str, period_end_date: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoices", ) # pylint: disable=line-too-long path_format_arguments = { "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), "billingProfileName": _SERIALIZER.url("billing_profile_name", billing_profile_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") _params["periodStartDate"] = _SERIALIZER.query("period_start_date", period_start_date, "str") _params["periodEndDate"] = _SERIALIZER.query("period_end_date", period_end_date, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_get_request(billing_account_name: str, invoice_name: str, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/invoices/{invoiceName}" ) # pylint: disable=line-too-long path_format_arguments = { "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), "invoiceName": _SERIALIZER.url("invoice_name", invoice_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_get_by_id_request(invoice_name: str, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop("template_url", "/providers/Microsoft.Billing/billingAccounts/default/invoices/{invoiceName}") path_format_arguments = { "invoiceName": _SERIALIZER.url("invoice_name", invoice_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_download_invoice_request( billing_account_name: str, invoice_name: str, *, download_token: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/invoices/{invoiceName}/download", ) # pylint: disable=line-too-long path_format_arguments = { "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), "invoiceName": _SERIALIZER.url("invoice_name", invoice_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") _params["downloadToken"] = _SERIALIZER.query("download_token", download_token, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) def build_download_multiple_billing_profile_invoices_request(billing_account_name: str, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/downloadDocuments" ) path_format_arguments = { "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers if content_type is not None: _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) def build_list_by_billing_subscription_request( subscription_id: str, *, period_start_date: str, period_end_date: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/providers/Microsoft.Billing/billingAccounts/default/billingSubscriptions/{subscriptionId}/invoices", ) # pylint: disable=line-too-long path_format_arguments = { "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["periodStartDate"] = _SERIALIZER.query("period_start_date", period_start_date, "str") _params["periodEndDate"] = _SERIALIZER.query("period_end_date", period_end_date, "str") _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_get_by_subscription_and_invoice_id_request( invoice_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/providers/Microsoft.Billing/billingAccounts/default/billingSubscriptions/{subscriptionId}/invoices/{invoiceName}", ) # pylint: disable=line-too-long path_format_arguments = { "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), "invoiceName": _SERIALIZER.url("invoice_name", invoice_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_download_billing_subscription_invoice_request( invoice_name: str, subscription_id: str, *, download_token: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/providers/Microsoft.Billing/billingAccounts/default/billingSubscriptions/{subscriptionId}/invoices/{invoiceName}/download", ) # pylint: disable=line-too-long path_format_arguments = { "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), "invoiceName": _SERIALIZER.url("invoice_name", invoice_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") _params["downloadToken"] = _SERIALIZER.query("download_token", download_token, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) def build_download_multiple_billing_subscription_invoices_request(subscription_id: str, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/providers/Microsoft.Billing/billingAccounts/default/billingSubscriptions/{subscriptionId}/downloadDocuments", ) # pylint: disable=line-too-long path_format_arguments = { "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers if content_type is not None: _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) class InvoicesOperations: """ .. warning:: **DO NOT** instantiate this class directly. Instead, you should access the following operations through :class:`~azure.mgmt.billing.BillingManagementClient`'s :attr:`invoices` attribute. """ models = _models def __init__(self, *args, **kwargs): input_args = list(args) self._client = input_args.pop(0) if input_args else kwargs.pop("client") self._config = input_args.pop(0) if input_args else kwargs.pop("config") self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace def list_by_billing_account( self, billing_account_name: str, period_start_date: str, period_end_date: str, **kwargs: Any ) -> Iterable["_models.Invoice"]: """Lists the invoices for a billing account for a given start date and end date. The operation is supported for billing accounts with agreement type Microsoft Partner Agreement or Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param period_start_date: The start date to fetch the invoices. The date should be specified in MM-DD-YYYY format. Required. :type period_start_date: str :param period_end_date: The end date to fetch the invoices. The date should be specified in MM-DD-YYYY format. Required. :type period_end_date: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either Invoice or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billing.models.Invoice] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.InvoiceListResult] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_by_billing_account_request( billing_account_name=billing_account_name, period_start_date=period_start_date, period_end_date=period_end_date, api_version=api_version, template_url=self.list_by_billing_account.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore else: request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request def extract_data(pipeline_response): deserialized = self._deserialize("InvoiceListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return ItemPaged(get_next, extract_data) list_by_billing_account.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/invoices"} # type: ignore @distributed_trace def list_by_billing_profile( self, billing_account_name: str, billing_profile_name: str, period_start_date: str, period_end_date: str, **kwargs: Any ) -> Iterable["_models.Invoice"]: """Lists the invoices for a billing profile for a given start date and end date. The operation is supported for billing accounts with agreement type Microsoft Partner Agreement or Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :param period_start_date: The start date to fetch the invoices. The date should be specified in MM-DD-YYYY format. Required. :type period_start_date: str :param period_end_date: The end date to fetch the invoices. The date should be specified in MM-DD-YYYY format. Required. :type period_end_date: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either Invoice or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billing.models.Invoice] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.InvoiceListResult] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_by_billing_profile_request( billing_account_name=billing_account_name, billing_profile_name=billing_profile_name, period_start_date=period_start_date, period_end_date=period_end_date, api_version=api_version, template_url=self.list_by_billing_profile.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore else: request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request def extract_data(pipeline_response): deserialized = self._deserialize("InvoiceListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return ItemPaged(get_next, extract_data) list_by_billing_profile.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoices"} # type: ignore @distributed_trace def get(self, billing_account_name: str, invoice_name: str, **kwargs: Any) -> _models.Invoice: """Gets an invoice by billing account name and ID. The operation is supported for billing accounts with agreement type Microsoft Partner Agreement or Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param invoice_name: The ID that uniquely identifies an invoice. Required. :type invoice_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Invoice or the result of cls(response) :rtype: ~azure.mgmt.billing.models.Invoice :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.Invoice] request = build_get_request( billing_account_name=billing_account_name, invoice_name=invoice_name, api_version=api_version, template_url=self.get.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize("Invoice", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/invoices/{invoiceName}"} # type: ignore @distributed_trace def get_by_id(self, invoice_name: str, **kwargs: Any) -> _models.Invoice: """Gets an invoice by ID. The operation is supported for billing accounts with agreement type Microsoft Partner Agreement or Microsoft Customer Agreement. :param invoice_name: The ID that uniquely identifies an invoice. Required. :type invoice_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Invoice or the result of cls(response) :rtype: ~azure.mgmt.billing.models.Invoice :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.Invoice] request = build_get_by_id_request( invoice_name=invoice_name, api_version=api_version, template_url=self.get_by_id.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize("Invoice", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get_by_id.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/default/invoices/{invoiceName}"} # type: ignore def _download_invoice_initial( self, billing_account_name: str, invoice_name: str, download_token: str, **kwargs: Any ) -> Optional[_models.DownloadUrl]: error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.DownloadUrl]] request = build_download_invoice_request( billing_account_name=billing_account_name, invoice_name=invoice_name, download_token=download_token, api_version=api_version, template_url=self._download_invoice_initial.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = None response_headers = {} if response.status_code == 200: deserialized = self._deserialize("DownloadUrl", pipeline_response) if response.status_code == 202: response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) response_headers["Retry-After"] = self._deserialize("str", response.headers.get("Retry-After")) if cls: return cls(pipeline_response, deserialized, response_headers) return deserialized _download_invoice_initial.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/invoices/{invoiceName}/download"} # type: ignore @distributed_trace def begin_download_invoice( self, billing_account_name: str, invoice_name: str, download_token: str, **kwargs: Any ) -> LROPoller[_models.DownloadUrl]: """Gets a URL to download an invoice. The operation is supported for billing accounts with agreement type Microsoft Partner Agreement or Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param invoice_name: The ID that uniquely identifies an invoice. Required. :type invoice_name: str :param download_token: Download token with document source and document ID. Required. :type download_token: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.PollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of LROPoller that returns either DownloadUrl or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.billing.models.DownloadUrl] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.DownloadUrl] polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod] lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: raw_result = self._download_invoice_initial( # type: ignore billing_account_name=billing_account_name, invoice_name=invoice_name, download_token=download_token, api_version=api_version, cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): deserialized = self._deserialize("DownloadUrl", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized if polling is True: polling_method = cast( PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) ) # type: PollingMethod elif polling is False: polling_method = cast(PollingMethod, NoPolling()) else: polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) return LROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_download_invoice.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/invoices/{invoiceName}/download"} # type: ignore def _download_multiple_billing_profile_invoices_initial( self, billing_account_name: str, download_urls: Union[List[str], IO], **kwargs: Any ) -> Optional[_models.DownloadUrl]: error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.DownloadUrl]] content_type = content_type or "application/json" _json = None _content = None if isinstance(download_urls, (IO, bytes)): _content = download_urls else: _json = self._serialize.body(download_urls, "[str]") request = build_download_multiple_billing_profile_invoices_request( billing_account_name=billing_account_name, api_version=api_version, content_type=content_type, json=_json, content=_content, template_url=self._download_multiple_billing_profile_invoices_initial.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = None response_headers = {} if response.status_code == 200: deserialized = self._deserialize("DownloadUrl", pipeline_response) if response.status_code == 202: response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) response_headers["Retry-After"] = self._deserialize("str", response.headers.get("Retry-After")) if cls: return cls(pipeline_response, deserialized, response_headers) return deserialized _download_multiple_billing_profile_invoices_initial.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/downloadDocuments"} # type: ignore @overload def begin_download_multiple_billing_profile_invoices( self, billing_account_name: str, download_urls: List[str], *, content_type: str = "application/json", **kwargs: Any ) -> LROPoller[_models.DownloadUrl]: """Gets a URL to download multiple invoice documents (invoice pdf, tax receipts, credit notes) as a zip file. The operation is supported for billing accounts with agreement type Microsoft Partner Agreement or Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param download_urls: An array of download urls for individual documents. Required. :type download_urls: list[str] :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.PollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of LROPoller that returns either DownloadUrl or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.billing.models.DownloadUrl] :raises ~azure.core.exceptions.HttpResponseError: """ @overload def begin_download_multiple_billing_profile_invoices( self, billing_account_name: str, download_urls: IO, *, content_type: str = "application/json", **kwargs: Any ) -> LROPoller[_models.DownloadUrl]: """Gets a URL to download multiple invoice documents (invoice pdf, tax receipts, credit notes) as a zip file. The operation is supported for billing accounts with agreement type Microsoft Partner Agreement or Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param download_urls: An array of download urls for individual documents. Required. :type download_urls: IO :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.PollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of LROPoller that returns either DownloadUrl or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.billing.models.DownloadUrl] :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace def begin_download_multiple_billing_profile_invoices( self, billing_account_name: str, download_urls: Union[List[str], IO], **kwargs: Any ) -> LROPoller[_models.DownloadUrl]: """Gets a URL to download multiple invoice documents (invoice pdf, tax receipts, credit notes) as a zip file. The operation is supported for billing accounts with agreement type Microsoft Partner Agreement or Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param download_urls: An array of download urls for individual documents. Is either a list type or a IO type. Required. :type download_urls: list[str] or IO :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. Default value is None. :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.PollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of LROPoller that returns either DownloadUrl or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.billing.models.DownloadUrl] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] cls = kwargs.pop("cls", None) # type: ClsType[_models.DownloadUrl] polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod] lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: raw_result = self._download_multiple_billing_profile_invoices_initial( # type: ignore billing_account_name=billing_account_name, download_urls=download_urls, api_version=api_version, content_type=content_type, cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): deserialized = self._deserialize("DownloadUrl", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized if polling is True: polling_method = cast( PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) ) # type: PollingMethod elif polling is False: polling_method = cast(PollingMethod, NoPolling()) else: polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) return LROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_download_multiple_billing_profile_invoices.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/downloadDocuments"} # type: ignore @distributed_trace def list_by_billing_subscription( self, period_start_date: str, period_end_date: str, **kwargs: Any ) -> Iterable["_models.Invoice"]: """Lists the invoices for a subscription. :param period_start_date: Invoice period start date. Required. :type period_start_date: str :param period_end_date: Invoice period end date. Required. :type period_end_date: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either Invoice or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billing.models.Invoice] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.InvoiceListResult] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_by_billing_subscription_request( subscription_id=self._config.subscription_id, period_start_date=period_start_date, period_end_date=period_end_date, api_version=api_version, template_url=self.list_by_billing_subscription.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore else: request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request def extract_data(pipeline_response): deserialized = self._deserialize("InvoiceListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return ItemPaged(get_next, extract_data) list_by_billing_subscription.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/default/billingSubscriptions/{subscriptionId}/invoices"} # type: ignore @distributed_trace def get_by_subscription_and_invoice_id(self, invoice_name: str, **kwargs: Any) -> _models.Invoice: """Gets an invoice by subscription ID and invoice ID. :param invoice_name: The ID that uniquely identifies an invoice. Required. :type invoice_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Invoice or the result of cls(response) :rtype: ~azure.mgmt.billing.models.Invoice :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.Invoice] request = build_get_by_subscription_and_invoice_id_request( invoice_name=invoice_name, subscription_id=self._config.subscription_id, api_version=api_version, template_url=self.get_by_subscription_and_invoice_id.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize("Invoice", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get_by_subscription_and_invoice_id.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/default/billingSubscriptions/{subscriptionId}/invoices/{invoiceName}"} # type: ignore def _download_billing_subscription_invoice_initial( self, invoice_name: str, download_token: str, **kwargs: Any ) -> Optional[_models.DownloadUrl]: error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.DownloadUrl]] request = build_download_billing_subscription_invoice_request( invoice_name=invoice_name, subscription_id=self._config.subscription_id, download_token=download_token, api_version=api_version, template_url=self._download_billing_subscription_invoice_initial.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = None response_headers = {} if response.status_code == 200: deserialized = self._deserialize("DownloadUrl", pipeline_response) if response.status_code == 202: response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) response_headers["Retry-After"] = self._deserialize("str", response.headers.get("Retry-After")) if cls: return cls(pipeline_response, deserialized, response_headers) return deserialized _download_billing_subscription_invoice_initial.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/default/billingSubscriptions/{subscriptionId}/invoices/{invoiceName}/download"} # type: ignore @distributed_trace def begin_download_billing_subscription_invoice( self, invoice_name: str, download_token: str, **kwargs: Any ) -> LROPoller[_models.DownloadUrl]: """Gets a URL to download an invoice. :param invoice_name: The ID that uniquely identifies an invoice. Required. :type invoice_name: str :param download_token: Download token with document source and document ID. Required. :type download_token: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.PollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of LROPoller that returns either DownloadUrl or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.billing.models.DownloadUrl] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.DownloadUrl] polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod] lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: raw_result = self._download_billing_subscription_invoice_initial( # type: ignore invoice_name=invoice_name, download_token=download_token, api_version=api_version, cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): deserialized = self._deserialize("DownloadUrl", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized if polling is True: polling_method = cast( PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) ) # type: PollingMethod elif polling is False: polling_method = cast(PollingMethod, NoPolling()) else: polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) return LROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_download_billing_subscription_invoice.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/default/billingSubscriptions/{subscriptionId}/invoices/{invoiceName}/download"} # type: ignore def _download_multiple_billing_subscription_invoices_initial( self, download_urls: Union[List[str], IO], **kwargs: Any ) -> Optional[_models.DownloadUrl]: error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.DownloadUrl]] content_type = content_type or "application/json" _json = None _content = None if isinstance(download_urls, (IO, bytes)): _content = download_urls else: _json = self._serialize.body(download_urls, "[str]") request = build_download_multiple_billing_subscription_invoices_request( subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, content=_content, template_url=self._download_multiple_billing_subscription_invoices_initial.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = None response_headers = {} if response.status_code == 200: deserialized = self._deserialize("DownloadUrl", pipeline_response) if response.status_code == 202: response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) response_headers["Retry-After"] = self._deserialize("str", response.headers.get("Retry-After")) if cls: return cls(pipeline_response, deserialized, response_headers) return deserialized _download_multiple_billing_subscription_invoices_initial.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/default/billingSubscriptions/{subscriptionId}/downloadDocuments"} # type: ignore @overload def begin_download_multiple_billing_subscription_invoices( self, download_urls: List[str], *, content_type: str = "application/json", **kwargs: Any ) -> LROPoller[_models.DownloadUrl]: """Gets a URL to download multiple invoice documents (invoice pdf, tax receipts, credit notes) as a zip file. :param download_urls: An array of download urls for individual documents. Required. :type download_urls: list[str] :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.PollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of LROPoller that returns either DownloadUrl or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.billing.models.DownloadUrl] :raises ~azure.core.exceptions.HttpResponseError: """ @overload def begin_download_multiple_billing_subscription_invoices( self, download_urls: IO, *, content_type: str = "application/json", **kwargs: Any ) -> LROPoller[_models.DownloadUrl]: """Gets a URL to download multiple invoice documents (invoice pdf, tax receipts, credit notes) as a zip file. :param download_urls: An array of download urls for individual documents. Required. :type download_urls: IO :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.PollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of LROPoller that returns either DownloadUrl or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.billing.models.DownloadUrl] :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace def begin_download_multiple_billing_subscription_invoices( self, download_urls: Union[List[str], IO], **kwargs: Any ) -> LROPoller[_models.DownloadUrl]: """Gets a URL to download multiple invoice documents (invoice pdf, tax receipts, credit notes) as a zip file. :param download_urls: An array of download urls for individual documents. Is either a list type or a IO type. Required. :type download_urls: list[str] or IO :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. Default value is None. :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.PollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of LROPoller that returns either DownloadUrl or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.billing.models.DownloadUrl] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] cls = kwargs.pop("cls", None) # type: ClsType[_models.DownloadUrl] polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod] lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: raw_result = self._download_multiple_billing_subscription_invoices_initial( # type: ignore download_urls=download_urls, api_version=api_version, content_type=content_type, cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): deserialized = self._deserialize("DownloadUrl", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized if polling is True: polling_method = cast( PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) ) # type: PollingMethod elif polling is False: polling_method = cast(PollingMethod, NoPolling()) else: polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) return LROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_download_multiple_billing_subscription_invoices.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/default/billingSubscriptions/{subscriptionId}/downloadDocuments"} # type: ignore
azure-mgmt-billing
/azure_mgmt_billing-6.1.0b1-py3-none-any.whl/azure/mgmt/billing/operations/_invoices_operations.py
_invoices_operations.py
import sys from typing import Any, Callable, Dict, IO, Iterable, List, Optional, TypeVar, Union, cast, overload from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, map_error, ) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse from azure.core.polling import LROPoller, NoPolling, PollingMethod from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.arm_polling import ARMPolling from .. import models as _models from .._serialization import Serializer from .._vendor import _convert_request, _format_url_section if sys.version_info >= (3, 8): from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports else: from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False def build_list_by_billing_account_request( billing_account_name: str, *, period_start_date: str, period_end_date: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop("template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/invoices") path_format_arguments = { "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") _params["periodStartDate"] = _SERIALIZER.query("period_start_date", period_start_date, "str") _params["periodEndDate"] = _SERIALIZER.query("period_end_date", period_end_date, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_list_by_billing_profile_request( billing_account_name: str, billing_profile_name: str, *, period_start_date: str, period_end_date: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoices", ) # pylint: disable=line-too-long path_format_arguments = { "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), "billingProfileName": _SERIALIZER.url("billing_profile_name", billing_profile_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") _params["periodStartDate"] = _SERIALIZER.query("period_start_date", period_start_date, "str") _params["periodEndDate"] = _SERIALIZER.query("period_end_date", period_end_date, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_get_request(billing_account_name: str, invoice_name: str, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/invoices/{invoiceName}" ) # pylint: disable=line-too-long path_format_arguments = { "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), "invoiceName": _SERIALIZER.url("invoice_name", invoice_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_get_by_id_request(invoice_name: str, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop("template_url", "/providers/Microsoft.Billing/billingAccounts/default/invoices/{invoiceName}") path_format_arguments = { "invoiceName": _SERIALIZER.url("invoice_name", invoice_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_download_invoice_request( billing_account_name: str, invoice_name: str, *, download_token: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/invoices/{invoiceName}/download", ) # pylint: disable=line-too-long path_format_arguments = { "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), "invoiceName": _SERIALIZER.url("invoice_name", invoice_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") _params["downloadToken"] = _SERIALIZER.query("download_token", download_token, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) def build_download_multiple_billing_profile_invoices_request(billing_account_name: str, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/downloadDocuments" ) path_format_arguments = { "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers if content_type is not None: _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) def build_list_by_billing_subscription_request( subscription_id: str, *, period_start_date: str, period_end_date: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/providers/Microsoft.Billing/billingAccounts/default/billingSubscriptions/{subscriptionId}/invoices", ) # pylint: disable=line-too-long path_format_arguments = { "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["periodStartDate"] = _SERIALIZER.query("period_start_date", period_start_date, "str") _params["periodEndDate"] = _SERIALIZER.query("period_end_date", period_end_date, "str") _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_get_by_subscription_and_invoice_id_request( invoice_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/providers/Microsoft.Billing/billingAccounts/default/billingSubscriptions/{subscriptionId}/invoices/{invoiceName}", ) # pylint: disable=line-too-long path_format_arguments = { "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), "invoiceName": _SERIALIZER.url("invoice_name", invoice_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_download_billing_subscription_invoice_request( invoice_name: str, subscription_id: str, *, download_token: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/providers/Microsoft.Billing/billingAccounts/default/billingSubscriptions/{subscriptionId}/invoices/{invoiceName}/download", ) # pylint: disable=line-too-long path_format_arguments = { "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), "invoiceName": _SERIALIZER.url("invoice_name", invoice_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") _params["downloadToken"] = _SERIALIZER.query("download_token", download_token, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) def build_download_multiple_billing_subscription_invoices_request(subscription_id: str, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/providers/Microsoft.Billing/billingAccounts/default/billingSubscriptions/{subscriptionId}/downloadDocuments", ) # pylint: disable=line-too-long path_format_arguments = { "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers if content_type is not None: _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) class InvoicesOperations: """ .. warning:: **DO NOT** instantiate this class directly. Instead, you should access the following operations through :class:`~azure.mgmt.billing.BillingManagementClient`'s :attr:`invoices` attribute. """ models = _models def __init__(self, *args, **kwargs): input_args = list(args) self._client = input_args.pop(0) if input_args else kwargs.pop("client") self._config = input_args.pop(0) if input_args else kwargs.pop("config") self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace def list_by_billing_account( self, billing_account_name: str, period_start_date: str, period_end_date: str, **kwargs: Any ) -> Iterable["_models.Invoice"]: """Lists the invoices for a billing account for a given start date and end date. The operation is supported for billing accounts with agreement type Microsoft Partner Agreement or Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param period_start_date: The start date to fetch the invoices. The date should be specified in MM-DD-YYYY format. Required. :type period_start_date: str :param period_end_date: The end date to fetch the invoices. The date should be specified in MM-DD-YYYY format. Required. :type period_end_date: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either Invoice or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billing.models.Invoice] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.InvoiceListResult] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_by_billing_account_request( billing_account_name=billing_account_name, period_start_date=period_start_date, period_end_date=period_end_date, api_version=api_version, template_url=self.list_by_billing_account.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore else: request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request def extract_data(pipeline_response): deserialized = self._deserialize("InvoiceListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return ItemPaged(get_next, extract_data) list_by_billing_account.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/invoices"} # type: ignore @distributed_trace def list_by_billing_profile( self, billing_account_name: str, billing_profile_name: str, period_start_date: str, period_end_date: str, **kwargs: Any ) -> Iterable["_models.Invoice"]: """Lists the invoices for a billing profile for a given start date and end date. The operation is supported for billing accounts with agreement type Microsoft Partner Agreement or Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :param period_start_date: The start date to fetch the invoices. The date should be specified in MM-DD-YYYY format. Required. :type period_start_date: str :param period_end_date: The end date to fetch the invoices. The date should be specified in MM-DD-YYYY format. Required. :type period_end_date: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either Invoice or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billing.models.Invoice] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.InvoiceListResult] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_by_billing_profile_request( billing_account_name=billing_account_name, billing_profile_name=billing_profile_name, period_start_date=period_start_date, period_end_date=period_end_date, api_version=api_version, template_url=self.list_by_billing_profile.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore else: request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request def extract_data(pipeline_response): deserialized = self._deserialize("InvoiceListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return ItemPaged(get_next, extract_data) list_by_billing_profile.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoices"} # type: ignore @distributed_trace def get(self, billing_account_name: str, invoice_name: str, **kwargs: Any) -> _models.Invoice: """Gets an invoice by billing account name and ID. The operation is supported for billing accounts with agreement type Microsoft Partner Agreement or Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param invoice_name: The ID that uniquely identifies an invoice. Required. :type invoice_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Invoice or the result of cls(response) :rtype: ~azure.mgmt.billing.models.Invoice :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.Invoice] request = build_get_request( billing_account_name=billing_account_name, invoice_name=invoice_name, api_version=api_version, template_url=self.get.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize("Invoice", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/invoices/{invoiceName}"} # type: ignore @distributed_trace def get_by_id(self, invoice_name: str, **kwargs: Any) -> _models.Invoice: """Gets an invoice by ID. The operation is supported for billing accounts with agreement type Microsoft Partner Agreement or Microsoft Customer Agreement. :param invoice_name: The ID that uniquely identifies an invoice. Required. :type invoice_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Invoice or the result of cls(response) :rtype: ~azure.mgmt.billing.models.Invoice :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.Invoice] request = build_get_by_id_request( invoice_name=invoice_name, api_version=api_version, template_url=self.get_by_id.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize("Invoice", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get_by_id.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/default/invoices/{invoiceName}"} # type: ignore def _download_invoice_initial( self, billing_account_name: str, invoice_name: str, download_token: str, **kwargs: Any ) -> Optional[_models.DownloadUrl]: error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.DownloadUrl]] request = build_download_invoice_request( billing_account_name=billing_account_name, invoice_name=invoice_name, download_token=download_token, api_version=api_version, template_url=self._download_invoice_initial.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = None response_headers = {} if response.status_code == 200: deserialized = self._deserialize("DownloadUrl", pipeline_response) if response.status_code == 202: response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) response_headers["Retry-After"] = self._deserialize("str", response.headers.get("Retry-After")) if cls: return cls(pipeline_response, deserialized, response_headers) return deserialized _download_invoice_initial.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/invoices/{invoiceName}/download"} # type: ignore @distributed_trace def begin_download_invoice( self, billing_account_name: str, invoice_name: str, download_token: str, **kwargs: Any ) -> LROPoller[_models.DownloadUrl]: """Gets a URL to download an invoice. The operation is supported for billing accounts with agreement type Microsoft Partner Agreement or Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param invoice_name: The ID that uniquely identifies an invoice. Required. :type invoice_name: str :param download_token: Download token with document source and document ID. Required. :type download_token: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.PollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of LROPoller that returns either DownloadUrl or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.billing.models.DownloadUrl] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.DownloadUrl] polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod] lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: raw_result = self._download_invoice_initial( # type: ignore billing_account_name=billing_account_name, invoice_name=invoice_name, download_token=download_token, api_version=api_version, cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): deserialized = self._deserialize("DownloadUrl", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized if polling is True: polling_method = cast( PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) ) # type: PollingMethod elif polling is False: polling_method = cast(PollingMethod, NoPolling()) else: polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) return LROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_download_invoice.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/invoices/{invoiceName}/download"} # type: ignore def _download_multiple_billing_profile_invoices_initial( self, billing_account_name: str, download_urls: Union[List[str], IO], **kwargs: Any ) -> Optional[_models.DownloadUrl]: error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.DownloadUrl]] content_type = content_type or "application/json" _json = None _content = None if isinstance(download_urls, (IO, bytes)): _content = download_urls else: _json = self._serialize.body(download_urls, "[str]") request = build_download_multiple_billing_profile_invoices_request( billing_account_name=billing_account_name, api_version=api_version, content_type=content_type, json=_json, content=_content, template_url=self._download_multiple_billing_profile_invoices_initial.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = None response_headers = {} if response.status_code == 200: deserialized = self._deserialize("DownloadUrl", pipeline_response) if response.status_code == 202: response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) response_headers["Retry-After"] = self._deserialize("str", response.headers.get("Retry-After")) if cls: return cls(pipeline_response, deserialized, response_headers) return deserialized _download_multiple_billing_profile_invoices_initial.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/downloadDocuments"} # type: ignore @overload def begin_download_multiple_billing_profile_invoices( self, billing_account_name: str, download_urls: List[str], *, content_type: str = "application/json", **kwargs: Any ) -> LROPoller[_models.DownloadUrl]: """Gets a URL to download multiple invoice documents (invoice pdf, tax receipts, credit notes) as a zip file. The operation is supported for billing accounts with agreement type Microsoft Partner Agreement or Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param download_urls: An array of download urls for individual documents. Required. :type download_urls: list[str] :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.PollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of LROPoller that returns either DownloadUrl or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.billing.models.DownloadUrl] :raises ~azure.core.exceptions.HttpResponseError: """ @overload def begin_download_multiple_billing_profile_invoices( self, billing_account_name: str, download_urls: IO, *, content_type: str = "application/json", **kwargs: Any ) -> LROPoller[_models.DownloadUrl]: """Gets a URL to download multiple invoice documents (invoice pdf, tax receipts, credit notes) as a zip file. The operation is supported for billing accounts with agreement type Microsoft Partner Agreement or Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param download_urls: An array of download urls for individual documents. Required. :type download_urls: IO :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.PollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of LROPoller that returns either DownloadUrl or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.billing.models.DownloadUrl] :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace def begin_download_multiple_billing_profile_invoices( self, billing_account_name: str, download_urls: Union[List[str], IO], **kwargs: Any ) -> LROPoller[_models.DownloadUrl]: """Gets a URL to download multiple invoice documents (invoice pdf, tax receipts, credit notes) as a zip file. The operation is supported for billing accounts with agreement type Microsoft Partner Agreement or Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param download_urls: An array of download urls for individual documents. Is either a list type or a IO type. Required. :type download_urls: list[str] or IO :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. Default value is None. :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.PollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of LROPoller that returns either DownloadUrl or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.billing.models.DownloadUrl] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] cls = kwargs.pop("cls", None) # type: ClsType[_models.DownloadUrl] polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod] lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: raw_result = self._download_multiple_billing_profile_invoices_initial( # type: ignore billing_account_name=billing_account_name, download_urls=download_urls, api_version=api_version, content_type=content_type, cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): deserialized = self._deserialize("DownloadUrl", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized if polling is True: polling_method = cast( PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) ) # type: PollingMethod elif polling is False: polling_method = cast(PollingMethod, NoPolling()) else: polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) return LROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_download_multiple_billing_profile_invoices.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/downloadDocuments"} # type: ignore @distributed_trace def list_by_billing_subscription( self, period_start_date: str, period_end_date: str, **kwargs: Any ) -> Iterable["_models.Invoice"]: """Lists the invoices for a subscription. :param period_start_date: Invoice period start date. Required. :type period_start_date: str :param period_end_date: Invoice period end date. Required. :type period_end_date: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either Invoice or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billing.models.Invoice] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.InvoiceListResult] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_by_billing_subscription_request( subscription_id=self._config.subscription_id, period_start_date=period_start_date, period_end_date=period_end_date, api_version=api_version, template_url=self.list_by_billing_subscription.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore else: request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request def extract_data(pipeline_response): deserialized = self._deserialize("InvoiceListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return ItemPaged(get_next, extract_data) list_by_billing_subscription.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/default/billingSubscriptions/{subscriptionId}/invoices"} # type: ignore @distributed_trace def get_by_subscription_and_invoice_id(self, invoice_name: str, **kwargs: Any) -> _models.Invoice: """Gets an invoice by subscription ID and invoice ID. :param invoice_name: The ID that uniquely identifies an invoice. Required. :type invoice_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Invoice or the result of cls(response) :rtype: ~azure.mgmt.billing.models.Invoice :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.Invoice] request = build_get_by_subscription_and_invoice_id_request( invoice_name=invoice_name, subscription_id=self._config.subscription_id, api_version=api_version, template_url=self.get_by_subscription_and_invoice_id.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize("Invoice", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get_by_subscription_and_invoice_id.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/default/billingSubscriptions/{subscriptionId}/invoices/{invoiceName}"} # type: ignore def _download_billing_subscription_invoice_initial( self, invoice_name: str, download_token: str, **kwargs: Any ) -> Optional[_models.DownloadUrl]: error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.DownloadUrl]] request = build_download_billing_subscription_invoice_request( invoice_name=invoice_name, subscription_id=self._config.subscription_id, download_token=download_token, api_version=api_version, template_url=self._download_billing_subscription_invoice_initial.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = None response_headers = {} if response.status_code == 200: deserialized = self._deserialize("DownloadUrl", pipeline_response) if response.status_code == 202: response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) response_headers["Retry-After"] = self._deserialize("str", response.headers.get("Retry-After")) if cls: return cls(pipeline_response, deserialized, response_headers) return deserialized _download_billing_subscription_invoice_initial.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/default/billingSubscriptions/{subscriptionId}/invoices/{invoiceName}/download"} # type: ignore @distributed_trace def begin_download_billing_subscription_invoice( self, invoice_name: str, download_token: str, **kwargs: Any ) -> LROPoller[_models.DownloadUrl]: """Gets a URL to download an invoice. :param invoice_name: The ID that uniquely identifies an invoice. Required. :type invoice_name: str :param download_token: Download token with document source and document ID. Required. :type download_token: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.PollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of LROPoller that returns either DownloadUrl or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.billing.models.DownloadUrl] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.DownloadUrl] polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod] lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: raw_result = self._download_billing_subscription_invoice_initial( # type: ignore invoice_name=invoice_name, download_token=download_token, api_version=api_version, cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): deserialized = self._deserialize("DownloadUrl", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized if polling is True: polling_method = cast( PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) ) # type: PollingMethod elif polling is False: polling_method = cast(PollingMethod, NoPolling()) else: polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) return LROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_download_billing_subscription_invoice.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/default/billingSubscriptions/{subscriptionId}/invoices/{invoiceName}/download"} # type: ignore def _download_multiple_billing_subscription_invoices_initial( self, download_urls: Union[List[str], IO], **kwargs: Any ) -> Optional[_models.DownloadUrl]: error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.DownloadUrl]] content_type = content_type or "application/json" _json = None _content = None if isinstance(download_urls, (IO, bytes)): _content = download_urls else: _json = self._serialize.body(download_urls, "[str]") request = build_download_multiple_billing_subscription_invoices_request( subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, content=_content, template_url=self._download_multiple_billing_subscription_invoices_initial.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = None response_headers = {} if response.status_code == 200: deserialized = self._deserialize("DownloadUrl", pipeline_response) if response.status_code == 202: response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) response_headers["Retry-After"] = self._deserialize("str", response.headers.get("Retry-After")) if cls: return cls(pipeline_response, deserialized, response_headers) return deserialized _download_multiple_billing_subscription_invoices_initial.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/default/billingSubscriptions/{subscriptionId}/downloadDocuments"} # type: ignore @overload def begin_download_multiple_billing_subscription_invoices( self, download_urls: List[str], *, content_type: str = "application/json", **kwargs: Any ) -> LROPoller[_models.DownloadUrl]: """Gets a URL to download multiple invoice documents (invoice pdf, tax receipts, credit notes) as a zip file. :param download_urls: An array of download urls for individual documents. Required. :type download_urls: list[str] :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.PollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of LROPoller that returns either DownloadUrl or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.billing.models.DownloadUrl] :raises ~azure.core.exceptions.HttpResponseError: """ @overload def begin_download_multiple_billing_subscription_invoices( self, download_urls: IO, *, content_type: str = "application/json", **kwargs: Any ) -> LROPoller[_models.DownloadUrl]: """Gets a URL to download multiple invoice documents (invoice pdf, tax receipts, credit notes) as a zip file. :param download_urls: An array of download urls for individual documents. Required. :type download_urls: IO :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.PollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of LROPoller that returns either DownloadUrl or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.billing.models.DownloadUrl] :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace def begin_download_multiple_billing_subscription_invoices( self, download_urls: Union[List[str], IO], **kwargs: Any ) -> LROPoller[_models.DownloadUrl]: """Gets a URL to download multiple invoice documents (invoice pdf, tax receipts, credit notes) as a zip file. :param download_urls: An array of download urls for individual documents. Is either a list type or a IO type. Required. :type download_urls: list[str] or IO :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. Default value is None. :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.PollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of LROPoller that returns either DownloadUrl or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.billing.models.DownloadUrl] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] cls = kwargs.pop("cls", None) # type: ClsType[_models.DownloadUrl] polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod] lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: raw_result = self._download_multiple_billing_subscription_invoices_initial( # type: ignore download_urls=download_urls, api_version=api_version, content_type=content_type, cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): deserialized = self._deserialize("DownloadUrl", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized if polling is True: polling_method = cast( PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) ) # type: PollingMethod elif polling is False: polling_method = cast(PollingMethod, NoPolling()) else: polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) return LROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_download_multiple_billing_subscription_invoices.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/default/billingSubscriptions/{subscriptionId}/downloadDocuments"} # type: ignore
0.633637
0.091951
import sys from typing import Any, Callable, Dict, Iterable, Optional, TypeVar from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, map_error, ) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models from .._serialization import Serializer from .._vendor import _convert_request, _format_url_section if sys.version_info >= (3, 8): from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports else: from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False def build_list_request(**kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop( "api_version", _params.pop("api-version", "2018-03-01-preview") ) # type: Literal["2018-03-01-preview"] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop("template_url", "/providers/Microsoft.Billing/enrollmentAccounts") # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_get_request(name: str, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop( "api_version", _params.pop("api-version", "2018-03-01-preview") ) # type: Literal["2018-03-01-preview"] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop("template_url", "/providers/Microsoft.Billing/enrollmentAccounts/{name}") path_format_arguments = { "name": _SERIALIZER.url("name", name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) class EnrollmentAccountsOperations: """ .. warning:: **DO NOT** instantiate this class directly. Instead, you should access the following operations through :class:`~azure.mgmt.billing.BillingManagementClient`'s :attr:`enrollment_accounts` attribute. """ models = _models def __init__(self, *args, **kwargs): input_args = list(args) self._client = input_args.pop(0) if input_args else kwargs.pop("client") self._config = input_args.pop(0) if input_args else kwargs.pop("config") self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace def list(self, **kwargs: Any) -> Iterable["_models.EnrollmentAccountSummary"]: """Lists the enrollment accounts the caller has access to. :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either EnrollmentAccountSummary or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billing.models.EnrollmentAccountSummary] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop( "api_version", _params.pop("api-version", "2018-03-01-preview") ) # type: Literal["2018-03-01-preview"] cls = kwargs.pop("cls", None) # type: ClsType[_models.EnrollmentAccountListResult] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_request( api_version=api_version, template_url=self.list.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore else: request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request def extract_data(pipeline_response): deserialized = self._deserialize("EnrollmentAccountListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return ItemPaged(get_next, extract_data) list.metadata = {"url": "/providers/Microsoft.Billing/enrollmentAccounts"} # type: ignore @distributed_trace def get(self, name: str, **kwargs: Any) -> _models.EnrollmentAccountSummary: """Gets a enrollment account by name. :param name: Enrollment Account name. Required. :type name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: EnrollmentAccountSummary or the result of cls(response) :rtype: ~azure.mgmt.billing.models.EnrollmentAccountSummary :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop( "api_version", _params.pop("api-version", "2018-03-01-preview") ) # type: Literal["2018-03-01-preview"] cls = kwargs.pop("cls", None) # type: ClsType[_models.EnrollmentAccountSummary] request = build_get_request( name=name, api_version=api_version, template_url=self.get.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize("EnrollmentAccountSummary", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get.metadata = {"url": "/providers/Microsoft.Billing/enrollmentAccounts/{name}"} # type: ignore
azure-mgmt-billing
/azure_mgmt_billing-6.1.0b1-py3-none-any.whl/azure/mgmt/billing/operations/_enrollment_accounts_operations.py
_enrollment_accounts_operations.py
import sys from typing import Any, Callable, Dict, Iterable, Optional, TypeVar from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, map_error, ) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models from .._serialization import Serializer from .._vendor import _convert_request, _format_url_section if sys.version_info >= (3, 8): from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports else: from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False def build_list_request(**kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop( "api_version", _params.pop("api-version", "2018-03-01-preview") ) # type: Literal["2018-03-01-preview"] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop("template_url", "/providers/Microsoft.Billing/enrollmentAccounts") # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_get_request(name: str, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop( "api_version", _params.pop("api-version", "2018-03-01-preview") ) # type: Literal["2018-03-01-preview"] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop("template_url", "/providers/Microsoft.Billing/enrollmentAccounts/{name}") path_format_arguments = { "name": _SERIALIZER.url("name", name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) class EnrollmentAccountsOperations: """ .. warning:: **DO NOT** instantiate this class directly. Instead, you should access the following operations through :class:`~azure.mgmt.billing.BillingManagementClient`'s :attr:`enrollment_accounts` attribute. """ models = _models def __init__(self, *args, **kwargs): input_args = list(args) self._client = input_args.pop(0) if input_args else kwargs.pop("client") self._config = input_args.pop(0) if input_args else kwargs.pop("config") self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace def list(self, **kwargs: Any) -> Iterable["_models.EnrollmentAccountSummary"]: """Lists the enrollment accounts the caller has access to. :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either EnrollmentAccountSummary or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billing.models.EnrollmentAccountSummary] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop( "api_version", _params.pop("api-version", "2018-03-01-preview") ) # type: Literal["2018-03-01-preview"] cls = kwargs.pop("cls", None) # type: ClsType[_models.EnrollmentAccountListResult] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_request( api_version=api_version, template_url=self.list.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore else: request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request def extract_data(pipeline_response): deserialized = self._deserialize("EnrollmentAccountListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return ItemPaged(get_next, extract_data) list.metadata = {"url": "/providers/Microsoft.Billing/enrollmentAccounts"} # type: ignore @distributed_trace def get(self, name: str, **kwargs: Any) -> _models.EnrollmentAccountSummary: """Gets a enrollment account by name. :param name: Enrollment Account name. Required. :type name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: EnrollmentAccountSummary or the result of cls(response) :rtype: ~azure.mgmt.billing.models.EnrollmentAccountSummary :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop( "api_version", _params.pop("api-version", "2018-03-01-preview") ) # type: Literal["2018-03-01-preview"] cls = kwargs.pop("cls", None) # type: ClsType[_models.EnrollmentAccountSummary] request = build_get_request( name=name, api_version=api_version, template_url=self.get.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize("EnrollmentAccountSummary", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get.metadata = {"url": "/providers/Microsoft.Billing/enrollmentAccounts/{name}"} # type: ignore
0.648578
0.069605
import sys from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, overload from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, map_error, ) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models from .._serialization import Serializer from .._vendor import _convert_request if sys.version_info >= (3, 8): from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports else: from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False def build_validate_request(**kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop("template_url", "/providers/Microsoft.Billing/validateAddress") # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers if content_type is not None: _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) class AddressOperations: """ .. warning:: **DO NOT** instantiate this class directly. Instead, you should access the following operations through :class:`~azure.mgmt.billing.BillingManagementClient`'s :attr:`address` attribute. """ models = _models def __init__(self, *args, **kwargs): input_args = list(args) self._client = input_args.pop(0) if input_args else kwargs.pop("client") self._config = input_args.pop(0) if input_args else kwargs.pop("config") self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @overload def validate( self, address: _models.AddressDetails, *, content_type: str = "application/json", **kwargs: Any ) -> _models.ValidateAddressResponse: """Validates an address. Use the operation to validate an address before using it as soldTo or a billTo address. :param address: Required. :type address: ~azure.mgmt.billing.models.AddressDetails :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: ValidateAddressResponse or the result of cls(response) :rtype: ~azure.mgmt.billing.models.ValidateAddressResponse :raises ~azure.core.exceptions.HttpResponseError: """ @overload def validate( self, address: IO, *, content_type: str = "application/json", **kwargs: Any ) -> _models.ValidateAddressResponse: """Validates an address. Use the operation to validate an address before using it as soldTo or a billTo address. :param address: Required. :type address: IO :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: ValidateAddressResponse or the result of cls(response) :rtype: ~azure.mgmt.billing.models.ValidateAddressResponse :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace def validate(self, address: Union[_models.AddressDetails, IO], **kwargs: Any) -> _models.ValidateAddressResponse: """Validates an address. Use the operation to validate an address before using it as soldTo or a billTo address. :param address: Is either a model type or a IO type. Required. :type address: ~azure.mgmt.billing.models.AddressDetails or IO :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. Default value is None. :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: ValidateAddressResponse or the result of cls(response) :rtype: ~azure.mgmt.billing.models.ValidateAddressResponse :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] cls = kwargs.pop("cls", None) # type: ClsType[_models.ValidateAddressResponse] content_type = content_type or "application/json" _json = None _content = None if isinstance(address, (IO, bytes)): _content = address else: _json = self._serialize.body(address, "AddressDetails") request = build_validate_request( api_version=api_version, content_type=content_type, json=_json, content=_content, template_url=self.validate.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize("ValidateAddressResponse", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized validate.metadata = {"url": "/providers/Microsoft.Billing/validateAddress"} # type: ignore
azure-mgmt-billing
/azure_mgmt_billing-6.1.0b1-py3-none-any.whl/azure/mgmt/billing/operations/_address_operations.py
_address_operations.py
import sys from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, overload from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, map_error, ) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models from .._serialization import Serializer from .._vendor import _convert_request if sys.version_info >= (3, 8): from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports else: from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False def build_validate_request(**kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop("template_url", "/providers/Microsoft.Billing/validateAddress") # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers if content_type is not None: _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) class AddressOperations: """ .. warning:: **DO NOT** instantiate this class directly. Instead, you should access the following operations through :class:`~azure.mgmt.billing.BillingManagementClient`'s :attr:`address` attribute. """ models = _models def __init__(self, *args, **kwargs): input_args = list(args) self._client = input_args.pop(0) if input_args else kwargs.pop("client") self._config = input_args.pop(0) if input_args else kwargs.pop("config") self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @overload def validate( self, address: _models.AddressDetails, *, content_type: str = "application/json", **kwargs: Any ) -> _models.ValidateAddressResponse: """Validates an address. Use the operation to validate an address before using it as soldTo or a billTo address. :param address: Required. :type address: ~azure.mgmt.billing.models.AddressDetails :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: ValidateAddressResponse or the result of cls(response) :rtype: ~azure.mgmt.billing.models.ValidateAddressResponse :raises ~azure.core.exceptions.HttpResponseError: """ @overload def validate( self, address: IO, *, content_type: str = "application/json", **kwargs: Any ) -> _models.ValidateAddressResponse: """Validates an address. Use the operation to validate an address before using it as soldTo or a billTo address. :param address: Required. :type address: IO :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: ValidateAddressResponse or the result of cls(response) :rtype: ~azure.mgmt.billing.models.ValidateAddressResponse :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace def validate(self, address: Union[_models.AddressDetails, IO], **kwargs: Any) -> _models.ValidateAddressResponse: """Validates an address. Use the operation to validate an address before using it as soldTo or a billTo address. :param address: Is either a model type or a IO type. Required. :type address: ~azure.mgmt.billing.models.AddressDetails or IO :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. Default value is None. :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: ValidateAddressResponse or the result of cls(response) :rtype: ~azure.mgmt.billing.models.ValidateAddressResponse :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] cls = kwargs.pop("cls", None) # type: ClsType[_models.ValidateAddressResponse] content_type = content_type or "application/json" _json = None _content = None if isinstance(address, (IO, bytes)): _content = address else: _json = self._serialize.body(address, "AddressDetails") request = build_validate_request( api_version=api_version, content_type=content_type, json=_json, content=_content, template_url=self.validate.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize("ValidateAddressResponse", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized validate.metadata = {"url": "/providers/Microsoft.Billing/validateAddress"} # type: ignore
0.728265
0.092524
from copy import deepcopy from typing import Any, Awaitable, TYPE_CHECKING from azure.core.rest import AsyncHttpResponse, HttpRequest from azure.mgmt.core import AsyncARMPipelineClient from .. import models from .._serialization import Deserializer, Serializer from ._configuration import BillingManagementClientConfiguration from .operations import ( AddressOperations, AgreementsOperations, AvailableBalancesOperations, BillingAccountsOperations, BillingPeriodsOperations, BillingPermissionsOperations, BillingProfilesOperations, BillingPropertyOperations, BillingRoleAssignmentsOperations, BillingRoleDefinitionsOperations, BillingSubscriptionsOperations, CustomersOperations, EnrollmentAccountsOperations, InstructionsOperations, InvoiceSectionsOperations, InvoicesOperations, Operations, PoliciesOperations, ProductsOperations, ReservationsOperations, TransactionsOperations, ) if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential class BillingManagementClient: # pylint: disable=client-accepts-api-version-keyword,too-many-instance-attributes """Billing client provides access to billing resources for Azure subscriptions. :ivar billing_accounts: BillingAccountsOperations operations :vartype billing_accounts: azure.mgmt.billing.aio.operations.BillingAccountsOperations :ivar address: AddressOperations operations :vartype address: azure.mgmt.billing.aio.operations.AddressOperations :ivar available_balances: AvailableBalancesOperations operations :vartype available_balances: azure.mgmt.billing.aio.operations.AvailableBalancesOperations :ivar instructions: InstructionsOperations operations :vartype instructions: azure.mgmt.billing.aio.operations.InstructionsOperations :ivar billing_profiles: BillingProfilesOperations operations :vartype billing_profiles: azure.mgmt.billing.aio.operations.BillingProfilesOperations :ivar customers: CustomersOperations operations :vartype customers: azure.mgmt.billing.aio.operations.CustomersOperations :ivar invoice_sections: InvoiceSectionsOperations operations :vartype invoice_sections: azure.mgmt.billing.aio.operations.InvoiceSectionsOperations :ivar billing_permissions: BillingPermissionsOperations operations :vartype billing_permissions: azure.mgmt.billing.aio.operations.BillingPermissionsOperations :ivar billing_subscriptions: BillingSubscriptionsOperations operations :vartype billing_subscriptions: azure.mgmt.billing.aio.operations.BillingSubscriptionsOperations :ivar products: ProductsOperations operations :vartype products: azure.mgmt.billing.aio.operations.ProductsOperations :ivar invoices: InvoicesOperations operations :vartype invoices: azure.mgmt.billing.aio.operations.InvoicesOperations :ivar transactions: TransactionsOperations operations :vartype transactions: azure.mgmt.billing.aio.operations.TransactionsOperations :ivar policies: PoliciesOperations operations :vartype policies: azure.mgmt.billing.aio.operations.PoliciesOperations :ivar billing_property: BillingPropertyOperations operations :vartype billing_property: azure.mgmt.billing.aio.operations.BillingPropertyOperations :ivar billing_role_definitions: BillingRoleDefinitionsOperations operations :vartype billing_role_definitions: azure.mgmt.billing.aio.operations.BillingRoleDefinitionsOperations :ivar billing_role_assignments: BillingRoleAssignmentsOperations operations :vartype billing_role_assignments: azure.mgmt.billing.aio.operations.BillingRoleAssignmentsOperations :ivar agreements: AgreementsOperations operations :vartype agreements: azure.mgmt.billing.aio.operations.AgreementsOperations :ivar reservations: ReservationsOperations operations :vartype reservations: azure.mgmt.billing.aio.operations.ReservationsOperations :ivar enrollment_accounts: EnrollmentAccountsOperations operations :vartype enrollment_accounts: azure.mgmt.billing.aio.operations.EnrollmentAccountsOperations :ivar billing_periods: BillingPeriodsOperations operations :vartype billing_periods: azure.mgmt.billing.aio.operations.BillingPeriodsOperations :ivar operations: Operations operations :vartype operations: azure.mgmt.billing.aio.operations.Operations :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials_async.AsyncTokenCredential :param subscription_id: The ID that uniquely identifies an Azure subscription. Required. :type subscription_id: str :param base_url: Service URL. Default value is "https://management.azure.com". :type base_url: str :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. """ def __init__( self, credential: "AsyncTokenCredential", subscription_id: str, base_url: str = "https://management.azure.com", **kwargs: Any ) -> None: self._config = BillingManagementClientConfiguration( credential=credential, subscription_id=subscription_id, **kwargs ) self._client = AsyncARMPipelineClient(base_url=base_url, config=self._config, **kwargs) client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} self._serialize = Serializer(client_models) self._deserialize = Deserializer(client_models) self._serialize.client_side_validation = False self.billing_accounts = BillingAccountsOperations( self._client, self._config, self._serialize, self._deserialize ) self.address = AddressOperations(self._client, self._config, self._serialize, self._deserialize) self.available_balances = AvailableBalancesOperations( self._client, self._config, self._serialize, self._deserialize ) self.instructions = InstructionsOperations(self._client, self._config, self._serialize, self._deserialize) self.billing_profiles = BillingProfilesOperations( self._client, self._config, self._serialize, self._deserialize ) self.customers = CustomersOperations(self._client, self._config, self._serialize, self._deserialize) self.invoice_sections = InvoiceSectionsOperations( self._client, self._config, self._serialize, self._deserialize ) self.billing_permissions = BillingPermissionsOperations( self._client, self._config, self._serialize, self._deserialize ) self.billing_subscriptions = BillingSubscriptionsOperations( self._client, self._config, self._serialize, self._deserialize ) self.products = ProductsOperations(self._client, self._config, self._serialize, self._deserialize) self.invoices = InvoicesOperations(self._client, self._config, self._serialize, self._deserialize) self.transactions = TransactionsOperations(self._client, self._config, self._serialize, self._deserialize) self.policies = PoliciesOperations(self._client, self._config, self._serialize, self._deserialize) self.billing_property = BillingPropertyOperations( self._client, self._config, self._serialize, self._deserialize ) self.billing_role_definitions = BillingRoleDefinitionsOperations( self._client, self._config, self._serialize, self._deserialize ) self.billing_role_assignments = BillingRoleAssignmentsOperations( self._client, self._config, self._serialize, self._deserialize ) self.agreements = AgreementsOperations(self._client, self._config, self._serialize, self._deserialize) self.reservations = ReservationsOperations(self._client, self._config, self._serialize, self._deserialize) self.enrollment_accounts = EnrollmentAccountsOperations( self._client, self._config, self._serialize, self._deserialize ) self.billing_periods = BillingPeriodsOperations(self._client, self._config, self._serialize, self._deserialize) self.operations = Operations(self._client, self._config, self._serialize, self._deserialize) def _send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]: """Runs the network request through the client's chained policies. >>> from azure.core.rest import HttpRequest >>> request = HttpRequest("GET", "https://www.example.org/") <HttpRequest [GET], url: 'https://www.example.org/'> >>> response = await client._send_request(request) <AsyncHttpResponse: 200 OK> For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request :param request: The network request you want to make. Required. :type request: ~azure.core.rest.HttpRequest :keyword bool stream: Whether the response payload will be streamed. Defaults to False. :return: The response of your network call. Does not do error handling on your response. :rtype: ~azure.core.rest.AsyncHttpResponse """ request_copy = deepcopy(request) request_copy.url = self._client.format_url(request_copy.url) return self._client.send_request(request_copy, **kwargs) async def close(self) -> None: await self._client.close() async def __aenter__(self) -> "BillingManagementClient": await self._client.__aenter__() return self async def __aexit__(self, *exc_details) -> None: await self._client.__aexit__(*exc_details)
azure-mgmt-billing
/azure_mgmt_billing-6.1.0b1-py3-none-any.whl/azure/mgmt/billing/aio/_billing_management_client.py
_billing_management_client.py
from copy import deepcopy from typing import Any, Awaitable, TYPE_CHECKING from azure.core.rest import AsyncHttpResponse, HttpRequest from azure.mgmt.core import AsyncARMPipelineClient from .. import models from .._serialization import Deserializer, Serializer from ._configuration import BillingManagementClientConfiguration from .operations import ( AddressOperations, AgreementsOperations, AvailableBalancesOperations, BillingAccountsOperations, BillingPeriodsOperations, BillingPermissionsOperations, BillingProfilesOperations, BillingPropertyOperations, BillingRoleAssignmentsOperations, BillingRoleDefinitionsOperations, BillingSubscriptionsOperations, CustomersOperations, EnrollmentAccountsOperations, InstructionsOperations, InvoiceSectionsOperations, InvoicesOperations, Operations, PoliciesOperations, ProductsOperations, ReservationsOperations, TransactionsOperations, ) if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential class BillingManagementClient: # pylint: disable=client-accepts-api-version-keyword,too-many-instance-attributes """Billing client provides access to billing resources for Azure subscriptions. :ivar billing_accounts: BillingAccountsOperations operations :vartype billing_accounts: azure.mgmt.billing.aio.operations.BillingAccountsOperations :ivar address: AddressOperations operations :vartype address: azure.mgmt.billing.aio.operations.AddressOperations :ivar available_balances: AvailableBalancesOperations operations :vartype available_balances: azure.mgmt.billing.aio.operations.AvailableBalancesOperations :ivar instructions: InstructionsOperations operations :vartype instructions: azure.mgmt.billing.aio.operations.InstructionsOperations :ivar billing_profiles: BillingProfilesOperations operations :vartype billing_profiles: azure.mgmt.billing.aio.operations.BillingProfilesOperations :ivar customers: CustomersOperations operations :vartype customers: azure.mgmt.billing.aio.operations.CustomersOperations :ivar invoice_sections: InvoiceSectionsOperations operations :vartype invoice_sections: azure.mgmt.billing.aio.operations.InvoiceSectionsOperations :ivar billing_permissions: BillingPermissionsOperations operations :vartype billing_permissions: azure.mgmt.billing.aio.operations.BillingPermissionsOperations :ivar billing_subscriptions: BillingSubscriptionsOperations operations :vartype billing_subscriptions: azure.mgmt.billing.aio.operations.BillingSubscriptionsOperations :ivar products: ProductsOperations operations :vartype products: azure.mgmt.billing.aio.operations.ProductsOperations :ivar invoices: InvoicesOperations operations :vartype invoices: azure.mgmt.billing.aio.operations.InvoicesOperations :ivar transactions: TransactionsOperations operations :vartype transactions: azure.mgmt.billing.aio.operations.TransactionsOperations :ivar policies: PoliciesOperations operations :vartype policies: azure.mgmt.billing.aio.operations.PoliciesOperations :ivar billing_property: BillingPropertyOperations operations :vartype billing_property: azure.mgmt.billing.aio.operations.BillingPropertyOperations :ivar billing_role_definitions: BillingRoleDefinitionsOperations operations :vartype billing_role_definitions: azure.mgmt.billing.aio.operations.BillingRoleDefinitionsOperations :ivar billing_role_assignments: BillingRoleAssignmentsOperations operations :vartype billing_role_assignments: azure.mgmt.billing.aio.operations.BillingRoleAssignmentsOperations :ivar agreements: AgreementsOperations operations :vartype agreements: azure.mgmt.billing.aio.operations.AgreementsOperations :ivar reservations: ReservationsOperations operations :vartype reservations: azure.mgmt.billing.aio.operations.ReservationsOperations :ivar enrollment_accounts: EnrollmentAccountsOperations operations :vartype enrollment_accounts: azure.mgmt.billing.aio.operations.EnrollmentAccountsOperations :ivar billing_periods: BillingPeriodsOperations operations :vartype billing_periods: azure.mgmt.billing.aio.operations.BillingPeriodsOperations :ivar operations: Operations operations :vartype operations: azure.mgmt.billing.aio.operations.Operations :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials_async.AsyncTokenCredential :param subscription_id: The ID that uniquely identifies an Azure subscription. Required. :type subscription_id: str :param base_url: Service URL. Default value is "https://management.azure.com". :type base_url: str :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. """ def __init__( self, credential: "AsyncTokenCredential", subscription_id: str, base_url: str = "https://management.azure.com", **kwargs: Any ) -> None: self._config = BillingManagementClientConfiguration( credential=credential, subscription_id=subscription_id, **kwargs ) self._client = AsyncARMPipelineClient(base_url=base_url, config=self._config, **kwargs) client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} self._serialize = Serializer(client_models) self._deserialize = Deserializer(client_models) self._serialize.client_side_validation = False self.billing_accounts = BillingAccountsOperations( self._client, self._config, self._serialize, self._deserialize ) self.address = AddressOperations(self._client, self._config, self._serialize, self._deserialize) self.available_balances = AvailableBalancesOperations( self._client, self._config, self._serialize, self._deserialize ) self.instructions = InstructionsOperations(self._client, self._config, self._serialize, self._deserialize) self.billing_profiles = BillingProfilesOperations( self._client, self._config, self._serialize, self._deserialize ) self.customers = CustomersOperations(self._client, self._config, self._serialize, self._deserialize) self.invoice_sections = InvoiceSectionsOperations( self._client, self._config, self._serialize, self._deserialize ) self.billing_permissions = BillingPermissionsOperations( self._client, self._config, self._serialize, self._deserialize ) self.billing_subscriptions = BillingSubscriptionsOperations( self._client, self._config, self._serialize, self._deserialize ) self.products = ProductsOperations(self._client, self._config, self._serialize, self._deserialize) self.invoices = InvoicesOperations(self._client, self._config, self._serialize, self._deserialize) self.transactions = TransactionsOperations(self._client, self._config, self._serialize, self._deserialize) self.policies = PoliciesOperations(self._client, self._config, self._serialize, self._deserialize) self.billing_property = BillingPropertyOperations( self._client, self._config, self._serialize, self._deserialize ) self.billing_role_definitions = BillingRoleDefinitionsOperations( self._client, self._config, self._serialize, self._deserialize ) self.billing_role_assignments = BillingRoleAssignmentsOperations( self._client, self._config, self._serialize, self._deserialize ) self.agreements = AgreementsOperations(self._client, self._config, self._serialize, self._deserialize) self.reservations = ReservationsOperations(self._client, self._config, self._serialize, self._deserialize) self.enrollment_accounts = EnrollmentAccountsOperations( self._client, self._config, self._serialize, self._deserialize ) self.billing_periods = BillingPeriodsOperations(self._client, self._config, self._serialize, self._deserialize) self.operations = Operations(self._client, self._config, self._serialize, self._deserialize) def _send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]: """Runs the network request through the client's chained policies. >>> from azure.core.rest import HttpRequest >>> request = HttpRequest("GET", "https://www.example.org/") <HttpRequest [GET], url: 'https://www.example.org/'> >>> response = await client._send_request(request) <AsyncHttpResponse: 200 OK> For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request :param request: The network request you want to make. Required. :type request: ~azure.core.rest.HttpRequest :keyword bool stream: Whether the response payload will be streamed. Defaults to False. :return: The response of your network call. Does not do error handling on your response. :rtype: ~azure.core.rest.AsyncHttpResponse """ request_copy = deepcopy(request) request_copy.url = self._client.format_url(request_copy.url) return self._client.send_request(request_copy, **kwargs) async def close(self) -> None: await self._client.close() async def __aenter__(self) -> "BillingManagementClient": await self._client.__aenter__() return self async def __aexit__(self, *exc_details) -> None: await self._client.__aexit__(*exc_details)
0.80525
0.136234
from typing import Any, TYPE_CHECKING from azure.core.configuration import Configuration from azure.core.pipeline import policies from azure.mgmt.core.policies import ARMHttpLoggingPolicy, AsyncARMChallengeAuthenticationPolicy from .._version import VERSION if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential class BillingManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes """Configuration for BillingManagementClient. Note that all parameters used to create this instance are saved as instance attributes. :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials_async.AsyncTokenCredential :param subscription_id: The ID that uniquely identifies an Azure subscription. Required. :type subscription_id: str """ def __init__(self, credential: "AsyncTokenCredential", subscription_id: str, **kwargs: Any) -> None: super(BillingManagementClientConfiguration, self).__init__(**kwargs) if credential is None: raise ValueError("Parameter 'credential' must not be None.") if subscription_id is None: raise ValueError("Parameter 'subscription_id' must not be None.") self.credential = credential self.subscription_id = subscription_id self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) kwargs.setdefault("sdk_moniker", "mgmt-billing/{}".format(VERSION)) self._configure(**kwargs) def _configure(self, **kwargs: Any) -> None: self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) self.retry_policy = kwargs.get("retry_policy") or policies.AsyncRetryPolicy(**kwargs) self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) self.redirect_policy = kwargs.get("redirect_policy") or policies.AsyncRedirectPolicy(**kwargs) self.authentication_policy = kwargs.get("authentication_policy") if self.credential and not self.authentication_policy: self.authentication_policy = AsyncARMChallengeAuthenticationPolicy( self.credential, *self.credential_scopes, **kwargs )
azure-mgmt-billing
/azure_mgmt_billing-6.1.0b1-py3-none-any.whl/azure/mgmt/billing/aio/_configuration.py
_configuration.py
from typing import Any, TYPE_CHECKING from azure.core.configuration import Configuration from azure.core.pipeline import policies from azure.mgmt.core.policies import ARMHttpLoggingPolicy, AsyncARMChallengeAuthenticationPolicy from .._version import VERSION if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential class BillingManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes """Configuration for BillingManagementClient. Note that all parameters used to create this instance are saved as instance attributes. :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials_async.AsyncTokenCredential :param subscription_id: The ID that uniquely identifies an Azure subscription. Required. :type subscription_id: str """ def __init__(self, credential: "AsyncTokenCredential", subscription_id: str, **kwargs: Any) -> None: super(BillingManagementClientConfiguration, self).__init__(**kwargs) if credential is None: raise ValueError("Parameter 'credential' must not be None.") if subscription_id is None: raise ValueError("Parameter 'subscription_id' must not be None.") self.credential = credential self.subscription_id = subscription_id self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) kwargs.setdefault("sdk_moniker", "mgmt-billing/{}".format(VERSION)) self._configure(**kwargs) def _configure(self, **kwargs: Any) -> None: self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) self.retry_policy = kwargs.get("retry_policy") or policies.AsyncRetryPolicy(**kwargs) self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) self.redirect_policy = kwargs.get("redirect_policy") or policies.AsyncRedirectPolicy(**kwargs) self.authentication_policy = kwargs.get("authentication_policy") if self.credential and not self.authentication_policy: self.authentication_policy = AsyncARMChallengeAuthenticationPolicy( self.credential, *self.credential_scopes, **kwargs )
0.822546
0.078008
import sys from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, overload from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, map_error, ) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models from ..._vendor import _convert_request from ...operations._instructions_operations import ( build_get_request, build_list_by_billing_profile_request, build_put_request, ) if sys.version_info >= (3, 8): from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports else: from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] class InstructionsOperations: """ .. warning:: **DO NOT** instantiate this class directly. Instead, you should access the following operations through :class:`~azure.mgmt.billing.aio.BillingManagementClient`'s :attr:`instructions` attribute. """ models = _models def __init__(self, *args, **kwargs) -> None: input_args = list(args) self._client = input_args.pop(0) if input_args else kwargs.pop("client") self._config = input_args.pop(0) if input_args else kwargs.pop("config") self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace def list_by_billing_profile( self, billing_account_name: str, billing_profile_name: str, **kwargs: Any ) -> AsyncIterable["_models.Instruction"]: """Lists the instructions by billing profile id. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either Instruction or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.Instruction] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.InstructionListResult] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_by_billing_profile_request( billing_account_name=billing_account_name, billing_profile_name=billing_profile_name, api_version=api_version, template_url=self.list_by_billing_profile.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore else: request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request async def extract_data(pipeline_response): deserialized = self._deserialize("InstructionListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged(get_next, extract_data) list_by_billing_profile.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/instructions"} # type: ignore @distributed_trace_async async def get( self, billing_account_name: str, billing_profile_name: str, instruction_name: str, **kwargs: Any ) -> _models.Instruction: """Get the instruction by name. These are custom billing instructions and are only applicable for certain customers. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :param instruction_name: Instruction Name. Required. :type instruction_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Instruction or the result of cls(response) :rtype: ~azure.mgmt.billing.models.Instruction :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.Instruction] request = build_get_request( billing_account_name=billing_account_name, billing_profile_name=billing_profile_name, instruction_name=instruction_name, api_version=api_version, template_url=self.get.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize("Instruction", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/instructions/{instructionName}"} # type: ignore @overload async def put( self, billing_account_name: str, billing_profile_name: str, instruction_name: str, parameters: _models.Instruction, *, content_type: str = "application/json", **kwargs: Any ) -> _models.Instruction: """Creates or updates an instruction. These are custom billing instructions and are only applicable for certain customers. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :param instruction_name: Instruction Name. Required. :type instruction_name: str :param parameters: The new instruction. Required. :type parameters: ~azure.mgmt.billing.models.Instruction :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Instruction or the result of cls(response) :rtype: ~azure.mgmt.billing.models.Instruction :raises ~azure.core.exceptions.HttpResponseError: """ @overload async def put( self, billing_account_name: str, billing_profile_name: str, instruction_name: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any ) -> _models.Instruction: """Creates or updates an instruction. These are custom billing instructions and are only applicable for certain customers. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :param instruction_name: Instruction Name. Required. :type instruction_name: str :param parameters: The new instruction. Required. :type parameters: IO :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Instruction or the result of cls(response) :rtype: ~azure.mgmt.billing.models.Instruction :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace_async async def put( self, billing_account_name: str, billing_profile_name: str, instruction_name: str, parameters: Union[_models.Instruction, IO], **kwargs: Any ) -> _models.Instruction: """Creates or updates an instruction. These are custom billing instructions and are only applicable for certain customers. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :param instruction_name: Instruction Name. Required. :type instruction_name: str :param parameters: The new instruction. Is either a model type or a IO type. Required. :type parameters: ~azure.mgmt.billing.models.Instruction or IO :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. Default value is None. :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Instruction or the result of cls(response) :rtype: ~azure.mgmt.billing.models.Instruction :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] cls = kwargs.pop("cls", None) # type: ClsType[_models.Instruction] content_type = content_type or "application/json" _json = None _content = None if isinstance(parameters, (IO, bytes)): _content = parameters else: _json = self._serialize.body(parameters, "Instruction") request = build_put_request( billing_account_name=billing_account_name, billing_profile_name=billing_profile_name, instruction_name=instruction_name, api_version=api_version, content_type=content_type, json=_json, content=_content, template_url=self.put.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize("Instruction", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized put.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/instructions/{instructionName}"} # type: ignore
azure-mgmt-billing
/azure_mgmt_billing-6.1.0b1-py3-none-any.whl/azure/mgmt/billing/aio/operations/_instructions_operations.py
_instructions_operations.py
import sys from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, overload from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, map_error, ) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models from ..._vendor import _convert_request from ...operations._instructions_operations import ( build_get_request, build_list_by_billing_profile_request, build_put_request, ) if sys.version_info >= (3, 8): from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports else: from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] class InstructionsOperations: """ .. warning:: **DO NOT** instantiate this class directly. Instead, you should access the following operations through :class:`~azure.mgmt.billing.aio.BillingManagementClient`'s :attr:`instructions` attribute. """ models = _models def __init__(self, *args, **kwargs) -> None: input_args = list(args) self._client = input_args.pop(0) if input_args else kwargs.pop("client") self._config = input_args.pop(0) if input_args else kwargs.pop("config") self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace def list_by_billing_profile( self, billing_account_name: str, billing_profile_name: str, **kwargs: Any ) -> AsyncIterable["_models.Instruction"]: """Lists the instructions by billing profile id. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either Instruction or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.Instruction] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.InstructionListResult] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_by_billing_profile_request( billing_account_name=billing_account_name, billing_profile_name=billing_profile_name, api_version=api_version, template_url=self.list_by_billing_profile.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore else: request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request async def extract_data(pipeline_response): deserialized = self._deserialize("InstructionListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged(get_next, extract_data) list_by_billing_profile.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/instructions"} # type: ignore @distributed_trace_async async def get( self, billing_account_name: str, billing_profile_name: str, instruction_name: str, **kwargs: Any ) -> _models.Instruction: """Get the instruction by name. These are custom billing instructions and are only applicable for certain customers. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :param instruction_name: Instruction Name. Required. :type instruction_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Instruction or the result of cls(response) :rtype: ~azure.mgmt.billing.models.Instruction :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.Instruction] request = build_get_request( billing_account_name=billing_account_name, billing_profile_name=billing_profile_name, instruction_name=instruction_name, api_version=api_version, template_url=self.get.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize("Instruction", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/instructions/{instructionName}"} # type: ignore @overload async def put( self, billing_account_name: str, billing_profile_name: str, instruction_name: str, parameters: _models.Instruction, *, content_type: str = "application/json", **kwargs: Any ) -> _models.Instruction: """Creates or updates an instruction. These are custom billing instructions and are only applicable for certain customers. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :param instruction_name: Instruction Name. Required. :type instruction_name: str :param parameters: The new instruction. Required. :type parameters: ~azure.mgmt.billing.models.Instruction :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Instruction or the result of cls(response) :rtype: ~azure.mgmt.billing.models.Instruction :raises ~azure.core.exceptions.HttpResponseError: """ @overload async def put( self, billing_account_name: str, billing_profile_name: str, instruction_name: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any ) -> _models.Instruction: """Creates or updates an instruction. These are custom billing instructions and are only applicable for certain customers. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :param instruction_name: Instruction Name. Required. :type instruction_name: str :param parameters: The new instruction. Required. :type parameters: IO :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Instruction or the result of cls(response) :rtype: ~azure.mgmt.billing.models.Instruction :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace_async async def put( self, billing_account_name: str, billing_profile_name: str, instruction_name: str, parameters: Union[_models.Instruction, IO], **kwargs: Any ) -> _models.Instruction: """Creates or updates an instruction. These are custom billing instructions and are only applicable for certain customers. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :param instruction_name: Instruction Name. Required. :type instruction_name: str :param parameters: The new instruction. Is either a model type or a IO type. Required. :type parameters: ~azure.mgmt.billing.models.Instruction or IO :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. Default value is None. :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Instruction or the result of cls(response) :rtype: ~azure.mgmt.billing.models.Instruction :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] cls = kwargs.pop("cls", None) # type: ClsType[_models.Instruction] content_type = content_type or "application/json" _json = None _content = None if isinstance(parameters, (IO, bytes)): _content = parameters else: _json = self._serialize.body(parameters, "Instruction") request = build_put_request( billing_account_name=billing_account_name, billing_profile_name=billing_profile_name, instruction_name=instruction_name, api_version=api_version, content_type=content_type, json=_json, content=_content, template_url=self.put.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize("Instruction", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized put.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/instructions/{instructionName}"} # type: ignore
0.700588
0.073397
import sys from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, map_error, ) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models from ..._vendor import _convert_request from ...operations._billing_permissions_operations import ( build_list_by_billing_account_request, build_list_by_billing_profile_request, build_list_by_customer_request, build_list_by_invoice_sections_request, ) if sys.version_info >= (3, 8): from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports else: from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] class BillingPermissionsOperations: """ .. warning:: **DO NOT** instantiate this class directly. Instead, you should access the following operations through :class:`~azure.mgmt.billing.aio.BillingManagementClient`'s :attr:`billing_permissions` attribute. """ models = _models def __init__(self, *args, **kwargs) -> None: input_args = list(args) self._client = input_args.pop(0) if input_args else kwargs.pop("client") self._config = input_args.pop(0) if input_args else kwargs.pop("config") self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace def list_by_customer( self, billing_account_name: str, customer_name: str, **kwargs: Any ) -> AsyncIterable["_models.BillingPermissionsProperties"]: """Lists the billing permissions the caller has for a customer. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param customer_name: The ID that uniquely identifies a customer. Required. :type customer_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either BillingPermissionsProperties or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.BillingPermissionsProperties] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingPermissionsListResult] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_by_customer_request( billing_account_name=billing_account_name, customer_name=customer_name, api_version=api_version, template_url=self.list_by_customer.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore else: request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request async def extract_data(pipeline_response): deserialized = self._deserialize("BillingPermissionsListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged(get_next, extract_data) list_by_customer.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/customers/{customerName}/billingPermissions"} # type: ignore @distributed_trace def list_by_billing_account( self, billing_account_name: str, **kwargs: Any ) -> AsyncIterable["_models.BillingPermissionsProperties"]: """Lists the billing permissions the caller has on a billing account. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either BillingPermissionsProperties or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.BillingPermissionsProperties] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingPermissionsListResult] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_by_billing_account_request( billing_account_name=billing_account_name, api_version=api_version, template_url=self.list_by_billing_account.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore else: request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request async def extract_data(pipeline_response): deserialized = self._deserialize("BillingPermissionsListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged(get_next, extract_data) list_by_billing_account.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingPermissions"} # type: ignore @distributed_trace def list_by_invoice_sections( self, billing_account_name: str, billing_profile_name: str, invoice_section_name: str, **kwargs: Any ) -> AsyncIterable["_models.BillingPermissionsProperties"]: """Lists the billing permissions the caller has on an invoice section. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :param invoice_section_name: The ID that uniquely identifies an invoice section. Required. :type invoice_section_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either BillingPermissionsProperties or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.BillingPermissionsProperties] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingPermissionsListResult] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_by_invoice_sections_request( billing_account_name=billing_account_name, billing_profile_name=billing_profile_name, invoice_section_name=invoice_section_name, api_version=api_version, template_url=self.list_by_invoice_sections.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore else: request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request async def extract_data(pipeline_response): deserialized = self._deserialize("BillingPermissionsListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged(get_next, extract_data) list_by_invoice_sections.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoiceSections/{invoiceSectionName}/billingPermissions"} # type: ignore @distributed_trace def list_by_billing_profile( self, billing_account_name: str, billing_profile_name: str, **kwargs: Any ) -> AsyncIterable["_models.BillingPermissionsProperties"]: """Lists the billing permissions the caller has on a billing profile. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either BillingPermissionsProperties or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.BillingPermissionsProperties] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingPermissionsListResult] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_by_billing_profile_request( billing_account_name=billing_account_name, billing_profile_name=billing_profile_name, api_version=api_version, template_url=self.list_by_billing_profile.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore else: request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request async def extract_data(pipeline_response): deserialized = self._deserialize("BillingPermissionsListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged(get_next, extract_data) list_by_billing_profile.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/billingPermissions"} # type: ignore
azure-mgmt-billing
/azure_mgmt_billing-6.1.0b1-py3-none-any.whl/azure/mgmt/billing/aio/operations/_billing_permissions_operations.py
_billing_permissions_operations.py
import sys from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, map_error, ) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models from ..._vendor import _convert_request from ...operations._billing_permissions_operations import ( build_list_by_billing_account_request, build_list_by_billing_profile_request, build_list_by_customer_request, build_list_by_invoice_sections_request, ) if sys.version_info >= (3, 8): from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports else: from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] class BillingPermissionsOperations: """ .. warning:: **DO NOT** instantiate this class directly. Instead, you should access the following operations through :class:`~azure.mgmt.billing.aio.BillingManagementClient`'s :attr:`billing_permissions` attribute. """ models = _models def __init__(self, *args, **kwargs) -> None: input_args = list(args) self._client = input_args.pop(0) if input_args else kwargs.pop("client") self._config = input_args.pop(0) if input_args else kwargs.pop("config") self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace def list_by_customer( self, billing_account_name: str, customer_name: str, **kwargs: Any ) -> AsyncIterable["_models.BillingPermissionsProperties"]: """Lists the billing permissions the caller has for a customer. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param customer_name: The ID that uniquely identifies a customer. Required. :type customer_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either BillingPermissionsProperties or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.BillingPermissionsProperties] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingPermissionsListResult] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_by_customer_request( billing_account_name=billing_account_name, customer_name=customer_name, api_version=api_version, template_url=self.list_by_customer.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore else: request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request async def extract_data(pipeline_response): deserialized = self._deserialize("BillingPermissionsListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged(get_next, extract_data) list_by_customer.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/customers/{customerName}/billingPermissions"} # type: ignore @distributed_trace def list_by_billing_account( self, billing_account_name: str, **kwargs: Any ) -> AsyncIterable["_models.BillingPermissionsProperties"]: """Lists the billing permissions the caller has on a billing account. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either BillingPermissionsProperties or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.BillingPermissionsProperties] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingPermissionsListResult] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_by_billing_account_request( billing_account_name=billing_account_name, api_version=api_version, template_url=self.list_by_billing_account.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore else: request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request async def extract_data(pipeline_response): deserialized = self._deserialize("BillingPermissionsListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged(get_next, extract_data) list_by_billing_account.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingPermissions"} # type: ignore @distributed_trace def list_by_invoice_sections( self, billing_account_name: str, billing_profile_name: str, invoice_section_name: str, **kwargs: Any ) -> AsyncIterable["_models.BillingPermissionsProperties"]: """Lists the billing permissions the caller has on an invoice section. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :param invoice_section_name: The ID that uniquely identifies an invoice section. Required. :type invoice_section_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either BillingPermissionsProperties or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.BillingPermissionsProperties] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingPermissionsListResult] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_by_invoice_sections_request( billing_account_name=billing_account_name, billing_profile_name=billing_profile_name, invoice_section_name=invoice_section_name, api_version=api_version, template_url=self.list_by_invoice_sections.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore else: request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request async def extract_data(pipeline_response): deserialized = self._deserialize("BillingPermissionsListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged(get_next, extract_data) list_by_invoice_sections.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoiceSections/{invoiceSectionName}/billingPermissions"} # type: ignore @distributed_trace def list_by_billing_profile( self, billing_account_name: str, billing_profile_name: str, **kwargs: Any ) -> AsyncIterable["_models.BillingPermissionsProperties"]: """Lists the billing permissions the caller has on a billing profile. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either BillingPermissionsProperties or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.BillingPermissionsProperties] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingPermissionsListResult] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_by_billing_profile_request( billing_account_name=billing_account_name, billing_profile_name=billing_profile_name, api_version=api_version, template_url=self.list_by_billing_profile.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore else: request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request async def extract_data(pipeline_response): deserialized = self._deserialize("BillingPermissionsListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged(get_next, extract_data) list_by_billing_profile.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/billingPermissions"} # type: ignore
0.673406
0.096663
import sys from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, map_error, ) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models from ..._vendor import _convert_request from ...operations._billing_periods_operations import build_get_request, build_list_request if sys.version_info >= (3, 8): from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports else: from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] class BillingPeriodsOperations: """ .. warning:: **DO NOT** instantiate this class directly. Instead, you should access the following operations through :class:`~azure.mgmt.billing.aio.BillingManagementClient`'s :attr:`billing_periods` attribute. """ models = _models def __init__(self, *args, **kwargs) -> None: input_args = list(args) self._client = input_args.pop(0) if input_args else kwargs.pop("client") self._config = input_args.pop(0) if input_args else kwargs.pop("config") self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace def list( self, filter: Optional[str] = None, skiptoken: Optional[str] = None, top: Optional[int] = None, **kwargs: Any ) -> AsyncIterable["_models.BillingPeriod"]: """Lists the available billing periods for a subscription in reverse chronological order. This is only supported for Azure Web-Direct subscriptions. Other subscription types which were not purchased directly through the Azure web portal are not supported through this preview API. :param filter: May be used to filter billing periods by billingPeriodEndDate. The filter supports 'eq', 'lt', 'gt', 'le', 'ge', and 'and'. It does not currently support 'ne', 'or', or 'not'. Default value is None. :type filter: str :param skiptoken: Skiptoken is only used if a previous operation returned a partial result. If a previous response contains a nextLink element, the value of the nextLink element will include a skiptoken parameter that specifies a starting point to use for subsequent calls. Default value is None. :type skiptoken: str :param top: May be used to limit the number of results to the most recent N billing periods. Default value is None. :type top: int :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either BillingPeriod or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.BillingPeriod] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop( "api_version", _params.pop("api-version", "2018-03-01-preview") ) # type: Literal["2018-03-01-preview"] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingPeriodsListResult] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_request( subscription_id=self._config.subscription_id, filter=filter, skiptoken=skiptoken, top=top, api_version=api_version, template_url=self.list.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore else: request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request async def extract_data(pipeline_response): deserialized = self._deserialize("BillingPeriodsListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged(get_next, extract_data) list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Billing/billingPeriods"} # type: ignore @distributed_trace_async async def get(self, billing_period_name: str, **kwargs: Any) -> _models.BillingPeriod: """Gets a named billing period. This is only supported for Azure Web-Direct subscriptions. Other subscription types which were not purchased directly through the Azure web portal are not supported through this preview API. :param billing_period_name: The name of a BillingPeriod resource. Required. :type billing_period_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: BillingPeriod or the result of cls(response) :rtype: ~azure.mgmt.billing.models.BillingPeriod :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop( "api_version", _params.pop("api-version", "2018-03-01-preview") ) # type: Literal["2018-03-01-preview"] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingPeriod] request = build_get_request( billing_period_name=billing_period_name, subscription_id=self._config.subscription_id, api_version=api_version, template_url=self.get.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize("BillingPeriod", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Billing/billingPeriods/{billingPeriodName}"} # type: ignore
azure-mgmt-billing
/azure_mgmt_billing-6.1.0b1-py3-none-any.whl/azure/mgmt/billing/aio/operations/_billing_periods_operations.py
_billing_periods_operations.py
import sys from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, map_error, ) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models from ..._vendor import _convert_request from ...operations._billing_periods_operations import build_get_request, build_list_request if sys.version_info >= (3, 8): from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports else: from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] class BillingPeriodsOperations: """ .. warning:: **DO NOT** instantiate this class directly. Instead, you should access the following operations through :class:`~azure.mgmt.billing.aio.BillingManagementClient`'s :attr:`billing_periods` attribute. """ models = _models def __init__(self, *args, **kwargs) -> None: input_args = list(args) self._client = input_args.pop(0) if input_args else kwargs.pop("client") self._config = input_args.pop(0) if input_args else kwargs.pop("config") self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace def list( self, filter: Optional[str] = None, skiptoken: Optional[str] = None, top: Optional[int] = None, **kwargs: Any ) -> AsyncIterable["_models.BillingPeriod"]: """Lists the available billing periods for a subscription in reverse chronological order. This is only supported for Azure Web-Direct subscriptions. Other subscription types which were not purchased directly through the Azure web portal are not supported through this preview API. :param filter: May be used to filter billing periods by billingPeriodEndDate. The filter supports 'eq', 'lt', 'gt', 'le', 'ge', and 'and'. It does not currently support 'ne', 'or', or 'not'. Default value is None. :type filter: str :param skiptoken: Skiptoken is only used if a previous operation returned a partial result. If a previous response contains a nextLink element, the value of the nextLink element will include a skiptoken parameter that specifies a starting point to use for subsequent calls. Default value is None. :type skiptoken: str :param top: May be used to limit the number of results to the most recent N billing periods. Default value is None. :type top: int :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either BillingPeriod or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.BillingPeriod] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop( "api_version", _params.pop("api-version", "2018-03-01-preview") ) # type: Literal["2018-03-01-preview"] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingPeriodsListResult] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_request( subscription_id=self._config.subscription_id, filter=filter, skiptoken=skiptoken, top=top, api_version=api_version, template_url=self.list.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore else: request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request async def extract_data(pipeline_response): deserialized = self._deserialize("BillingPeriodsListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged(get_next, extract_data) list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Billing/billingPeriods"} # type: ignore @distributed_trace_async async def get(self, billing_period_name: str, **kwargs: Any) -> _models.BillingPeriod: """Gets a named billing period. This is only supported for Azure Web-Direct subscriptions. Other subscription types which were not purchased directly through the Azure web portal are not supported through this preview API. :param billing_period_name: The name of a BillingPeriod resource. Required. :type billing_period_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: BillingPeriod or the result of cls(response) :rtype: ~azure.mgmt.billing.models.BillingPeriod :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop( "api_version", _params.pop("api-version", "2018-03-01-preview") ) # type: Literal["2018-03-01-preview"] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingPeriod] request = build_get_request( billing_period_name=billing_period_name, subscription_id=self._config.subscription_id, api_version=api_version, template_url=self.get.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize("BillingPeriod", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Billing/billingPeriods/{billingPeriodName}"} # type: ignore
0.724383
0.12276
import sys from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, overload from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, map_error, ) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.rest import HttpRequest from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models from ..._vendor import _convert_request from ...operations._policies_operations import ( build_get_by_billing_profile_request, build_get_by_customer_request, build_update_customer_request, build_update_request, ) if sys.version_info >= (3, 8): from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports else: from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] class PoliciesOperations: """ .. warning:: **DO NOT** instantiate this class directly. Instead, you should access the following operations through :class:`~azure.mgmt.billing.aio.BillingManagementClient`'s :attr:`policies` attribute. """ models = _models def __init__(self, *args, **kwargs) -> None: input_args = list(args) self._client = input_args.pop(0) if input_args else kwargs.pop("client") self._config = input_args.pop(0) if input_args else kwargs.pop("config") self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace_async async def get_by_billing_profile( self, billing_account_name: str, billing_profile_name: str, **kwargs: Any ) -> _models.Policy: """Lists the policies for a billing profile. This operation is supported only for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Policy or the result of cls(response) :rtype: ~azure.mgmt.billing.models.Policy :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.Policy] request = build_get_by_billing_profile_request( billing_account_name=billing_account_name, billing_profile_name=billing_profile_name, api_version=api_version, template_url=self.get_by_billing_profile.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize("Policy", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get_by_billing_profile.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/policies/default"} # type: ignore @overload async def update( self, billing_account_name: str, billing_profile_name: str, parameters: _models.Policy, *, content_type: str = "application/json", **kwargs: Any ) -> _models.Policy: """Updates the policies for a billing profile. This operation is supported only for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :param parameters: Request parameters that are provided to the update policies operation. Required. :type parameters: ~azure.mgmt.billing.models.Policy :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Policy or the result of cls(response) :rtype: ~azure.mgmt.billing.models.Policy :raises ~azure.core.exceptions.HttpResponseError: """ @overload async def update( self, billing_account_name: str, billing_profile_name: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any ) -> _models.Policy: """Updates the policies for a billing profile. This operation is supported only for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :param parameters: Request parameters that are provided to the update policies operation. Required. :type parameters: IO :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Policy or the result of cls(response) :rtype: ~azure.mgmt.billing.models.Policy :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace_async async def update( self, billing_account_name: str, billing_profile_name: str, parameters: Union[_models.Policy, IO], **kwargs: Any ) -> _models.Policy: """Updates the policies for a billing profile. This operation is supported only for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :param parameters: Request parameters that are provided to the update policies operation. Is either a model type or a IO type. Required. :type parameters: ~azure.mgmt.billing.models.Policy or IO :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. Default value is None. :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Policy or the result of cls(response) :rtype: ~azure.mgmt.billing.models.Policy :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] cls = kwargs.pop("cls", None) # type: ClsType[_models.Policy] content_type = content_type or "application/json" _json = None _content = None if isinstance(parameters, (IO, bytes)): _content = parameters else: _json = self._serialize.body(parameters, "Policy") request = build_update_request( billing_account_name=billing_account_name, billing_profile_name=billing_profile_name, api_version=api_version, content_type=content_type, json=_json, content=_content, template_url=self.update.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize("Policy", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized update.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/policies/default"} # type: ignore @distributed_trace_async async def get_by_customer( self, billing_account_name: str, customer_name: str, **kwargs: Any ) -> _models.CustomerPolicy: """Lists the policies for a customer. This operation is supported only for billing accounts with agreement type Microsoft Partner Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param customer_name: The ID that uniquely identifies a customer. Required. :type customer_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: CustomerPolicy or the result of cls(response) :rtype: ~azure.mgmt.billing.models.CustomerPolicy :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.CustomerPolicy] request = build_get_by_customer_request( billing_account_name=billing_account_name, customer_name=customer_name, api_version=api_version, template_url=self.get_by_customer.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize("CustomerPolicy", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get_by_customer.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/customers/{customerName}/policies/default"} # type: ignore @overload async def update_customer( self, billing_account_name: str, customer_name: str, parameters: _models.CustomerPolicy, *, content_type: str = "application/json", **kwargs: Any ) -> _models.CustomerPolicy: """Updates the policies for a customer. This operation is supported only for billing accounts with agreement type Microsoft Partner Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param customer_name: The ID that uniquely identifies a customer. Required. :type customer_name: str :param parameters: Request parameters that are provided to the update policies operation. Required. :type parameters: ~azure.mgmt.billing.models.CustomerPolicy :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: CustomerPolicy or the result of cls(response) :rtype: ~azure.mgmt.billing.models.CustomerPolicy :raises ~azure.core.exceptions.HttpResponseError: """ @overload async def update_customer( self, billing_account_name: str, customer_name: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any ) -> _models.CustomerPolicy: """Updates the policies for a customer. This operation is supported only for billing accounts with agreement type Microsoft Partner Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param customer_name: The ID that uniquely identifies a customer. Required. :type customer_name: str :param parameters: Request parameters that are provided to the update policies operation. Required. :type parameters: IO :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: CustomerPolicy or the result of cls(response) :rtype: ~azure.mgmt.billing.models.CustomerPolicy :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace_async async def update_customer( self, billing_account_name: str, customer_name: str, parameters: Union[_models.CustomerPolicy, IO], **kwargs: Any ) -> _models.CustomerPolicy: """Updates the policies for a customer. This operation is supported only for billing accounts with agreement type Microsoft Partner Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param customer_name: The ID that uniquely identifies a customer. Required. :type customer_name: str :param parameters: Request parameters that are provided to the update policies operation. Is either a model type or a IO type. Required. :type parameters: ~azure.mgmt.billing.models.CustomerPolicy or IO :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. Default value is None. :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: CustomerPolicy or the result of cls(response) :rtype: ~azure.mgmt.billing.models.CustomerPolicy :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] cls = kwargs.pop("cls", None) # type: ClsType[_models.CustomerPolicy] content_type = content_type or "application/json" _json = None _content = None if isinstance(parameters, (IO, bytes)): _content = parameters else: _json = self._serialize.body(parameters, "CustomerPolicy") request = build_update_customer_request( billing_account_name=billing_account_name, customer_name=customer_name, api_version=api_version, content_type=content_type, json=_json, content=_content, template_url=self.update_customer.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize("CustomerPolicy", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized update_customer.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/customers/{customerName}/policies/default"} # type: ignore
azure-mgmt-billing
/azure_mgmt_billing-6.1.0b1-py3-none-any.whl/azure/mgmt/billing/aio/operations/_policies_operations.py
_policies_operations.py
import sys from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, overload from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, map_error, ) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.rest import HttpRequest from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models from ..._vendor import _convert_request from ...operations._policies_operations import ( build_get_by_billing_profile_request, build_get_by_customer_request, build_update_customer_request, build_update_request, ) if sys.version_info >= (3, 8): from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports else: from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] class PoliciesOperations: """ .. warning:: **DO NOT** instantiate this class directly. Instead, you should access the following operations through :class:`~azure.mgmt.billing.aio.BillingManagementClient`'s :attr:`policies` attribute. """ models = _models def __init__(self, *args, **kwargs) -> None: input_args = list(args) self._client = input_args.pop(0) if input_args else kwargs.pop("client") self._config = input_args.pop(0) if input_args else kwargs.pop("config") self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace_async async def get_by_billing_profile( self, billing_account_name: str, billing_profile_name: str, **kwargs: Any ) -> _models.Policy: """Lists the policies for a billing profile. This operation is supported only for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Policy or the result of cls(response) :rtype: ~azure.mgmt.billing.models.Policy :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.Policy] request = build_get_by_billing_profile_request( billing_account_name=billing_account_name, billing_profile_name=billing_profile_name, api_version=api_version, template_url=self.get_by_billing_profile.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize("Policy", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get_by_billing_profile.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/policies/default"} # type: ignore @overload async def update( self, billing_account_name: str, billing_profile_name: str, parameters: _models.Policy, *, content_type: str = "application/json", **kwargs: Any ) -> _models.Policy: """Updates the policies for a billing profile. This operation is supported only for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :param parameters: Request parameters that are provided to the update policies operation. Required. :type parameters: ~azure.mgmt.billing.models.Policy :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Policy or the result of cls(response) :rtype: ~azure.mgmt.billing.models.Policy :raises ~azure.core.exceptions.HttpResponseError: """ @overload async def update( self, billing_account_name: str, billing_profile_name: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any ) -> _models.Policy: """Updates the policies for a billing profile. This operation is supported only for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :param parameters: Request parameters that are provided to the update policies operation. Required. :type parameters: IO :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Policy or the result of cls(response) :rtype: ~azure.mgmt.billing.models.Policy :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace_async async def update( self, billing_account_name: str, billing_profile_name: str, parameters: Union[_models.Policy, IO], **kwargs: Any ) -> _models.Policy: """Updates the policies for a billing profile. This operation is supported only for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :param parameters: Request parameters that are provided to the update policies operation. Is either a model type or a IO type. Required. :type parameters: ~azure.mgmt.billing.models.Policy or IO :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. Default value is None. :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Policy or the result of cls(response) :rtype: ~azure.mgmt.billing.models.Policy :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] cls = kwargs.pop("cls", None) # type: ClsType[_models.Policy] content_type = content_type or "application/json" _json = None _content = None if isinstance(parameters, (IO, bytes)): _content = parameters else: _json = self._serialize.body(parameters, "Policy") request = build_update_request( billing_account_name=billing_account_name, billing_profile_name=billing_profile_name, api_version=api_version, content_type=content_type, json=_json, content=_content, template_url=self.update.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize("Policy", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized update.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/policies/default"} # type: ignore @distributed_trace_async async def get_by_customer( self, billing_account_name: str, customer_name: str, **kwargs: Any ) -> _models.CustomerPolicy: """Lists the policies for a customer. This operation is supported only for billing accounts with agreement type Microsoft Partner Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param customer_name: The ID that uniquely identifies a customer. Required. :type customer_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: CustomerPolicy or the result of cls(response) :rtype: ~azure.mgmt.billing.models.CustomerPolicy :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.CustomerPolicy] request = build_get_by_customer_request( billing_account_name=billing_account_name, customer_name=customer_name, api_version=api_version, template_url=self.get_by_customer.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize("CustomerPolicy", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get_by_customer.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/customers/{customerName}/policies/default"} # type: ignore @overload async def update_customer( self, billing_account_name: str, customer_name: str, parameters: _models.CustomerPolicy, *, content_type: str = "application/json", **kwargs: Any ) -> _models.CustomerPolicy: """Updates the policies for a customer. This operation is supported only for billing accounts with agreement type Microsoft Partner Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param customer_name: The ID that uniquely identifies a customer. Required. :type customer_name: str :param parameters: Request parameters that are provided to the update policies operation. Required. :type parameters: ~azure.mgmt.billing.models.CustomerPolicy :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: CustomerPolicy or the result of cls(response) :rtype: ~azure.mgmt.billing.models.CustomerPolicy :raises ~azure.core.exceptions.HttpResponseError: """ @overload async def update_customer( self, billing_account_name: str, customer_name: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any ) -> _models.CustomerPolicy: """Updates the policies for a customer. This operation is supported only for billing accounts with agreement type Microsoft Partner Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param customer_name: The ID that uniquely identifies a customer. Required. :type customer_name: str :param parameters: Request parameters that are provided to the update policies operation. Required. :type parameters: IO :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: CustomerPolicy or the result of cls(response) :rtype: ~azure.mgmt.billing.models.CustomerPolicy :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace_async async def update_customer( self, billing_account_name: str, customer_name: str, parameters: Union[_models.CustomerPolicy, IO], **kwargs: Any ) -> _models.CustomerPolicy: """Updates the policies for a customer. This operation is supported only for billing accounts with agreement type Microsoft Partner Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param customer_name: The ID that uniquely identifies a customer. Required. :type customer_name: str :param parameters: Request parameters that are provided to the update policies operation. Is either a model type or a IO type. Required. :type parameters: ~azure.mgmt.billing.models.CustomerPolicy or IO :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. Default value is None. :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: CustomerPolicy or the result of cls(response) :rtype: ~azure.mgmt.billing.models.CustomerPolicy :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] cls = kwargs.pop("cls", None) # type: ClsType[_models.CustomerPolicy] content_type = content_type or "application/json" _json = None _content = None if isinstance(parameters, (IO, bytes)): _content = parameters else: _json = self._serialize.body(parameters, "CustomerPolicy") request = build_update_customer_request( billing_account_name=billing_account_name, customer_name=customer_name, api_version=api_version, content_type=content_type, json=_json, content=_content, template_url=self.update_customer.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize("CustomerPolicy", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized update_customer.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/customers/{customerName}/policies/default"} # type: ignore
0.709824
0.074467
import sys from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, map_error, ) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models from ..._vendor import _convert_request from ...operations._agreements_operations import build_get_request, build_list_by_billing_account_request if sys.version_info >= (3, 8): from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports else: from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] class AgreementsOperations: """ .. warning:: **DO NOT** instantiate this class directly. Instead, you should access the following operations through :class:`~azure.mgmt.billing.aio.BillingManagementClient`'s :attr:`agreements` attribute. """ models = _models def __init__(self, *args, **kwargs) -> None: input_args = list(args) self._client = input_args.pop(0) if input_args else kwargs.pop("client") self._config = input_args.pop(0) if input_args else kwargs.pop("config") self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace def list_by_billing_account( self, billing_account_name: str, expand: Optional[str] = None, **kwargs: Any ) -> AsyncIterable["_models.Agreement"]: """Lists the agreements for a billing account. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param expand: May be used to expand the participants. Default value is None. :type expand: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either Agreement or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.Agreement] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.AgreementListResult] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_by_billing_account_request( billing_account_name=billing_account_name, expand=expand, api_version=api_version, template_url=self.list_by_billing_account.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore else: request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request async def extract_data(pipeline_response): deserialized = self._deserialize("AgreementListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged(get_next, extract_data) list_by_billing_account.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/agreements"} # type: ignore @distributed_trace_async async def get( self, billing_account_name: str, agreement_name: str, expand: Optional[str] = None, **kwargs: Any ) -> _models.Agreement: """Gets an agreement by ID. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param agreement_name: The ID that uniquely identifies an agreement. Required. :type agreement_name: str :param expand: May be used to expand the participants. Default value is None. :type expand: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Agreement or the result of cls(response) :rtype: ~azure.mgmt.billing.models.Agreement :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.Agreement] request = build_get_request( billing_account_name=billing_account_name, agreement_name=agreement_name, expand=expand, api_version=api_version, template_url=self.get.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize("Agreement", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/agreements/{agreementName}"} # type: ignore
azure-mgmt-billing
/azure_mgmt_billing-6.1.0b1-py3-none-any.whl/azure/mgmt/billing/aio/operations/_agreements_operations.py
_agreements_operations.py
import sys from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, map_error, ) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models from ..._vendor import _convert_request from ...operations._agreements_operations import build_get_request, build_list_by_billing_account_request if sys.version_info >= (3, 8): from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports else: from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] class AgreementsOperations: """ .. warning:: **DO NOT** instantiate this class directly. Instead, you should access the following operations through :class:`~azure.mgmt.billing.aio.BillingManagementClient`'s :attr:`agreements` attribute. """ models = _models def __init__(self, *args, **kwargs) -> None: input_args = list(args) self._client = input_args.pop(0) if input_args else kwargs.pop("client") self._config = input_args.pop(0) if input_args else kwargs.pop("config") self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace def list_by_billing_account( self, billing_account_name: str, expand: Optional[str] = None, **kwargs: Any ) -> AsyncIterable["_models.Agreement"]: """Lists the agreements for a billing account. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param expand: May be used to expand the participants. Default value is None. :type expand: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either Agreement or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.Agreement] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.AgreementListResult] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_by_billing_account_request( billing_account_name=billing_account_name, expand=expand, api_version=api_version, template_url=self.list_by_billing_account.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore else: request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request async def extract_data(pipeline_response): deserialized = self._deserialize("AgreementListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged(get_next, extract_data) list_by_billing_account.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/agreements"} # type: ignore @distributed_trace_async async def get( self, billing_account_name: str, agreement_name: str, expand: Optional[str] = None, **kwargs: Any ) -> _models.Agreement: """Gets an agreement by ID. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param agreement_name: The ID that uniquely identifies an agreement. Required. :type agreement_name: str :param expand: May be used to expand the participants. Default value is None. :type expand: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Agreement or the result of cls(response) :rtype: ~azure.mgmt.billing.models.Agreement :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.Agreement] request = build_get_request( billing_account_name=billing_account_name, agreement_name=agreement_name, expand=expand, api_version=api_version, template_url=self.get.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize("Agreement", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/agreements/{agreementName}"} # type: ignore
0.686895
0.093844
import sys from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, map_error, ) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling from ... import models as _models from ..._vendor import _convert_request from ...operations._invoice_sections_operations import ( build_create_or_update_request, build_get_request, build_list_by_billing_profile_request, ) if sys.version_info >= (3, 8): from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports else: from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] class InvoiceSectionsOperations: """ .. warning:: **DO NOT** instantiate this class directly. Instead, you should access the following operations through :class:`~azure.mgmt.billing.aio.BillingManagementClient`'s :attr:`invoice_sections` attribute. """ models = _models def __init__(self, *args, **kwargs) -> None: input_args = list(args) self._client = input_args.pop(0) if input_args else kwargs.pop("client") self._config = input_args.pop(0) if input_args else kwargs.pop("config") self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace def list_by_billing_profile( self, billing_account_name: str, billing_profile_name: str, **kwargs: Any ) -> AsyncIterable["_models.InvoiceSection"]: """Lists the invoice sections that a user has access to. The operation is supported only for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either InvoiceSection or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.InvoiceSection] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.InvoiceSectionListResult] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_by_billing_profile_request( billing_account_name=billing_account_name, billing_profile_name=billing_profile_name, api_version=api_version, template_url=self.list_by_billing_profile.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore else: request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request async def extract_data(pipeline_response): deserialized = self._deserialize("InvoiceSectionListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged(get_next, extract_data) list_by_billing_profile.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoiceSections"} # type: ignore @distributed_trace_async async def get( self, billing_account_name: str, billing_profile_name: str, invoice_section_name: str, **kwargs: Any ) -> _models.InvoiceSection: """Gets an invoice section by its ID. The operation is supported only for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :param invoice_section_name: The ID that uniquely identifies an invoice section. Required. :type invoice_section_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: InvoiceSection or the result of cls(response) :rtype: ~azure.mgmt.billing.models.InvoiceSection :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.InvoiceSection] request = build_get_request( billing_account_name=billing_account_name, billing_profile_name=billing_profile_name, invoice_section_name=invoice_section_name, api_version=api_version, template_url=self.get.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize("InvoiceSection", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoiceSections/{invoiceSectionName}"} # type: ignore async def _create_or_update_initial( self, billing_account_name: str, billing_profile_name: str, invoice_section_name: str, parameters: Union[_models.InvoiceSection, IO], **kwargs: Any ) -> Optional[_models.InvoiceSection]: error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.InvoiceSection]] content_type = content_type or "application/json" _json = None _content = None if isinstance(parameters, (IO, bytes)): _content = parameters else: _json = self._serialize.body(parameters, "InvoiceSection") request = build_create_or_update_request( billing_account_name=billing_account_name, billing_profile_name=billing_profile_name, invoice_section_name=invoice_section_name, api_version=api_version, content_type=content_type, json=_json, content=_content, template_url=self._create_or_update_initial.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = None response_headers = {} if response.status_code == 200: deserialized = self._deserialize("InvoiceSection", pipeline_response) if response.status_code == 202: response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) if cls: return cls(pipeline_response, deserialized, response_headers) return deserialized _create_or_update_initial.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoiceSections/{invoiceSectionName}"} # type: ignore @overload async def begin_create_or_update( self, billing_account_name: str, billing_profile_name: str, invoice_section_name: str, parameters: _models.InvoiceSection, *, content_type: str = "application/json", **kwargs: Any ) -> AsyncLROPoller[_models.InvoiceSection]: """Creates or updates an invoice section. The operation is supported only for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :param invoice_section_name: The ID that uniquely identifies an invoice section. Required. :type invoice_section_name: str :param parameters: The new or updated invoice section. Required. :type parameters: ~azure.mgmt.billing.models.InvoiceSection :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of AsyncLROPoller that returns either InvoiceSection or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.InvoiceSection] :raises ~azure.core.exceptions.HttpResponseError: """ @overload async def begin_create_or_update( self, billing_account_name: str, billing_profile_name: str, invoice_section_name: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any ) -> AsyncLROPoller[_models.InvoiceSection]: """Creates or updates an invoice section. The operation is supported only for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :param invoice_section_name: The ID that uniquely identifies an invoice section. Required. :type invoice_section_name: str :param parameters: The new or updated invoice section. Required. :type parameters: IO :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of AsyncLROPoller that returns either InvoiceSection or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.InvoiceSection] :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace_async async def begin_create_or_update( self, billing_account_name: str, billing_profile_name: str, invoice_section_name: str, parameters: Union[_models.InvoiceSection, IO], **kwargs: Any ) -> AsyncLROPoller[_models.InvoiceSection]: """Creates or updates an invoice section. The operation is supported only for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :param invoice_section_name: The ID that uniquely identifies an invoice section. Required. :type invoice_section_name: str :param parameters: The new or updated invoice section. Is either a model type or a IO type. Required. :type parameters: ~azure.mgmt.billing.models.InvoiceSection or IO :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. Default value is None. :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of AsyncLROPoller that returns either InvoiceSection or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.InvoiceSection] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] cls = kwargs.pop("cls", None) # type: ClsType[_models.InvoiceSection] polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod] lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: raw_result = await self._create_or_update_initial( # type: ignore billing_account_name=billing_account_name, billing_profile_name=billing_profile_name, invoice_section_name=invoice_section_name, parameters=parameters, api_version=api_version, content_type=content_type, cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): deserialized = self._deserialize("InvoiceSection", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized if polling is True: polling_method = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) # type: AsyncPollingMethod elif polling is False: polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) else: polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_create_or_update.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoiceSections/{invoiceSectionName}"} # type: ignore
azure-mgmt-billing
/azure_mgmt_billing-6.1.0b1-py3-none-any.whl/azure/mgmt/billing/aio/operations/_invoice_sections_operations.py
_invoice_sections_operations.py
import sys from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, map_error, ) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling from ... import models as _models from ..._vendor import _convert_request from ...operations._invoice_sections_operations import ( build_create_or_update_request, build_get_request, build_list_by_billing_profile_request, ) if sys.version_info >= (3, 8): from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports else: from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] class InvoiceSectionsOperations: """ .. warning:: **DO NOT** instantiate this class directly. Instead, you should access the following operations through :class:`~azure.mgmt.billing.aio.BillingManagementClient`'s :attr:`invoice_sections` attribute. """ models = _models def __init__(self, *args, **kwargs) -> None: input_args = list(args) self._client = input_args.pop(0) if input_args else kwargs.pop("client") self._config = input_args.pop(0) if input_args else kwargs.pop("config") self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace def list_by_billing_profile( self, billing_account_name: str, billing_profile_name: str, **kwargs: Any ) -> AsyncIterable["_models.InvoiceSection"]: """Lists the invoice sections that a user has access to. The operation is supported only for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either InvoiceSection or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.InvoiceSection] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.InvoiceSectionListResult] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_by_billing_profile_request( billing_account_name=billing_account_name, billing_profile_name=billing_profile_name, api_version=api_version, template_url=self.list_by_billing_profile.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore else: request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request async def extract_data(pipeline_response): deserialized = self._deserialize("InvoiceSectionListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged(get_next, extract_data) list_by_billing_profile.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoiceSections"} # type: ignore @distributed_trace_async async def get( self, billing_account_name: str, billing_profile_name: str, invoice_section_name: str, **kwargs: Any ) -> _models.InvoiceSection: """Gets an invoice section by its ID. The operation is supported only for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :param invoice_section_name: The ID that uniquely identifies an invoice section. Required. :type invoice_section_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: InvoiceSection or the result of cls(response) :rtype: ~azure.mgmt.billing.models.InvoiceSection :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.InvoiceSection] request = build_get_request( billing_account_name=billing_account_name, billing_profile_name=billing_profile_name, invoice_section_name=invoice_section_name, api_version=api_version, template_url=self.get.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize("InvoiceSection", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoiceSections/{invoiceSectionName}"} # type: ignore async def _create_or_update_initial( self, billing_account_name: str, billing_profile_name: str, invoice_section_name: str, parameters: Union[_models.InvoiceSection, IO], **kwargs: Any ) -> Optional[_models.InvoiceSection]: error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.InvoiceSection]] content_type = content_type or "application/json" _json = None _content = None if isinstance(parameters, (IO, bytes)): _content = parameters else: _json = self._serialize.body(parameters, "InvoiceSection") request = build_create_or_update_request( billing_account_name=billing_account_name, billing_profile_name=billing_profile_name, invoice_section_name=invoice_section_name, api_version=api_version, content_type=content_type, json=_json, content=_content, template_url=self._create_or_update_initial.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = None response_headers = {} if response.status_code == 200: deserialized = self._deserialize("InvoiceSection", pipeline_response) if response.status_code == 202: response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) if cls: return cls(pipeline_response, deserialized, response_headers) return deserialized _create_or_update_initial.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoiceSections/{invoiceSectionName}"} # type: ignore @overload async def begin_create_or_update( self, billing_account_name: str, billing_profile_name: str, invoice_section_name: str, parameters: _models.InvoiceSection, *, content_type: str = "application/json", **kwargs: Any ) -> AsyncLROPoller[_models.InvoiceSection]: """Creates or updates an invoice section. The operation is supported only for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :param invoice_section_name: The ID that uniquely identifies an invoice section. Required. :type invoice_section_name: str :param parameters: The new or updated invoice section. Required. :type parameters: ~azure.mgmt.billing.models.InvoiceSection :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of AsyncLROPoller that returns either InvoiceSection or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.InvoiceSection] :raises ~azure.core.exceptions.HttpResponseError: """ @overload async def begin_create_or_update( self, billing_account_name: str, billing_profile_name: str, invoice_section_name: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any ) -> AsyncLROPoller[_models.InvoiceSection]: """Creates or updates an invoice section. The operation is supported only for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :param invoice_section_name: The ID that uniquely identifies an invoice section. Required. :type invoice_section_name: str :param parameters: The new or updated invoice section. Required. :type parameters: IO :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of AsyncLROPoller that returns either InvoiceSection or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.InvoiceSection] :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace_async async def begin_create_or_update( self, billing_account_name: str, billing_profile_name: str, invoice_section_name: str, parameters: Union[_models.InvoiceSection, IO], **kwargs: Any ) -> AsyncLROPoller[_models.InvoiceSection]: """Creates or updates an invoice section. The operation is supported only for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :param invoice_section_name: The ID that uniquely identifies an invoice section. Required. :type invoice_section_name: str :param parameters: The new or updated invoice section. Is either a model type or a IO type. Required. :type parameters: ~azure.mgmt.billing.models.InvoiceSection or IO :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. Default value is None. :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of AsyncLROPoller that returns either InvoiceSection or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.InvoiceSection] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] cls = kwargs.pop("cls", None) # type: ClsType[_models.InvoiceSection] polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod] lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: raw_result = await self._create_or_update_initial( # type: ignore billing_account_name=billing_account_name, billing_profile_name=billing_profile_name, invoice_section_name=invoice_section_name, parameters=parameters, api_version=api_version, content_type=content_type, cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): deserialized = self._deserialize("InvoiceSection", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized if polling is True: polling_method = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) # type: AsyncPollingMethod elif polling is False: polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) else: polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_create_or_update.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoiceSections/{invoiceSectionName}"} # type: ignore
0.714429
0.092606
import sys from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, map_error, ) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling from ... import models as _models from ..._vendor import _convert_request from ...operations._billing_accounts_operations import ( build_get_request, build_list_invoice_sections_by_create_subscription_permission_request, build_list_request, build_update_request, ) if sys.version_info >= (3, 8): from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports else: from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] class BillingAccountsOperations: """ .. warning:: **DO NOT** instantiate this class directly. Instead, you should access the following operations through :class:`~azure.mgmt.billing.aio.BillingManagementClient`'s :attr:`billing_accounts` attribute. """ models = _models def __init__(self, *args, **kwargs) -> None: input_args = list(args) self._client = input_args.pop(0) if input_args else kwargs.pop("client") self._config = input_args.pop(0) if input_args else kwargs.pop("config") self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace def list(self, expand: Optional[str] = None, **kwargs: Any) -> AsyncIterable["_models.BillingAccount"]: """Lists the billing accounts that a user has access to. :param expand: May be used to expand the soldTo, invoice sections and billing profiles. Default value is None. :type expand: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either BillingAccount or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.BillingAccount] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingAccountListResult] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_request( expand=expand, api_version=api_version, template_url=self.list.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore else: request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request async def extract_data(pipeline_response): deserialized = self._deserialize("BillingAccountListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged(get_next, extract_data) list.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts"} # type: ignore @distributed_trace_async async def get( self, billing_account_name: str, expand: Optional[str] = None, **kwargs: Any ) -> _models.BillingAccount: """Gets a billing account by its ID. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param expand: May be used to expand the soldTo, invoice sections and billing profiles. Default value is None. :type expand: str :keyword callable cls: A custom type or function that will be passed the direct response :return: BillingAccount or the result of cls(response) :rtype: ~azure.mgmt.billing.models.BillingAccount :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingAccount] request = build_get_request( billing_account_name=billing_account_name, expand=expand, api_version=api_version, template_url=self.get.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize("BillingAccount", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}"} # type: ignore async def _update_initial( self, billing_account_name: str, parameters: Union[_models.BillingAccountUpdateRequest, IO], **kwargs: Any ) -> Optional[_models.BillingAccount]: error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.BillingAccount]] content_type = content_type or "application/json" _json = None _content = None if isinstance(parameters, (IO, bytes)): _content = parameters else: _json = self._serialize.body(parameters, "BillingAccountUpdateRequest") request = build_update_request( billing_account_name=billing_account_name, api_version=api_version, content_type=content_type, json=_json, content=_content, template_url=self._update_initial.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = None if response.status_code == 200: deserialized = self._deserialize("BillingAccount", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized _update_initial.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}"} # type: ignore @overload async def begin_update( self, billing_account_name: str, parameters: _models.BillingAccountUpdateRequest, *, content_type: str = "application/json", **kwargs: Any ) -> AsyncLROPoller[_models.BillingAccount]: """Updates the properties of a billing account. Currently, displayName and address can be updated. The operation is supported only for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param parameters: Request parameters that are provided to the update billing account operation. Required. :type parameters: ~azure.mgmt.billing.models.BillingAccountUpdateRequest :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of AsyncLROPoller that returns either BillingAccount or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.BillingAccount] :raises ~azure.core.exceptions.HttpResponseError: """ @overload async def begin_update( self, billing_account_name: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any ) -> AsyncLROPoller[_models.BillingAccount]: """Updates the properties of a billing account. Currently, displayName and address can be updated. The operation is supported only for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param parameters: Request parameters that are provided to the update billing account operation. Required. :type parameters: IO :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of AsyncLROPoller that returns either BillingAccount or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.BillingAccount] :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace_async async def begin_update( self, billing_account_name: str, parameters: Union[_models.BillingAccountUpdateRequest, IO], **kwargs: Any ) -> AsyncLROPoller[_models.BillingAccount]: """Updates the properties of a billing account. Currently, displayName and address can be updated. The operation is supported only for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param parameters: Request parameters that are provided to the update billing account operation. Is either a model type or a IO type. Required. :type parameters: ~azure.mgmt.billing.models.BillingAccountUpdateRequest or IO :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. Default value is None. :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of AsyncLROPoller that returns either BillingAccount or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.BillingAccount] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingAccount] polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod] lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: raw_result = await self._update_initial( # type: ignore billing_account_name=billing_account_name, parameters=parameters, api_version=api_version, content_type=content_type, cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): deserialized = self._deserialize("BillingAccount", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized if polling is True: polling_method = cast( AsyncPollingMethod, AsyncARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs), ) # type: AsyncPollingMethod elif polling is False: polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) else: polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_update.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}"} # type: ignore @distributed_trace def list_invoice_sections_by_create_subscription_permission( self, billing_account_name: str, **kwargs: Any ) -> AsyncIterable["_models.InvoiceSectionWithCreateSubPermission"]: """Lists the invoice sections for which the user has permission to create Azure subscriptions. The operation is supported only for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either InvoiceSectionWithCreateSubPermission or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.InvoiceSectionWithCreateSubPermission] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.InvoiceSectionListWithCreateSubPermissionResult] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_invoice_sections_by_create_subscription_permission_request( billing_account_name=billing_account_name, api_version=api_version, template_url=self.list_invoice_sections_by_create_subscription_permission.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore else: request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request async def extract_data(pipeline_response): deserialized = self._deserialize("InvoiceSectionListWithCreateSubPermissionResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged(get_next, extract_data) list_invoice_sections_by_create_subscription_permission.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/listInvoiceSectionsWithCreateSubscriptionPermission"} # type: ignore
azure-mgmt-billing
/azure_mgmt_billing-6.1.0b1-py3-none-any.whl/azure/mgmt/billing/aio/operations/_billing_accounts_operations.py
_billing_accounts_operations.py
import sys from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, map_error, ) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling from ... import models as _models from ..._vendor import _convert_request from ...operations._billing_accounts_operations import ( build_get_request, build_list_invoice_sections_by_create_subscription_permission_request, build_list_request, build_update_request, ) if sys.version_info >= (3, 8): from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports else: from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] class BillingAccountsOperations: """ .. warning:: **DO NOT** instantiate this class directly. Instead, you should access the following operations through :class:`~azure.mgmt.billing.aio.BillingManagementClient`'s :attr:`billing_accounts` attribute. """ models = _models def __init__(self, *args, **kwargs) -> None: input_args = list(args) self._client = input_args.pop(0) if input_args else kwargs.pop("client") self._config = input_args.pop(0) if input_args else kwargs.pop("config") self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace def list(self, expand: Optional[str] = None, **kwargs: Any) -> AsyncIterable["_models.BillingAccount"]: """Lists the billing accounts that a user has access to. :param expand: May be used to expand the soldTo, invoice sections and billing profiles. Default value is None. :type expand: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either BillingAccount or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.BillingAccount] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingAccountListResult] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_request( expand=expand, api_version=api_version, template_url=self.list.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore else: request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request async def extract_data(pipeline_response): deserialized = self._deserialize("BillingAccountListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged(get_next, extract_data) list.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts"} # type: ignore @distributed_trace_async async def get( self, billing_account_name: str, expand: Optional[str] = None, **kwargs: Any ) -> _models.BillingAccount: """Gets a billing account by its ID. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param expand: May be used to expand the soldTo, invoice sections and billing profiles. Default value is None. :type expand: str :keyword callable cls: A custom type or function that will be passed the direct response :return: BillingAccount or the result of cls(response) :rtype: ~azure.mgmt.billing.models.BillingAccount :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingAccount] request = build_get_request( billing_account_name=billing_account_name, expand=expand, api_version=api_version, template_url=self.get.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize("BillingAccount", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}"} # type: ignore async def _update_initial( self, billing_account_name: str, parameters: Union[_models.BillingAccountUpdateRequest, IO], **kwargs: Any ) -> Optional[_models.BillingAccount]: error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.BillingAccount]] content_type = content_type or "application/json" _json = None _content = None if isinstance(parameters, (IO, bytes)): _content = parameters else: _json = self._serialize.body(parameters, "BillingAccountUpdateRequest") request = build_update_request( billing_account_name=billing_account_name, api_version=api_version, content_type=content_type, json=_json, content=_content, template_url=self._update_initial.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = None if response.status_code == 200: deserialized = self._deserialize("BillingAccount", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized _update_initial.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}"} # type: ignore @overload async def begin_update( self, billing_account_name: str, parameters: _models.BillingAccountUpdateRequest, *, content_type: str = "application/json", **kwargs: Any ) -> AsyncLROPoller[_models.BillingAccount]: """Updates the properties of a billing account. Currently, displayName and address can be updated. The operation is supported only for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param parameters: Request parameters that are provided to the update billing account operation. Required. :type parameters: ~azure.mgmt.billing.models.BillingAccountUpdateRequest :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of AsyncLROPoller that returns either BillingAccount or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.BillingAccount] :raises ~azure.core.exceptions.HttpResponseError: """ @overload async def begin_update( self, billing_account_name: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any ) -> AsyncLROPoller[_models.BillingAccount]: """Updates the properties of a billing account. Currently, displayName and address can be updated. The operation is supported only for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param parameters: Request parameters that are provided to the update billing account operation. Required. :type parameters: IO :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of AsyncLROPoller that returns either BillingAccount or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.BillingAccount] :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace_async async def begin_update( self, billing_account_name: str, parameters: Union[_models.BillingAccountUpdateRequest, IO], **kwargs: Any ) -> AsyncLROPoller[_models.BillingAccount]: """Updates the properties of a billing account. Currently, displayName and address can be updated. The operation is supported only for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param parameters: Request parameters that are provided to the update billing account operation. Is either a model type or a IO type. Required. :type parameters: ~azure.mgmt.billing.models.BillingAccountUpdateRequest or IO :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. Default value is None. :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of AsyncLROPoller that returns either BillingAccount or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.BillingAccount] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingAccount] polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod] lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: raw_result = await self._update_initial( # type: ignore billing_account_name=billing_account_name, parameters=parameters, api_version=api_version, content_type=content_type, cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): deserialized = self._deserialize("BillingAccount", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized if polling is True: polling_method = cast( AsyncPollingMethod, AsyncARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs), ) # type: AsyncPollingMethod elif polling is False: polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) else: polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_update.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}"} # type: ignore @distributed_trace def list_invoice_sections_by_create_subscription_permission( self, billing_account_name: str, **kwargs: Any ) -> AsyncIterable["_models.InvoiceSectionWithCreateSubPermission"]: """Lists the invoice sections for which the user has permission to create Azure subscriptions. The operation is supported only for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either InvoiceSectionWithCreateSubPermission or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.InvoiceSectionWithCreateSubPermission] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.InvoiceSectionListWithCreateSubPermissionResult] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_invoice_sections_by_create_subscription_permission_request( billing_account_name=billing_account_name, api_version=api_version, template_url=self.list_invoice_sections_by_create_subscription_permission.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore else: request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request async def extract_data(pipeline_response): deserialized = self._deserialize("InvoiceSectionListWithCreateSubPermissionResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged(get_next, extract_data) list_invoice_sections_by_create_subscription_permission.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/listInvoiceSectionsWithCreateSubscriptionPermission"} # type: ignore
0.685844
0.093347
import sys from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, map_error, ) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models from ..._vendor import _convert_request from ...operations._customers_operations import ( build_get_request, build_list_by_billing_account_request, build_list_by_billing_profile_request, ) if sys.version_info >= (3, 8): from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports else: from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] class CustomersOperations: """ .. warning:: **DO NOT** instantiate this class directly. Instead, you should access the following operations through :class:`~azure.mgmt.billing.aio.BillingManagementClient`'s :attr:`customers` attribute. """ models = _models def __init__(self, *args, **kwargs) -> None: input_args = list(args) self._client = input_args.pop(0) if input_args else kwargs.pop("client") self._config = input_args.pop(0) if input_args else kwargs.pop("config") self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace def list_by_billing_profile( self, billing_account_name: str, billing_profile_name: str, search: Optional[str] = None, filter: Optional[str] = None, **kwargs: Any ) -> AsyncIterable["_models.Customer"]: """Lists the customers that are billed to a billing profile. The operation is supported only for billing accounts with agreement type Microsoft Partner Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :param search: Used for searching customers by their name. Any customer with name containing the search text will be included in the response. Default value is None. :type search: str :param filter: May be used to filter the list of customers. Default value is None. :type filter: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either Customer or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.Customer] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.CustomerListResult] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_by_billing_profile_request( billing_account_name=billing_account_name, billing_profile_name=billing_profile_name, search=search, filter=filter, api_version=api_version, template_url=self.list_by_billing_profile.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore else: request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request async def extract_data(pipeline_response): deserialized = self._deserialize("CustomerListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged(get_next, extract_data) list_by_billing_profile.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/customers"} # type: ignore @distributed_trace def list_by_billing_account( self, billing_account_name: str, search: Optional[str] = None, filter: Optional[str] = None, **kwargs: Any ) -> AsyncIterable["_models.Customer"]: """Lists the customers that are billed to a billing account. The operation is supported only for billing accounts with agreement type Microsoft Partner Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param search: Used for searching customers by their name. Any customer with name containing the search text will be included in the response. Default value is None. :type search: str :param filter: May be used to filter the list of customers. Default value is None. :type filter: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either Customer or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.Customer] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.CustomerListResult] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_by_billing_account_request( billing_account_name=billing_account_name, search=search, filter=filter, api_version=api_version, template_url=self.list_by_billing_account.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore else: request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request async def extract_data(pipeline_response): deserialized = self._deserialize("CustomerListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged(get_next, extract_data) list_by_billing_account.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/customers"} # type: ignore @distributed_trace_async async def get( self, billing_account_name: str, customer_name: str, expand: Optional[str] = None, **kwargs: Any ) -> _models.Customer: """Gets a customer by its ID. The operation is supported only for billing accounts with agreement type Microsoft Partner Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param customer_name: The ID that uniquely identifies a customer. Required. :type customer_name: str :param expand: May be used to expand enabledAzurePlans and resellers. Default value is None. :type expand: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Customer or the result of cls(response) :rtype: ~azure.mgmt.billing.models.Customer :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.Customer] request = build_get_request( billing_account_name=billing_account_name, customer_name=customer_name, expand=expand, api_version=api_version, template_url=self.get.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize("Customer", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/customers/{customerName}"} # type: ignore
azure-mgmt-billing
/azure_mgmt_billing-6.1.0b1-py3-none-any.whl/azure/mgmt/billing/aio/operations/_customers_operations.py
_customers_operations.py
import sys from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, map_error, ) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models from ..._vendor import _convert_request from ...operations._customers_operations import ( build_get_request, build_list_by_billing_account_request, build_list_by_billing_profile_request, ) if sys.version_info >= (3, 8): from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports else: from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] class CustomersOperations: """ .. warning:: **DO NOT** instantiate this class directly. Instead, you should access the following operations through :class:`~azure.mgmt.billing.aio.BillingManagementClient`'s :attr:`customers` attribute. """ models = _models def __init__(self, *args, **kwargs) -> None: input_args = list(args) self._client = input_args.pop(0) if input_args else kwargs.pop("client") self._config = input_args.pop(0) if input_args else kwargs.pop("config") self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace def list_by_billing_profile( self, billing_account_name: str, billing_profile_name: str, search: Optional[str] = None, filter: Optional[str] = None, **kwargs: Any ) -> AsyncIterable["_models.Customer"]: """Lists the customers that are billed to a billing profile. The operation is supported only for billing accounts with agreement type Microsoft Partner Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :param search: Used for searching customers by their name. Any customer with name containing the search text will be included in the response. Default value is None. :type search: str :param filter: May be used to filter the list of customers. Default value is None. :type filter: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either Customer or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.Customer] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.CustomerListResult] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_by_billing_profile_request( billing_account_name=billing_account_name, billing_profile_name=billing_profile_name, search=search, filter=filter, api_version=api_version, template_url=self.list_by_billing_profile.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore else: request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request async def extract_data(pipeline_response): deserialized = self._deserialize("CustomerListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged(get_next, extract_data) list_by_billing_profile.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/customers"} # type: ignore @distributed_trace def list_by_billing_account( self, billing_account_name: str, search: Optional[str] = None, filter: Optional[str] = None, **kwargs: Any ) -> AsyncIterable["_models.Customer"]: """Lists the customers that are billed to a billing account. The operation is supported only for billing accounts with agreement type Microsoft Partner Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param search: Used for searching customers by their name. Any customer with name containing the search text will be included in the response. Default value is None. :type search: str :param filter: May be used to filter the list of customers. Default value is None. :type filter: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either Customer or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.Customer] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.CustomerListResult] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_by_billing_account_request( billing_account_name=billing_account_name, search=search, filter=filter, api_version=api_version, template_url=self.list_by_billing_account.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore else: request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request async def extract_data(pipeline_response): deserialized = self._deserialize("CustomerListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged(get_next, extract_data) list_by_billing_account.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/customers"} # type: ignore @distributed_trace_async async def get( self, billing_account_name: str, customer_name: str, expand: Optional[str] = None, **kwargs: Any ) -> _models.Customer: """Gets a customer by its ID. The operation is supported only for billing accounts with agreement type Microsoft Partner Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param customer_name: The ID that uniquely identifies a customer. Required. :type customer_name: str :param expand: May be used to expand enabledAzurePlans and resellers. Default value is None. :type expand: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Customer or the result of cls(response) :rtype: ~azure.mgmt.billing.models.Customer :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.Customer] request = build_get_request( billing_account_name=billing_account_name, customer_name=customer_name, expand=expand, api_version=api_version, template_url=self.get.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize("Customer", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/customers/{customerName}"} # type: ignore
0.702326
0.090897
import sys from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, map_error, ) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models from ..._vendor import _convert_request from ...operations._billing_role_assignments_operations import ( build_delete_by_billing_account_request, build_delete_by_billing_profile_request, build_delete_by_invoice_section_request, build_get_by_billing_account_request, build_get_by_billing_profile_request, build_get_by_invoice_section_request, build_list_by_billing_account_request, build_list_by_billing_profile_request, build_list_by_invoice_section_request, ) if sys.version_info >= (3, 8): from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports else: from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] class BillingRoleAssignmentsOperations: """ .. warning:: **DO NOT** instantiate this class directly. Instead, you should access the following operations through :class:`~azure.mgmt.billing.aio.BillingManagementClient`'s :attr:`billing_role_assignments` attribute. """ models = _models def __init__(self, *args, **kwargs) -> None: input_args = list(args) self._client = input_args.pop(0) if input_args else kwargs.pop("client") self._config = input_args.pop(0) if input_args else kwargs.pop("config") self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace_async async def get_by_billing_account( self, billing_account_name: str, billing_role_assignment_name: str, **kwargs: Any ) -> _models.BillingRoleAssignment: """Gets a role assignment for the caller on a billing account. The operation is supported for billing accounts with agreement type Microsoft Partner Agreement or Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_role_assignment_name: The ID that uniquely identifies a role assignment. Required. :type billing_role_assignment_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: BillingRoleAssignment or the result of cls(response) :rtype: ~azure.mgmt.billing.models.BillingRoleAssignment :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingRoleAssignment] request = build_get_by_billing_account_request( billing_account_name=billing_account_name, billing_role_assignment_name=billing_role_assignment_name, api_version=api_version, template_url=self.get_by_billing_account.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize("BillingRoleAssignment", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get_by_billing_account.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingRoleAssignments/{billingRoleAssignmentName}"} # type: ignore @distributed_trace_async async def delete_by_billing_account( self, billing_account_name: str, billing_role_assignment_name: str, **kwargs: Any ) -> _models.BillingRoleAssignment: """Deletes a role assignment for the caller on a billing account. The operation is supported for billing accounts with agreement type Microsoft Partner Agreement or Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_role_assignment_name: The ID that uniquely identifies a role assignment. Required. :type billing_role_assignment_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: BillingRoleAssignment or the result of cls(response) :rtype: ~azure.mgmt.billing.models.BillingRoleAssignment :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingRoleAssignment] request = build_delete_by_billing_account_request( billing_account_name=billing_account_name, billing_role_assignment_name=billing_role_assignment_name, api_version=api_version, template_url=self.delete_by_billing_account.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize("BillingRoleAssignment", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized delete_by_billing_account.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingRoleAssignments/{billingRoleAssignmentName}"} # type: ignore @distributed_trace_async async def get_by_invoice_section( self, billing_account_name: str, billing_profile_name: str, invoice_section_name: str, billing_role_assignment_name: str, **kwargs: Any ) -> _models.BillingRoleAssignment: """Gets a role assignment for the caller on an invoice section. The operation is supported for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :param invoice_section_name: The ID that uniquely identifies an invoice section. Required. :type invoice_section_name: str :param billing_role_assignment_name: The ID that uniquely identifies a role assignment. Required. :type billing_role_assignment_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: BillingRoleAssignment or the result of cls(response) :rtype: ~azure.mgmt.billing.models.BillingRoleAssignment :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingRoleAssignment] request = build_get_by_invoice_section_request( billing_account_name=billing_account_name, billing_profile_name=billing_profile_name, invoice_section_name=invoice_section_name, billing_role_assignment_name=billing_role_assignment_name, api_version=api_version, template_url=self.get_by_invoice_section.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize("BillingRoleAssignment", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get_by_invoice_section.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoiceSections/{invoiceSectionName}/billingRoleAssignments/{billingRoleAssignmentName}"} # type: ignore @distributed_trace_async async def delete_by_invoice_section( self, billing_account_name: str, billing_profile_name: str, invoice_section_name: str, billing_role_assignment_name: str, **kwargs: Any ) -> _models.BillingRoleAssignment: """Deletes a role assignment for the caller on an invoice section. The operation is supported for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :param invoice_section_name: The ID that uniquely identifies an invoice section. Required. :type invoice_section_name: str :param billing_role_assignment_name: The ID that uniquely identifies a role assignment. Required. :type billing_role_assignment_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: BillingRoleAssignment or the result of cls(response) :rtype: ~azure.mgmt.billing.models.BillingRoleAssignment :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingRoleAssignment] request = build_delete_by_invoice_section_request( billing_account_name=billing_account_name, billing_profile_name=billing_profile_name, invoice_section_name=invoice_section_name, billing_role_assignment_name=billing_role_assignment_name, api_version=api_version, template_url=self.delete_by_invoice_section.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize("BillingRoleAssignment", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized delete_by_invoice_section.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoiceSections/{invoiceSectionName}/billingRoleAssignments/{billingRoleAssignmentName}"} # type: ignore @distributed_trace_async async def get_by_billing_profile( self, billing_account_name: str, billing_profile_name: str, billing_role_assignment_name: str, **kwargs: Any ) -> _models.BillingRoleAssignment: """Gets a role assignment for the caller on a billing profile. The operation is supported for billing accounts with agreement type Microsoft Partner Agreement or Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :param billing_role_assignment_name: The ID that uniquely identifies a role assignment. Required. :type billing_role_assignment_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: BillingRoleAssignment or the result of cls(response) :rtype: ~azure.mgmt.billing.models.BillingRoleAssignment :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingRoleAssignment] request = build_get_by_billing_profile_request( billing_account_name=billing_account_name, billing_profile_name=billing_profile_name, billing_role_assignment_name=billing_role_assignment_name, api_version=api_version, template_url=self.get_by_billing_profile.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize("BillingRoleAssignment", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get_by_billing_profile.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/billingRoleAssignments/{billingRoleAssignmentName}"} # type: ignore @distributed_trace_async async def delete_by_billing_profile( self, billing_account_name: str, billing_profile_name: str, billing_role_assignment_name: str, **kwargs: Any ) -> _models.BillingRoleAssignment: """Deletes a role assignment for the caller on a billing profile. The operation is supported for billing accounts with agreement type Microsoft Partner Agreement or Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :param billing_role_assignment_name: The ID that uniquely identifies a role assignment. Required. :type billing_role_assignment_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: BillingRoleAssignment or the result of cls(response) :rtype: ~azure.mgmt.billing.models.BillingRoleAssignment :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingRoleAssignment] request = build_delete_by_billing_profile_request( billing_account_name=billing_account_name, billing_profile_name=billing_profile_name, billing_role_assignment_name=billing_role_assignment_name, api_version=api_version, template_url=self.delete_by_billing_profile.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize("BillingRoleAssignment", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized delete_by_billing_profile.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/billingRoleAssignments/{billingRoleAssignmentName}"} # type: ignore @distributed_trace def list_by_billing_account( self, billing_account_name: str, **kwargs: Any ) -> AsyncIterable["_models.BillingRoleAssignment"]: """Lists the role assignments for the caller on a billing account. The operation is supported for billing accounts with agreement type Microsoft Partner Agreement or Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either BillingRoleAssignment or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.BillingRoleAssignment] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingRoleAssignmentListResult] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_by_billing_account_request( billing_account_name=billing_account_name, api_version=api_version, template_url=self.list_by_billing_account.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore else: request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request async def extract_data(pipeline_response): deserialized = self._deserialize("BillingRoleAssignmentListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged(get_next, extract_data) list_by_billing_account.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingRoleAssignments"} # type: ignore @distributed_trace def list_by_invoice_section( self, billing_account_name: str, billing_profile_name: str, invoice_section_name: str, **kwargs: Any ) -> AsyncIterable["_models.BillingRoleAssignment"]: """Lists the role assignments for the caller on an invoice section. The operation is supported for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :param invoice_section_name: The ID that uniquely identifies an invoice section. Required. :type invoice_section_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either BillingRoleAssignment or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.BillingRoleAssignment] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingRoleAssignmentListResult] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_by_invoice_section_request( billing_account_name=billing_account_name, billing_profile_name=billing_profile_name, invoice_section_name=invoice_section_name, api_version=api_version, template_url=self.list_by_invoice_section.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore else: request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request async def extract_data(pipeline_response): deserialized = self._deserialize("BillingRoleAssignmentListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged(get_next, extract_data) list_by_invoice_section.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoiceSections/{invoiceSectionName}/billingRoleAssignments"} # type: ignore @distributed_trace def list_by_billing_profile( self, billing_account_name: str, billing_profile_name: str, **kwargs: Any ) -> AsyncIterable["_models.BillingRoleAssignment"]: """Lists the role assignments for the caller on a billing profile. The operation is supported for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either BillingRoleAssignment or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.BillingRoleAssignment] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingRoleAssignmentListResult] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_by_billing_profile_request( billing_account_name=billing_account_name, billing_profile_name=billing_profile_name, api_version=api_version, template_url=self.list_by_billing_profile.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore else: request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request async def extract_data(pipeline_response): deserialized = self._deserialize("BillingRoleAssignmentListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged(get_next, extract_data) list_by_billing_profile.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/billingRoleAssignments"} # type: ignore
azure-mgmt-billing
/azure_mgmt_billing-6.1.0b1-py3-none-any.whl/azure/mgmt/billing/aio/operations/_billing_role_assignments_operations.py
_billing_role_assignments_operations.py
import sys from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, map_error, ) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models from ..._vendor import _convert_request from ...operations._billing_role_assignments_operations import ( build_delete_by_billing_account_request, build_delete_by_billing_profile_request, build_delete_by_invoice_section_request, build_get_by_billing_account_request, build_get_by_billing_profile_request, build_get_by_invoice_section_request, build_list_by_billing_account_request, build_list_by_billing_profile_request, build_list_by_invoice_section_request, ) if sys.version_info >= (3, 8): from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports else: from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] class BillingRoleAssignmentsOperations: """ .. warning:: **DO NOT** instantiate this class directly. Instead, you should access the following operations through :class:`~azure.mgmt.billing.aio.BillingManagementClient`'s :attr:`billing_role_assignments` attribute. """ models = _models def __init__(self, *args, **kwargs) -> None: input_args = list(args) self._client = input_args.pop(0) if input_args else kwargs.pop("client") self._config = input_args.pop(0) if input_args else kwargs.pop("config") self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace_async async def get_by_billing_account( self, billing_account_name: str, billing_role_assignment_name: str, **kwargs: Any ) -> _models.BillingRoleAssignment: """Gets a role assignment for the caller on a billing account. The operation is supported for billing accounts with agreement type Microsoft Partner Agreement or Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_role_assignment_name: The ID that uniquely identifies a role assignment. Required. :type billing_role_assignment_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: BillingRoleAssignment or the result of cls(response) :rtype: ~azure.mgmt.billing.models.BillingRoleAssignment :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingRoleAssignment] request = build_get_by_billing_account_request( billing_account_name=billing_account_name, billing_role_assignment_name=billing_role_assignment_name, api_version=api_version, template_url=self.get_by_billing_account.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize("BillingRoleAssignment", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get_by_billing_account.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingRoleAssignments/{billingRoleAssignmentName}"} # type: ignore @distributed_trace_async async def delete_by_billing_account( self, billing_account_name: str, billing_role_assignment_name: str, **kwargs: Any ) -> _models.BillingRoleAssignment: """Deletes a role assignment for the caller on a billing account. The operation is supported for billing accounts with agreement type Microsoft Partner Agreement or Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_role_assignment_name: The ID that uniquely identifies a role assignment. Required. :type billing_role_assignment_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: BillingRoleAssignment or the result of cls(response) :rtype: ~azure.mgmt.billing.models.BillingRoleAssignment :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingRoleAssignment] request = build_delete_by_billing_account_request( billing_account_name=billing_account_name, billing_role_assignment_name=billing_role_assignment_name, api_version=api_version, template_url=self.delete_by_billing_account.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize("BillingRoleAssignment", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized delete_by_billing_account.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingRoleAssignments/{billingRoleAssignmentName}"} # type: ignore @distributed_trace_async async def get_by_invoice_section( self, billing_account_name: str, billing_profile_name: str, invoice_section_name: str, billing_role_assignment_name: str, **kwargs: Any ) -> _models.BillingRoleAssignment: """Gets a role assignment for the caller on an invoice section. The operation is supported for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :param invoice_section_name: The ID that uniquely identifies an invoice section. Required. :type invoice_section_name: str :param billing_role_assignment_name: The ID that uniquely identifies a role assignment. Required. :type billing_role_assignment_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: BillingRoleAssignment or the result of cls(response) :rtype: ~azure.mgmt.billing.models.BillingRoleAssignment :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingRoleAssignment] request = build_get_by_invoice_section_request( billing_account_name=billing_account_name, billing_profile_name=billing_profile_name, invoice_section_name=invoice_section_name, billing_role_assignment_name=billing_role_assignment_name, api_version=api_version, template_url=self.get_by_invoice_section.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize("BillingRoleAssignment", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get_by_invoice_section.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoiceSections/{invoiceSectionName}/billingRoleAssignments/{billingRoleAssignmentName}"} # type: ignore @distributed_trace_async async def delete_by_invoice_section( self, billing_account_name: str, billing_profile_name: str, invoice_section_name: str, billing_role_assignment_name: str, **kwargs: Any ) -> _models.BillingRoleAssignment: """Deletes a role assignment for the caller on an invoice section. The operation is supported for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :param invoice_section_name: The ID that uniquely identifies an invoice section. Required. :type invoice_section_name: str :param billing_role_assignment_name: The ID that uniquely identifies a role assignment. Required. :type billing_role_assignment_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: BillingRoleAssignment or the result of cls(response) :rtype: ~azure.mgmt.billing.models.BillingRoleAssignment :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingRoleAssignment] request = build_delete_by_invoice_section_request( billing_account_name=billing_account_name, billing_profile_name=billing_profile_name, invoice_section_name=invoice_section_name, billing_role_assignment_name=billing_role_assignment_name, api_version=api_version, template_url=self.delete_by_invoice_section.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize("BillingRoleAssignment", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized delete_by_invoice_section.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoiceSections/{invoiceSectionName}/billingRoleAssignments/{billingRoleAssignmentName}"} # type: ignore @distributed_trace_async async def get_by_billing_profile( self, billing_account_name: str, billing_profile_name: str, billing_role_assignment_name: str, **kwargs: Any ) -> _models.BillingRoleAssignment: """Gets a role assignment for the caller on a billing profile. The operation is supported for billing accounts with agreement type Microsoft Partner Agreement or Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :param billing_role_assignment_name: The ID that uniquely identifies a role assignment. Required. :type billing_role_assignment_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: BillingRoleAssignment or the result of cls(response) :rtype: ~azure.mgmt.billing.models.BillingRoleAssignment :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingRoleAssignment] request = build_get_by_billing_profile_request( billing_account_name=billing_account_name, billing_profile_name=billing_profile_name, billing_role_assignment_name=billing_role_assignment_name, api_version=api_version, template_url=self.get_by_billing_profile.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize("BillingRoleAssignment", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get_by_billing_profile.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/billingRoleAssignments/{billingRoleAssignmentName}"} # type: ignore @distributed_trace_async async def delete_by_billing_profile( self, billing_account_name: str, billing_profile_name: str, billing_role_assignment_name: str, **kwargs: Any ) -> _models.BillingRoleAssignment: """Deletes a role assignment for the caller on a billing profile. The operation is supported for billing accounts with agreement type Microsoft Partner Agreement or Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :param billing_role_assignment_name: The ID that uniquely identifies a role assignment. Required. :type billing_role_assignment_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: BillingRoleAssignment or the result of cls(response) :rtype: ~azure.mgmt.billing.models.BillingRoleAssignment :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingRoleAssignment] request = build_delete_by_billing_profile_request( billing_account_name=billing_account_name, billing_profile_name=billing_profile_name, billing_role_assignment_name=billing_role_assignment_name, api_version=api_version, template_url=self.delete_by_billing_profile.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize("BillingRoleAssignment", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized delete_by_billing_profile.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/billingRoleAssignments/{billingRoleAssignmentName}"} # type: ignore @distributed_trace def list_by_billing_account( self, billing_account_name: str, **kwargs: Any ) -> AsyncIterable["_models.BillingRoleAssignment"]: """Lists the role assignments for the caller on a billing account. The operation is supported for billing accounts with agreement type Microsoft Partner Agreement or Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either BillingRoleAssignment or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.BillingRoleAssignment] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingRoleAssignmentListResult] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_by_billing_account_request( billing_account_name=billing_account_name, api_version=api_version, template_url=self.list_by_billing_account.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore else: request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request async def extract_data(pipeline_response): deserialized = self._deserialize("BillingRoleAssignmentListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged(get_next, extract_data) list_by_billing_account.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingRoleAssignments"} # type: ignore @distributed_trace def list_by_invoice_section( self, billing_account_name: str, billing_profile_name: str, invoice_section_name: str, **kwargs: Any ) -> AsyncIterable["_models.BillingRoleAssignment"]: """Lists the role assignments for the caller on an invoice section. The operation is supported for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :param invoice_section_name: The ID that uniquely identifies an invoice section. Required. :type invoice_section_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either BillingRoleAssignment or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.BillingRoleAssignment] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingRoleAssignmentListResult] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_by_invoice_section_request( billing_account_name=billing_account_name, billing_profile_name=billing_profile_name, invoice_section_name=invoice_section_name, api_version=api_version, template_url=self.list_by_invoice_section.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore else: request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request async def extract_data(pipeline_response): deserialized = self._deserialize("BillingRoleAssignmentListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged(get_next, extract_data) list_by_invoice_section.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoiceSections/{invoiceSectionName}/billingRoleAssignments"} # type: ignore @distributed_trace def list_by_billing_profile( self, billing_account_name: str, billing_profile_name: str, **kwargs: Any ) -> AsyncIterable["_models.BillingRoleAssignment"]: """Lists the role assignments for the caller on a billing profile. The operation is supported for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either BillingRoleAssignment or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.BillingRoleAssignment] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingRoleAssignmentListResult] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_by_billing_profile_request( billing_account_name=billing_account_name, billing_profile_name=billing_profile_name, api_version=api_version, template_url=self.list_by_billing_profile.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore else: request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request async def extract_data(pipeline_response): deserialized = self._deserialize("BillingRoleAssignmentListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged(get_next, extract_data) list_by_billing_profile.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/billingRoleAssignments"} # type: ignore
0.659953
0.080069
import sys from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, overload from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, map_error, ) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models from ..._vendor import _convert_request from ...operations._products_operations import ( build_get_request, build_list_by_billing_account_request, build_list_by_billing_profile_request, build_list_by_customer_request, build_list_by_invoice_section_request, build_move_request, build_update_request, build_validate_move_request, ) if sys.version_info >= (3, 8): from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports else: from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] class ProductsOperations: """ .. warning:: **DO NOT** instantiate this class directly. Instead, you should access the following operations through :class:`~azure.mgmt.billing.aio.BillingManagementClient`'s :attr:`products` attribute. """ models = _models def __init__(self, *args, **kwargs) -> None: input_args = list(args) self._client = input_args.pop(0) if input_args else kwargs.pop("client") self._config = input_args.pop(0) if input_args else kwargs.pop("config") self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace def list_by_customer( self, billing_account_name: str, customer_name: str, **kwargs: Any ) -> AsyncIterable["_models.Product"]: """Lists the products for a customer. These don't include products billed based on usage.The operation is supported only for billing accounts with agreement type Microsoft Partner Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param customer_name: The ID that uniquely identifies a customer. Required. :type customer_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either Product or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.Product] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.ProductsListResult] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_by_customer_request( billing_account_name=billing_account_name, customer_name=customer_name, api_version=api_version, template_url=self.list_by_customer.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore else: request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request async def extract_data(pipeline_response): deserialized = self._deserialize("ProductsListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged(get_next, extract_data) list_by_customer.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/customers/{customerName}/products"} # type: ignore @distributed_trace def list_by_billing_account( self, billing_account_name: str, filter: Optional[str] = None, **kwargs: Any ) -> AsyncIterable["_models.Product"]: """Lists the products for a billing account. These don't include products billed based on usage. The operation is supported for billing accounts with agreement type Microsoft Customer Agreement or Microsoft Partner Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param filter: May be used to filter by product type. The filter supports 'eq', 'lt', 'gt', 'le', 'ge', and 'and'. It does not currently support 'ne', 'or', or 'not'. Tag filter is a key value pair string where key and value are separated by a colon (:). Default value is None. :type filter: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either Product or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.Product] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.ProductsListResult] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_by_billing_account_request( billing_account_name=billing_account_name, filter=filter, api_version=api_version, template_url=self.list_by_billing_account.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore else: request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request async def extract_data(pipeline_response): deserialized = self._deserialize("ProductsListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged(get_next, extract_data) list_by_billing_account.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/products"} # type: ignore @distributed_trace def list_by_billing_profile( self, billing_account_name: str, billing_profile_name: str, filter: Optional[str] = None, **kwargs: Any ) -> AsyncIterable["_models.Product"]: """Lists the products for a billing profile. These don't include products billed based on usage. The operation is supported for billing accounts with agreement type Microsoft Customer Agreement or Microsoft Partner Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :param filter: May be used to filter by product type. The filter supports 'eq', 'lt', 'gt', 'le', 'ge', and 'and'. It does not currently support 'ne', 'or', or 'not'. Tag filter is a key value pair string where key and value are separated by a colon (:). Default value is None. :type filter: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either Product or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.Product] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.ProductsListResult] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_by_billing_profile_request( billing_account_name=billing_account_name, billing_profile_name=billing_profile_name, filter=filter, api_version=api_version, template_url=self.list_by_billing_profile.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore else: request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request async def extract_data(pipeline_response): deserialized = self._deserialize("ProductsListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged(get_next, extract_data) list_by_billing_profile.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/products"} # type: ignore @distributed_trace def list_by_invoice_section( self, billing_account_name: str, billing_profile_name: str, invoice_section_name: str, filter: Optional[str] = None, **kwargs: Any ) -> AsyncIterable["_models.Product"]: """Lists the products for an invoice section. These don't include products billed based on usage. The operation is supported only for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :param invoice_section_name: The ID that uniquely identifies an invoice section. Required. :type invoice_section_name: str :param filter: May be used to filter by product type. The filter supports 'eq', 'lt', 'gt', 'le', 'ge', and 'and'. It does not currently support 'ne', 'or', or 'not'. Tag filter is a key value pair string where key and value are separated by a colon (:). Default value is None. :type filter: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either Product or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.Product] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.ProductsListResult] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_by_invoice_section_request( billing_account_name=billing_account_name, billing_profile_name=billing_profile_name, invoice_section_name=invoice_section_name, filter=filter, api_version=api_version, template_url=self.list_by_invoice_section.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore else: request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request async def extract_data(pipeline_response): deserialized = self._deserialize("ProductsListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged(get_next, extract_data) list_by_invoice_section.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoiceSections/{invoiceSectionName}/products"} # type: ignore @distributed_trace_async async def get(self, billing_account_name: str, product_name: str, **kwargs: Any) -> _models.Product: """Gets a product by ID. The operation is supported only for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param product_name: The ID that uniquely identifies a product. Required. :type product_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Product or the result of cls(response) :rtype: ~azure.mgmt.billing.models.Product :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.Product] request = build_get_request( billing_account_name=billing_account_name, product_name=product_name, api_version=api_version, template_url=self.get.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize("Product", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/products/{productName}"} # type: ignore @overload async def update( self, billing_account_name: str, product_name: str, parameters: _models.Product, *, content_type: str = "application/json", **kwargs: Any ) -> _models.Product: """Updates the properties of a Product. Currently, auto renew can be updated. The operation is supported only for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param product_name: The ID that uniquely identifies a product. Required. :type product_name: str :param parameters: Request parameters that are provided to the update product operation. Required. :type parameters: ~azure.mgmt.billing.models.Product :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Product or the result of cls(response) :rtype: ~azure.mgmt.billing.models.Product :raises ~azure.core.exceptions.HttpResponseError: """ @overload async def update( self, billing_account_name: str, product_name: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any ) -> _models.Product: """Updates the properties of a Product. Currently, auto renew can be updated. The operation is supported only for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param product_name: The ID that uniquely identifies a product. Required. :type product_name: str :param parameters: Request parameters that are provided to the update product operation. Required. :type parameters: IO :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Product or the result of cls(response) :rtype: ~azure.mgmt.billing.models.Product :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace_async async def update( self, billing_account_name: str, product_name: str, parameters: Union[_models.Product, IO], **kwargs: Any ) -> _models.Product: """Updates the properties of a Product. Currently, auto renew can be updated. The operation is supported only for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param product_name: The ID that uniquely identifies a product. Required. :type product_name: str :param parameters: Request parameters that are provided to the update product operation. Is either a model type or a IO type. Required. :type parameters: ~azure.mgmt.billing.models.Product or IO :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. Default value is None. :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Product or the result of cls(response) :rtype: ~azure.mgmt.billing.models.Product :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] cls = kwargs.pop("cls", None) # type: ClsType[_models.Product] content_type = content_type or "application/json" _json = None _content = None if isinstance(parameters, (IO, bytes)): _content = parameters else: _json = self._serialize.body(parameters, "Product") request = build_update_request( billing_account_name=billing_account_name, product_name=product_name, api_version=api_version, content_type=content_type, json=_json, content=_content, template_url=self.update.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize("Product", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized update.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/products/{productName}"} # type: ignore @overload async def move( self, billing_account_name: str, product_name: str, parameters: _models.TransferProductRequestProperties, *, content_type: str = "application/json", **kwargs: Any ) -> Optional[_models.Product]: """Moves a product's charges to a new invoice section. The new invoice section must belong to the same billing profile as the existing invoice section. This operation is supported only for products that are purchased with a recurring charge and for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param product_name: The ID that uniquely identifies a product. Required. :type product_name: str :param parameters: Request parameters that are provided to the move product operation. Required. :type parameters: ~azure.mgmt.billing.models.TransferProductRequestProperties :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Product or None or the result of cls(response) :rtype: ~azure.mgmt.billing.models.Product or None :raises ~azure.core.exceptions.HttpResponseError: """ @overload async def move( self, billing_account_name: str, product_name: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any ) -> Optional[_models.Product]: """Moves a product's charges to a new invoice section. The new invoice section must belong to the same billing profile as the existing invoice section. This operation is supported only for products that are purchased with a recurring charge and for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param product_name: The ID that uniquely identifies a product. Required. :type product_name: str :param parameters: Request parameters that are provided to the move product operation. Required. :type parameters: IO :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Product or None or the result of cls(response) :rtype: ~azure.mgmt.billing.models.Product or None :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace_async async def move( self, billing_account_name: str, product_name: str, parameters: Union[_models.TransferProductRequestProperties, IO], **kwargs: Any ) -> Optional[_models.Product]: """Moves a product's charges to a new invoice section. The new invoice section must belong to the same billing profile as the existing invoice section. This operation is supported only for products that are purchased with a recurring charge and for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param product_name: The ID that uniquely identifies a product. Required. :type product_name: str :param parameters: Request parameters that are provided to the move product operation. Is either a model type or a IO type. Required. :type parameters: ~azure.mgmt.billing.models.TransferProductRequestProperties or IO :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. Default value is None. :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Product or None or the result of cls(response) :rtype: ~azure.mgmt.billing.models.Product or None :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.Product]] content_type = content_type or "application/json" _json = None _content = None if isinstance(parameters, (IO, bytes)): _content = parameters else: _json = self._serialize.body(parameters, "TransferProductRequestProperties") request = build_move_request( billing_account_name=billing_account_name, product_name=product_name, api_version=api_version, content_type=content_type, json=_json, content=_content, template_url=self.move.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = None response_headers = {} if response.status_code == 200: deserialized = self._deserialize("Product", pipeline_response) if response.status_code == 202: response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) if cls: return cls(pipeline_response, deserialized, response_headers) return deserialized move.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/products/{productName}/move"} # type: ignore @overload async def validate_move( self, billing_account_name: str, product_name: str, parameters: _models.TransferProductRequestProperties, *, content_type: str = "application/json", **kwargs: Any ) -> _models.ValidateProductTransferEligibilityResult: """Validates if a product's charges can be moved to a new invoice section. This operation is supported only for products that are purchased with a recurring charge and for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param product_name: The ID that uniquely identifies a product. Required. :type product_name: str :param parameters: Request parameters that are provided to the validate move eligibility operation. Required. :type parameters: ~azure.mgmt.billing.models.TransferProductRequestProperties :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: ValidateProductTransferEligibilityResult or the result of cls(response) :rtype: ~azure.mgmt.billing.models.ValidateProductTransferEligibilityResult :raises ~azure.core.exceptions.HttpResponseError: """ @overload async def validate_move( self, billing_account_name: str, product_name: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any ) -> _models.ValidateProductTransferEligibilityResult: """Validates if a product's charges can be moved to a new invoice section. This operation is supported only for products that are purchased with a recurring charge and for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param product_name: The ID that uniquely identifies a product. Required. :type product_name: str :param parameters: Request parameters that are provided to the validate move eligibility operation. Required. :type parameters: IO :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: ValidateProductTransferEligibilityResult or the result of cls(response) :rtype: ~azure.mgmt.billing.models.ValidateProductTransferEligibilityResult :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace_async async def validate_move( self, billing_account_name: str, product_name: str, parameters: Union[_models.TransferProductRequestProperties, IO], **kwargs: Any ) -> _models.ValidateProductTransferEligibilityResult: """Validates if a product's charges can be moved to a new invoice section. This operation is supported only for products that are purchased with a recurring charge and for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param product_name: The ID that uniquely identifies a product. Required. :type product_name: str :param parameters: Request parameters that are provided to the validate move eligibility operation. Is either a model type or a IO type. Required. :type parameters: ~azure.mgmt.billing.models.TransferProductRequestProperties or IO :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. Default value is None. :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: ValidateProductTransferEligibilityResult or the result of cls(response) :rtype: ~azure.mgmt.billing.models.ValidateProductTransferEligibilityResult :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] cls = kwargs.pop("cls", None) # type: ClsType[_models.ValidateProductTransferEligibilityResult] content_type = content_type or "application/json" _json = None _content = None if isinstance(parameters, (IO, bytes)): _content = parameters else: _json = self._serialize.body(parameters, "TransferProductRequestProperties") request = build_validate_move_request( billing_account_name=billing_account_name, product_name=product_name, api_version=api_version, content_type=content_type, json=_json, content=_content, template_url=self.validate_move.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize("ValidateProductTransferEligibilityResult", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized validate_move.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/products/{productName}/validateMoveEligibility"} # type: ignore
azure-mgmt-billing
/azure_mgmt_billing-6.1.0b1-py3-none-any.whl/azure/mgmt/billing/aio/operations/_products_operations.py
_products_operations.py
import sys from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, overload from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, map_error, ) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models from ..._vendor import _convert_request from ...operations._products_operations import ( build_get_request, build_list_by_billing_account_request, build_list_by_billing_profile_request, build_list_by_customer_request, build_list_by_invoice_section_request, build_move_request, build_update_request, build_validate_move_request, ) if sys.version_info >= (3, 8): from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports else: from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] class ProductsOperations: """ .. warning:: **DO NOT** instantiate this class directly. Instead, you should access the following operations through :class:`~azure.mgmt.billing.aio.BillingManagementClient`'s :attr:`products` attribute. """ models = _models def __init__(self, *args, **kwargs) -> None: input_args = list(args) self._client = input_args.pop(0) if input_args else kwargs.pop("client") self._config = input_args.pop(0) if input_args else kwargs.pop("config") self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace def list_by_customer( self, billing_account_name: str, customer_name: str, **kwargs: Any ) -> AsyncIterable["_models.Product"]: """Lists the products for a customer. These don't include products billed based on usage.The operation is supported only for billing accounts with agreement type Microsoft Partner Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param customer_name: The ID that uniquely identifies a customer. Required. :type customer_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either Product or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.Product] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.ProductsListResult] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_by_customer_request( billing_account_name=billing_account_name, customer_name=customer_name, api_version=api_version, template_url=self.list_by_customer.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore else: request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request async def extract_data(pipeline_response): deserialized = self._deserialize("ProductsListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged(get_next, extract_data) list_by_customer.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/customers/{customerName}/products"} # type: ignore @distributed_trace def list_by_billing_account( self, billing_account_name: str, filter: Optional[str] = None, **kwargs: Any ) -> AsyncIterable["_models.Product"]: """Lists the products for a billing account. These don't include products billed based on usage. The operation is supported for billing accounts with agreement type Microsoft Customer Agreement or Microsoft Partner Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param filter: May be used to filter by product type. The filter supports 'eq', 'lt', 'gt', 'le', 'ge', and 'and'. It does not currently support 'ne', 'or', or 'not'. Tag filter is a key value pair string where key and value are separated by a colon (:). Default value is None. :type filter: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either Product or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.Product] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.ProductsListResult] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_by_billing_account_request( billing_account_name=billing_account_name, filter=filter, api_version=api_version, template_url=self.list_by_billing_account.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore else: request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request async def extract_data(pipeline_response): deserialized = self._deserialize("ProductsListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged(get_next, extract_data) list_by_billing_account.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/products"} # type: ignore @distributed_trace def list_by_billing_profile( self, billing_account_name: str, billing_profile_name: str, filter: Optional[str] = None, **kwargs: Any ) -> AsyncIterable["_models.Product"]: """Lists the products for a billing profile. These don't include products billed based on usage. The operation is supported for billing accounts with agreement type Microsoft Customer Agreement or Microsoft Partner Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :param filter: May be used to filter by product type. The filter supports 'eq', 'lt', 'gt', 'le', 'ge', and 'and'. It does not currently support 'ne', 'or', or 'not'. Tag filter is a key value pair string where key and value are separated by a colon (:). Default value is None. :type filter: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either Product or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.Product] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.ProductsListResult] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_by_billing_profile_request( billing_account_name=billing_account_name, billing_profile_name=billing_profile_name, filter=filter, api_version=api_version, template_url=self.list_by_billing_profile.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore else: request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request async def extract_data(pipeline_response): deserialized = self._deserialize("ProductsListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged(get_next, extract_data) list_by_billing_profile.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/products"} # type: ignore @distributed_trace def list_by_invoice_section( self, billing_account_name: str, billing_profile_name: str, invoice_section_name: str, filter: Optional[str] = None, **kwargs: Any ) -> AsyncIterable["_models.Product"]: """Lists the products for an invoice section. These don't include products billed based on usage. The operation is supported only for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :param invoice_section_name: The ID that uniquely identifies an invoice section. Required. :type invoice_section_name: str :param filter: May be used to filter by product type. The filter supports 'eq', 'lt', 'gt', 'le', 'ge', and 'and'. It does not currently support 'ne', 'or', or 'not'. Tag filter is a key value pair string where key and value are separated by a colon (:). Default value is None. :type filter: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either Product or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.Product] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.ProductsListResult] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_by_invoice_section_request( billing_account_name=billing_account_name, billing_profile_name=billing_profile_name, invoice_section_name=invoice_section_name, filter=filter, api_version=api_version, template_url=self.list_by_invoice_section.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore else: request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request async def extract_data(pipeline_response): deserialized = self._deserialize("ProductsListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged(get_next, extract_data) list_by_invoice_section.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoiceSections/{invoiceSectionName}/products"} # type: ignore @distributed_trace_async async def get(self, billing_account_name: str, product_name: str, **kwargs: Any) -> _models.Product: """Gets a product by ID. The operation is supported only for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param product_name: The ID that uniquely identifies a product. Required. :type product_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Product or the result of cls(response) :rtype: ~azure.mgmt.billing.models.Product :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.Product] request = build_get_request( billing_account_name=billing_account_name, product_name=product_name, api_version=api_version, template_url=self.get.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize("Product", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/products/{productName}"} # type: ignore @overload async def update( self, billing_account_name: str, product_name: str, parameters: _models.Product, *, content_type: str = "application/json", **kwargs: Any ) -> _models.Product: """Updates the properties of a Product. Currently, auto renew can be updated. The operation is supported only for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param product_name: The ID that uniquely identifies a product. Required. :type product_name: str :param parameters: Request parameters that are provided to the update product operation. Required. :type parameters: ~azure.mgmt.billing.models.Product :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Product or the result of cls(response) :rtype: ~azure.mgmt.billing.models.Product :raises ~azure.core.exceptions.HttpResponseError: """ @overload async def update( self, billing_account_name: str, product_name: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any ) -> _models.Product: """Updates the properties of a Product. Currently, auto renew can be updated. The operation is supported only for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param product_name: The ID that uniquely identifies a product. Required. :type product_name: str :param parameters: Request parameters that are provided to the update product operation. Required. :type parameters: IO :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Product or the result of cls(response) :rtype: ~azure.mgmt.billing.models.Product :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace_async async def update( self, billing_account_name: str, product_name: str, parameters: Union[_models.Product, IO], **kwargs: Any ) -> _models.Product: """Updates the properties of a Product. Currently, auto renew can be updated. The operation is supported only for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param product_name: The ID that uniquely identifies a product. Required. :type product_name: str :param parameters: Request parameters that are provided to the update product operation. Is either a model type or a IO type. Required. :type parameters: ~azure.mgmt.billing.models.Product or IO :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. Default value is None. :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Product or the result of cls(response) :rtype: ~azure.mgmt.billing.models.Product :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] cls = kwargs.pop("cls", None) # type: ClsType[_models.Product] content_type = content_type or "application/json" _json = None _content = None if isinstance(parameters, (IO, bytes)): _content = parameters else: _json = self._serialize.body(parameters, "Product") request = build_update_request( billing_account_name=billing_account_name, product_name=product_name, api_version=api_version, content_type=content_type, json=_json, content=_content, template_url=self.update.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize("Product", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized update.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/products/{productName}"} # type: ignore @overload async def move( self, billing_account_name: str, product_name: str, parameters: _models.TransferProductRequestProperties, *, content_type: str = "application/json", **kwargs: Any ) -> Optional[_models.Product]: """Moves a product's charges to a new invoice section. The new invoice section must belong to the same billing profile as the existing invoice section. This operation is supported only for products that are purchased with a recurring charge and for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param product_name: The ID that uniquely identifies a product. Required. :type product_name: str :param parameters: Request parameters that are provided to the move product operation. Required. :type parameters: ~azure.mgmt.billing.models.TransferProductRequestProperties :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Product or None or the result of cls(response) :rtype: ~azure.mgmt.billing.models.Product or None :raises ~azure.core.exceptions.HttpResponseError: """ @overload async def move( self, billing_account_name: str, product_name: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any ) -> Optional[_models.Product]: """Moves a product's charges to a new invoice section. The new invoice section must belong to the same billing profile as the existing invoice section. This operation is supported only for products that are purchased with a recurring charge and for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param product_name: The ID that uniquely identifies a product. Required. :type product_name: str :param parameters: Request parameters that are provided to the move product operation. Required. :type parameters: IO :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Product or None or the result of cls(response) :rtype: ~azure.mgmt.billing.models.Product or None :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace_async async def move( self, billing_account_name: str, product_name: str, parameters: Union[_models.TransferProductRequestProperties, IO], **kwargs: Any ) -> Optional[_models.Product]: """Moves a product's charges to a new invoice section. The new invoice section must belong to the same billing profile as the existing invoice section. This operation is supported only for products that are purchased with a recurring charge and for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param product_name: The ID that uniquely identifies a product. Required. :type product_name: str :param parameters: Request parameters that are provided to the move product operation. Is either a model type or a IO type. Required. :type parameters: ~azure.mgmt.billing.models.TransferProductRequestProperties or IO :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. Default value is None. :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Product or None or the result of cls(response) :rtype: ~azure.mgmt.billing.models.Product or None :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.Product]] content_type = content_type or "application/json" _json = None _content = None if isinstance(parameters, (IO, bytes)): _content = parameters else: _json = self._serialize.body(parameters, "TransferProductRequestProperties") request = build_move_request( billing_account_name=billing_account_name, product_name=product_name, api_version=api_version, content_type=content_type, json=_json, content=_content, template_url=self.move.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = None response_headers = {} if response.status_code == 200: deserialized = self._deserialize("Product", pipeline_response) if response.status_code == 202: response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) if cls: return cls(pipeline_response, deserialized, response_headers) return deserialized move.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/products/{productName}/move"} # type: ignore @overload async def validate_move( self, billing_account_name: str, product_name: str, parameters: _models.TransferProductRequestProperties, *, content_type: str = "application/json", **kwargs: Any ) -> _models.ValidateProductTransferEligibilityResult: """Validates if a product's charges can be moved to a new invoice section. This operation is supported only for products that are purchased with a recurring charge and for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param product_name: The ID that uniquely identifies a product. Required. :type product_name: str :param parameters: Request parameters that are provided to the validate move eligibility operation. Required. :type parameters: ~azure.mgmt.billing.models.TransferProductRequestProperties :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: ValidateProductTransferEligibilityResult or the result of cls(response) :rtype: ~azure.mgmt.billing.models.ValidateProductTransferEligibilityResult :raises ~azure.core.exceptions.HttpResponseError: """ @overload async def validate_move( self, billing_account_name: str, product_name: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any ) -> _models.ValidateProductTransferEligibilityResult: """Validates if a product's charges can be moved to a new invoice section. This operation is supported only for products that are purchased with a recurring charge and for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param product_name: The ID that uniquely identifies a product. Required. :type product_name: str :param parameters: Request parameters that are provided to the validate move eligibility operation. Required. :type parameters: IO :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: ValidateProductTransferEligibilityResult or the result of cls(response) :rtype: ~azure.mgmt.billing.models.ValidateProductTransferEligibilityResult :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace_async async def validate_move( self, billing_account_name: str, product_name: str, parameters: Union[_models.TransferProductRequestProperties, IO], **kwargs: Any ) -> _models.ValidateProductTransferEligibilityResult: """Validates if a product's charges can be moved to a new invoice section. This operation is supported only for products that are purchased with a recurring charge and for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param product_name: The ID that uniquely identifies a product. Required. :type product_name: str :param parameters: Request parameters that are provided to the validate move eligibility operation. Is either a model type or a IO type. Required. :type parameters: ~azure.mgmt.billing.models.TransferProductRequestProperties or IO :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. Default value is None. :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: ValidateProductTransferEligibilityResult or the result of cls(response) :rtype: ~azure.mgmt.billing.models.ValidateProductTransferEligibilityResult :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] cls = kwargs.pop("cls", None) # type: ClsType[_models.ValidateProductTransferEligibilityResult] content_type = content_type or "application/json" _json = None _content = None if isinstance(parameters, (IO, bytes)): _content = parameters else: _json = self._serialize.body(parameters, "TransferProductRequestProperties") request = build_validate_move_request( billing_account_name=billing_account_name, product_name=product_name, api_version=api_version, content_type=content_type, json=_json, content=_content, template_url=self.validate_move.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize("ValidateProductTransferEligibilityResult", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized validate_move.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/products/{productName}/validateMoveEligibility"} # type: ignore
0.709523
0.079282
import sys from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, map_error, ) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models from ..._vendor import _convert_request from ...operations._billing_role_definitions_operations import ( build_get_by_billing_account_request, build_get_by_billing_profile_request, build_get_by_invoice_section_request, build_list_by_billing_account_request, build_list_by_billing_profile_request, build_list_by_invoice_section_request, ) if sys.version_info >= (3, 8): from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports else: from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] class BillingRoleDefinitionsOperations: """ .. warning:: **DO NOT** instantiate this class directly. Instead, you should access the following operations through :class:`~azure.mgmt.billing.aio.BillingManagementClient`'s :attr:`billing_role_definitions` attribute. """ models = _models def __init__(self, *args, **kwargs) -> None: input_args = list(args) self._client = input_args.pop(0) if input_args else kwargs.pop("client") self._config = input_args.pop(0) if input_args else kwargs.pop("config") self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace_async async def get_by_billing_account( self, billing_account_name: str, billing_role_definition_name: str, **kwargs: Any ) -> _models.BillingRoleDefinition: """Gets the definition for a role on a billing account. The operation is supported for billing accounts with agreement type Microsoft Partner Agreement or Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_role_definition_name: The ID that uniquely identifies a role definition. Required. :type billing_role_definition_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: BillingRoleDefinition or the result of cls(response) :rtype: ~azure.mgmt.billing.models.BillingRoleDefinition :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingRoleDefinition] request = build_get_by_billing_account_request( billing_account_name=billing_account_name, billing_role_definition_name=billing_role_definition_name, api_version=api_version, template_url=self.get_by_billing_account.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize("BillingRoleDefinition", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get_by_billing_account.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingRoleDefinitions/{billingRoleDefinitionName}"} # type: ignore @distributed_trace_async async def get_by_invoice_section( self, billing_account_name: str, billing_profile_name: str, invoice_section_name: str, billing_role_definition_name: str, **kwargs: Any ) -> _models.BillingRoleDefinition: """Gets the definition for a role on an invoice section. The operation is supported only for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :param invoice_section_name: The ID that uniquely identifies an invoice section. Required. :type invoice_section_name: str :param billing_role_definition_name: The ID that uniquely identifies a role definition. Required. :type billing_role_definition_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: BillingRoleDefinition or the result of cls(response) :rtype: ~azure.mgmt.billing.models.BillingRoleDefinition :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingRoleDefinition] request = build_get_by_invoice_section_request( billing_account_name=billing_account_name, billing_profile_name=billing_profile_name, invoice_section_name=invoice_section_name, billing_role_definition_name=billing_role_definition_name, api_version=api_version, template_url=self.get_by_invoice_section.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize("BillingRoleDefinition", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get_by_invoice_section.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoiceSections/{invoiceSectionName}/billingRoleDefinitions/{billingRoleDefinitionName}"} # type: ignore @distributed_trace_async async def get_by_billing_profile( self, billing_account_name: str, billing_profile_name: str, billing_role_definition_name: str, **kwargs: Any ) -> _models.BillingRoleDefinition: """Gets the definition for a role on a billing profile. The operation is supported for billing accounts with agreement type Microsoft Partner Agreement or Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :param billing_role_definition_name: The ID that uniquely identifies a role definition. Required. :type billing_role_definition_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: BillingRoleDefinition or the result of cls(response) :rtype: ~azure.mgmt.billing.models.BillingRoleDefinition :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingRoleDefinition] request = build_get_by_billing_profile_request( billing_account_name=billing_account_name, billing_profile_name=billing_profile_name, billing_role_definition_name=billing_role_definition_name, api_version=api_version, template_url=self.get_by_billing_profile.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize("BillingRoleDefinition", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get_by_billing_profile.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/billingRoleDefinitions/{billingRoleDefinitionName}"} # type: ignore @distributed_trace def list_by_billing_account( self, billing_account_name: str, **kwargs: Any ) -> AsyncIterable["_models.BillingRoleDefinition"]: """Lists the role definitions for a billing account. The operation is supported for billing accounts with agreement type Microsoft Partner Agreement or Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either BillingRoleDefinition or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.BillingRoleDefinition] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingRoleDefinitionListResult] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_by_billing_account_request( billing_account_name=billing_account_name, api_version=api_version, template_url=self.list_by_billing_account.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore else: request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request async def extract_data(pipeline_response): deserialized = self._deserialize("BillingRoleDefinitionListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged(get_next, extract_data) list_by_billing_account.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingRoleDefinitions"} # type: ignore @distributed_trace def list_by_invoice_section( self, billing_account_name: str, billing_profile_name: str, invoice_section_name: str, **kwargs: Any ) -> AsyncIterable["_models.BillingRoleDefinition"]: """Lists the role definitions for an invoice section. The operation is supported for billing accounts with agreement type Microsoft Partner Agreement or Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :param invoice_section_name: The ID that uniquely identifies an invoice section. Required. :type invoice_section_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either BillingRoleDefinition or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.BillingRoleDefinition] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingRoleDefinitionListResult] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_by_invoice_section_request( billing_account_name=billing_account_name, billing_profile_name=billing_profile_name, invoice_section_name=invoice_section_name, api_version=api_version, template_url=self.list_by_invoice_section.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore else: request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request async def extract_data(pipeline_response): deserialized = self._deserialize("BillingRoleDefinitionListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged(get_next, extract_data) list_by_invoice_section.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoiceSections/{invoiceSectionName}/billingRoleDefinitions"} # type: ignore @distributed_trace def list_by_billing_profile( self, billing_account_name: str, billing_profile_name: str, **kwargs: Any ) -> AsyncIterable["_models.BillingRoleDefinition"]: """Lists the role definitions for a billing profile. The operation is supported for billing accounts with agreement type Microsoft Partner Agreement or Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either BillingRoleDefinition or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.BillingRoleDefinition] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingRoleDefinitionListResult] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_by_billing_profile_request( billing_account_name=billing_account_name, billing_profile_name=billing_profile_name, api_version=api_version, template_url=self.list_by_billing_profile.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore else: request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request async def extract_data(pipeline_response): deserialized = self._deserialize("BillingRoleDefinitionListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged(get_next, extract_data) list_by_billing_profile.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/billingRoleDefinitions"} # type: ignore
azure-mgmt-billing
/azure_mgmt_billing-6.1.0b1-py3-none-any.whl/azure/mgmt/billing/aio/operations/_billing_role_definitions_operations.py
_billing_role_definitions_operations.py
import sys from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, map_error, ) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models from ..._vendor import _convert_request from ...operations._billing_role_definitions_operations import ( build_get_by_billing_account_request, build_get_by_billing_profile_request, build_get_by_invoice_section_request, build_list_by_billing_account_request, build_list_by_billing_profile_request, build_list_by_invoice_section_request, ) if sys.version_info >= (3, 8): from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports else: from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] class BillingRoleDefinitionsOperations: """ .. warning:: **DO NOT** instantiate this class directly. Instead, you should access the following operations through :class:`~azure.mgmt.billing.aio.BillingManagementClient`'s :attr:`billing_role_definitions` attribute. """ models = _models def __init__(self, *args, **kwargs) -> None: input_args = list(args) self._client = input_args.pop(0) if input_args else kwargs.pop("client") self._config = input_args.pop(0) if input_args else kwargs.pop("config") self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace_async async def get_by_billing_account( self, billing_account_name: str, billing_role_definition_name: str, **kwargs: Any ) -> _models.BillingRoleDefinition: """Gets the definition for a role on a billing account. The operation is supported for billing accounts with agreement type Microsoft Partner Agreement or Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_role_definition_name: The ID that uniquely identifies a role definition. Required. :type billing_role_definition_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: BillingRoleDefinition or the result of cls(response) :rtype: ~azure.mgmt.billing.models.BillingRoleDefinition :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingRoleDefinition] request = build_get_by_billing_account_request( billing_account_name=billing_account_name, billing_role_definition_name=billing_role_definition_name, api_version=api_version, template_url=self.get_by_billing_account.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize("BillingRoleDefinition", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get_by_billing_account.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingRoleDefinitions/{billingRoleDefinitionName}"} # type: ignore @distributed_trace_async async def get_by_invoice_section( self, billing_account_name: str, billing_profile_name: str, invoice_section_name: str, billing_role_definition_name: str, **kwargs: Any ) -> _models.BillingRoleDefinition: """Gets the definition for a role on an invoice section. The operation is supported only for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :param invoice_section_name: The ID that uniquely identifies an invoice section. Required. :type invoice_section_name: str :param billing_role_definition_name: The ID that uniquely identifies a role definition. Required. :type billing_role_definition_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: BillingRoleDefinition or the result of cls(response) :rtype: ~azure.mgmt.billing.models.BillingRoleDefinition :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingRoleDefinition] request = build_get_by_invoice_section_request( billing_account_name=billing_account_name, billing_profile_name=billing_profile_name, invoice_section_name=invoice_section_name, billing_role_definition_name=billing_role_definition_name, api_version=api_version, template_url=self.get_by_invoice_section.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize("BillingRoleDefinition", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get_by_invoice_section.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoiceSections/{invoiceSectionName}/billingRoleDefinitions/{billingRoleDefinitionName}"} # type: ignore @distributed_trace_async async def get_by_billing_profile( self, billing_account_name: str, billing_profile_name: str, billing_role_definition_name: str, **kwargs: Any ) -> _models.BillingRoleDefinition: """Gets the definition for a role on a billing profile. The operation is supported for billing accounts with agreement type Microsoft Partner Agreement or Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :param billing_role_definition_name: The ID that uniquely identifies a role definition. Required. :type billing_role_definition_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: BillingRoleDefinition or the result of cls(response) :rtype: ~azure.mgmt.billing.models.BillingRoleDefinition :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingRoleDefinition] request = build_get_by_billing_profile_request( billing_account_name=billing_account_name, billing_profile_name=billing_profile_name, billing_role_definition_name=billing_role_definition_name, api_version=api_version, template_url=self.get_by_billing_profile.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize("BillingRoleDefinition", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get_by_billing_profile.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/billingRoleDefinitions/{billingRoleDefinitionName}"} # type: ignore @distributed_trace def list_by_billing_account( self, billing_account_name: str, **kwargs: Any ) -> AsyncIterable["_models.BillingRoleDefinition"]: """Lists the role definitions for a billing account. The operation is supported for billing accounts with agreement type Microsoft Partner Agreement or Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either BillingRoleDefinition or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.BillingRoleDefinition] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingRoleDefinitionListResult] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_by_billing_account_request( billing_account_name=billing_account_name, api_version=api_version, template_url=self.list_by_billing_account.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore else: request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request async def extract_data(pipeline_response): deserialized = self._deserialize("BillingRoleDefinitionListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged(get_next, extract_data) list_by_billing_account.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingRoleDefinitions"} # type: ignore @distributed_trace def list_by_invoice_section( self, billing_account_name: str, billing_profile_name: str, invoice_section_name: str, **kwargs: Any ) -> AsyncIterable["_models.BillingRoleDefinition"]: """Lists the role definitions for an invoice section. The operation is supported for billing accounts with agreement type Microsoft Partner Agreement or Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :param invoice_section_name: The ID that uniquely identifies an invoice section. Required. :type invoice_section_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either BillingRoleDefinition or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.BillingRoleDefinition] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingRoleDefinitionListResult] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_by_invoice_section_request( billing_account_name=billing_account_name, billing_profile_name=billing_profile_name, invoice_section_name=invoice_section_name, api_version=api_version, template_url=self.list_by_invoice_section.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore else: request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request async def extract_data(pipeline_response): deserialized = self._deserialize("BillingRoleDefinitionListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged(get_next, extract_data) list_by_invoice_section.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoiceSections/{invoiceSectionName}/billingRoleDefinitions"} # type: ignore @distributed_trace def list_by_billing_profile( self, billing_account_name: str, billing_profile_name: str, **kwargs: Any ) -> AsyncIterable["_models.BillingRoleDefinition"]: """Lists the role definitions for a billing profile. The operation is supported for billing accounts with agreement type Microsoft Partner Agreement or Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either BillingRoleDefinition or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.BillingRoleDefinition] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingRoleDefinitionListResult] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_by_billing_profile_request( billing_account_name=billing_account_name, billing_profile_name=billing_profile_name, api_version=api_version, template_url=self.list_by_billing_profile.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore else: request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request async def extract_data(pipeline_response): deserialized = self._deserialize("BillingRoleDefinitionListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged(get_next, extract_data) list_by_billing_profile.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/billingRoleDefinitions"} # type: ignore
0.672977
0.089654
import sys from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, map_error, ) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models from ..._vendor import _convert_request from ...operations._transactions_operations import build_list_by_invoice_request if sys.version_info >= (3, 8): from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports else: from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] class TransactionsOperations: """ .. warning:: **DO NOT** instantiate this class directly. Instead, you should access the following operations through :class:`~azure.mgmt.billing.aio.BillingManagementClient`'s :attr:`transactions` attribute. """ models = _models def __init__(self, *args, **kwargs) -> None: input_args = list(args) self._client = input_args.pop(0) if input_args else kwargs.pop("client") self._config = input_args.pop(0) if input_args else kwargs.pop("config") self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace def list_by_invoice( self, billing_account_name: str, invoice_name: str, **kwargs: Any ) -> AsyncIterable["_models.Transaction"]: """Lists the transactions for an invoice. Transactions include purchases, refunds and Azure usage charges. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param invoice_name: The ID that uniquely identifies an invoice. Required. :type invoice_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either Transaction or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.Transaction] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.TransactionListResult] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_by_invoice_request( billing_account_name=billing_account_name, invoice_name=invoice_name, api_version=api_version, template_url=self.list_by_invoice.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore else: request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request async def extract_data(pipeline_response): deserialized = self._deserialize("TransactionListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged(get_next, extract_data) list_by_invoice.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/invoices/{invoiceName}/transactions"} # type: ignore
azure-mgmt-billing
/azure_mgmt_billing-6.1.0b1-py3-none-any.whl/azure/mgmt/billing/aio/operations/_transactions_operations.py
_transactions_operations.py
import sys from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, map_error, ) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models from ..._vendor import _convert_request from ...operations._transactions_operations import build_list_by_invoice_request if sys.version_info >= (3, 8): from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports else: from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] class TransactionsOperations: """ .. warning:: **DO NOT** instantiate this class directly. Instead, you should access the following operations through :class:`~azure.mgmt.billing.aio.BillingManagementClient`'s :attr:`transactions` attribute. """ models = _models def __init__(self, *args, **kwargs) -> None: input_args = list(args) self._client = input_args.pop(0) if input_args else kwargs.pop("client") self._config = input_args.pop(0) if input_args else kwargs.pop("config") self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace def list_by_invoice( self, billing_account_name: str, invoice_name: str, **kwargs: Any ) -> AsyncIterable["_models.Transaction"]: """Lists the transactions for an invoice. Transactions include purchases, refunds and Azure usage charges. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param invoice_name: The ID that uniquely identifies an invoice. Required. :type invoice_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either Transaction or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.Transaction] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.TransactionListResult] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_by_invoice_request( billing_account_name=billing_account_name, invoice_name=invoice_name, api_version=api_version, template_url=self.list_by_invoice.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore else: request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request async def extract_data(pipeline_response): deserialized = self._deserialize("TransactionListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged(get_next, extract_data) list_by_invoice.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/invoices/{invoiceName}/transactions"} # type: ignore
0.632843
0.092565
import sys from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, map_error, ) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling from ... import models as _models from ..._vendor import _convert_request from ...operations._billing_subscriptions_operations import ( build_get_request, build_list_by_billing_account_request, build_list_by_billing_profile_request, build_list_by_customer_request, build_list_by_invoice_section_request, build_move_request, build_update_request, build_validate_move_request, ) if sys.version_info >= (3, 8): from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports else: from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] class BillingSubscriptionsOperations: """ .. warning:: **DO NOT** instantiate this class directly. Instead, you should access the following operations through :class:`~azure.mgmt.billing.aio.BillingManagementClient`'s :attr:`billing_subscriptions` attribute. """ models = _models def __init__(self, *args, **kwargs) -> None: input_args = list(args) self._client = input_args.pop(0) if input_args else kwargs.pop("client") self._config = input_args.pop(0) if input_args else kwargs.pop("config") self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace def list_by_customer( self, billing_account_name: str, customer_name: str, **kwargs: Any ) -> AsyncIterable["_models.BillingSubscription"]: """Lists the subscriptions for a customer. The operation is supported only for billing accounts with agreement type Microsoft Partner Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param customer_name: The ID that uniquely identifies a customer. Required. :type customer_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either BillingSubscription or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.BillingSubscription] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingSubscriptionsListResult] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_by_customer_request( billing_account_name=billing_account_name, customer_name=customer_name, api_version=api_version, template_url=self.list_by_customer.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore else: request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request async def extract_data(pipeline_response): deserialized = self._deserialize("BillingSubscriptionsListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged(get_next, extract_data) list_by_customer.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/customers/{customerName}/billingSubscriptions"} # type: ignore @distributed_trace def list_by_billing_account( self, billing_account_name: str, **kwargs: Any ) -> AsyncIterable["_models.BillingSubscription"]: """Lists the subscriptions for a billing account. The operation is supported for billing accounts with agreement type Microsoft Customer Agreement or Microsoft Partner Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either BillingSubscription or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.BillingSubscription] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingSubscriptionsListResult] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_by_billing_account_request( billing_account_name=billing_account_name, api_version=api_version, template_url=self.list_by_billing_account.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore else: request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request async def extract_data(pipeline_response): deserialized = self._deserialize("BillingSubscriptionsListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged(get_next, extract_data) list_by_billing_account.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingSubscriptions"} # type: ignore @distributed_trace def list_by_billing_profile( self, billing_account_name: str, billing_profile_name: str, **kwargs: Any ) -> AsyncIterable["_models.BillingSubscription"]: """Lists the subscriptions that are billed to a billing profile. The operation is supported for billing accounts with agreement type Microsoft Customer Agreement or Microsoft Partner Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either BillingSubscription or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.BillingSubscription] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingSubscriptionsListResult] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_by_billing_profile_request( billing_account_name=billing_account_name, billing_profile_name=billing_profile_name, api_version=api_version, template_url=self.list_by_billing_profile.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore else: request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request async def extract_data(pipeline_response): deserialized = self._deserialize("BillingSubscriptionsListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged(get_next, extract_data) list_by_billing_profile.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/billingSubscriptions"} # type: ignore @distributed_trace def list_by_invoice_section( self, billing_account_name: str, billing_profile_name: str, invoice_section_name: str, **kwargs: Any ) -> AsyncIterable["_models.BillingSubscription"]: """Lists the subscriptions that are billed to an invoice section. The operation is supported only for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :param invoice_section_name: The ID that uniquely identifies an invoice section. Required. :type invoice_section_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either BillingSubscription or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.BillingSubscription] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingSubscriptionsListResult] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_by_invoice_section_request( billing_account_name=billing_account_name, billing_profile_name=billing_profile_name, invoice_section_name=invoice_section_name, api_version=api_version, template_url=self.list_by_invoice_section.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore else: request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request async def extract_data(pipeline_response): deserialized = self._deserialize("BillingSubscriptionsListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged(get_next, extract_data) list_by_invoice_section.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoiceSections/{invoiceSectionName}/billingSubscriptions"} # type: ignore @distributed_trace_async async def get(self, billing_account_name: str, **kwargs: Any) -> _models.BillingSubscription: """Gets a subscription by its ID. The operation is supported for billing accounts with agreement type Microsoft Customer Agreement and Microsoft Partner Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: BillingSubscription or the result of cls(response) :rtype: ~azure.mgmt.billing.models.BillingSubscription :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingSubscription] request = build_get_request( billing_account_name=billing_account_name, subscription_id=self._config.subscription_id, api_version=api_version, template_url=self.get.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize("BillingSubscription", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingSubscriptions/{subscriptionId}"} # type: ignore @overload async def update( self, billing_account_name: str, parameters: _models.BillingSubscription, *, content_type: str = "application/json", **kwargs: Any ) -> _models.BillingSubscription: """Updates the properties of a billing subscription. Currently, cost center can be updated. The operation is supported only for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param parameters: Request parameters that are provided to the update billing subscription operation. Required. :type parameters: ~azure.mgmt.billing.models.BillingSubscription :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: BillingSubscription or the result of cls(response) :rtype: ~azure.mgmt.billing.models.BillingSubscription :raises ~azure.core.exceptions.HttpResponseError: """ @overload async def update( self, billing_account_name: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any ) -> _models.BillingSubscription: """Updates the properties of a billing subscription. Currently, cost center can be updated. The operation is supported only for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param parameters: Request parameters that are provided to the update billing subscription operation. Required. :type parameters: IO :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: BillingSubscription or the result of cls(response) :rtype: ~azure.mgmt.billing.models.BillingSubscription :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace_async async def update( self, billing_account_name: str, parameters: Union[_models.BillingSubscription, IO], **kwargs: Any ) -> _models.BillingSubscription: """Updates the properties of a billing subscription. Currently, cost center can be updated. The operation is supported only for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param parameters: Request parameters that are provided to the update billing subscription operation. Is either a model type or a IO type. Required. :type parameters: ~azure.mgmt.billing.models.BillingSubscription or IO :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. Default value is None. :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: BillingSubscription or the result of cls(response) :rtype: ~azure.mgmt.billing.models.BillingSubscription :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingSubscription] content_type = content_type or "application/json" _json = None _content = None if isinstance(parameters, (IO, bytes)): _content = parameters else: _json = self._serialize.body(parameters, "BillingSubscription") request = build_update_request( billing_account_name=billing_account_name, subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, content=_content, template_url=self.update.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize("BillingSubscription", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized update.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingSubscriptions/{subscriptionId}"} # type: ignore async def _move_initial( self, billing_account_name: str, parameters: Union[_models.TransferBillingSubscriptionRequestProperties, IO], **kwargs: Any ) -> Optional[_models.BillingSubscription]: error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.BillingSubscription]] content_type = content_type or "application/json" _json = None _content = None if isinstance(parameters, (IO, bytes)): _content = parameters else: _json = self._serialize.body(parameters, "TransferBillingSubscriptionRequestProperties") request = build_move_request( billing_account_name=billing_account_name, subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, content=_content, template_url=self._move_initial.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = None response_headers = {} if response.status_code == 200: deserialized = self._deserialize("BillingSubscription", pipeline_response) if response.status_code == 202: response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) if cls: return cls(pipeline_response, deserialized, response_headers) return deserialized _move_initial.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingSubscriptions/{subscriptionId}/move"} # type: ignore @overload async def begin_move( self, billing_account_name: str, parameters: _models.TransferBillingSubscriptionRequestProperties, *, content_type: str = "application/json", **kwargs: Any ) -> AsyncLROPoller[_models.BillingSubscription]: """Moves a subscription's charges to a new invoice section. The new invoice section must belong to the same billing profile as the existing invoice section. This operation is supported for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param parameters: Request parameters that are provided to the move subscription operation. Required. :type parameters: ~azure.mgmt.billing.models.TransferBillingSubscriptionRequestProperties :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of AsyncLROPoller that returns either BillingSubscription or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.BillingSubscription] :raises ~azure.core.exceptions.HttpResponseError: """ @overload async def begin_move( self, billing_account_name: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any ) -> AsyncLROPoller[_models.BillingSubscription]: """Moves a subscription's charges to a new invoice section. The new invoice section must belong to the same billing profile as the existing invoice section. This operation is supported for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param parameters: Request parameters that are provided to the move subscription operation. Required. :type parameters: IO :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of AsyncLROPoller that returns either BillingSubscription or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.BillingSubscription] :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace_async async def begin_move( self, billing_account_name: str, parameters: Union[_models.TransferBillingSubscriptionRequestProperties, IO], **kwargs: Any ) -> AsyncLROPoller[_models.BillingSubscription]: """Moves a subscription's charges to a new invoice section. The new invoice section must belong to the same billing profile as the existing invoice section. This operation is supported for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param parameters: Request parameters that are provided to the move subscription operation. Is either a model type or a IO type. Required. :type parameters: ~azure.mgmt.billing.models.TransferBillingSubscriptionRequestProperties or IO :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. Default value is None. :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of AsyncLROPoller that returns either BillingSubscription or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.BillingSubscription] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingSubscription] polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod] lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: raw_result = await self._move_initial( # type: ignore billing_account_name=billing_account_name, parameters=parameters, api_version=api_version, content_type=content_type, cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): deserialized = self._deserialize("BillingSubscription", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized if polling is True: polling_method = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) # type: AsyncPollingMethod elif polling is False: polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) else: polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_move.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingSubscriptions/{subscriptionId}/move"} # type: ignore @overload async def validate_move( self, billing_account_name: str, parameters: _models.TransferBillingSubscriptionRequestProperties, *, content_type: str = "application/json", **kwargs: Any ) -> _models.ValidateSubscriptionTransferEligibilityResult: """Validates if a subscription's charges can be moved to a new invoice section. This operation is supported for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param parameters: Request parameters that are provided to the validate move eligibility operation. Required. :type parameters: ~azure.mgmt.billing.models.TransferBillingSubscriptionRequestProperties :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: ValidateSubscriptionTransferEligibilityResult or the result of cls(response) :rtype: ~azure.mgmt.billing.models.ValidateSubscriptionTransferEligibilityResult :raises ~azure.core.exceptions.HttpResponseError: """ @overload async def validate_move( self, billing_account_name: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any ) -> _models.ValidateSubscriptionTransferEligibilityResult: """Validates if a subscription's charges can be moved to a new invoice section. This operation is supported for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param parameters: Request parameters that are provided to the validate move eligibility operation. Required. :type parameters: IO :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: ValidateSubscriptionTransferEligibilityResult or the result of cls(response) :rtype: ~azure.mgmt.billing.models.ValidateSubscriptionTransferEligibilityResult :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace_async async def validate_move( self, billing_account_name: str, parameters: Union[_models.TransferBillingSubscriptionRequestProperties, IO], **kwargs: Any ) -> _models.ValidateSubscriptionTransferEligibilityResult: """Validates if a subscription's charges can be moved to a new invoice section. This operation is supported for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param parameters: Request parameters that are provided to the validate move eligibility operation. Is either a model type or a IO type. Required. :type parameters: ~azure.mgmt.billing.models.TransferBillingSubscriptionRequestProperties or IO :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. Default value is None. :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: ValidateSubscriptionTransferEligibilityResult or the result of cls(response) :rtype: ~azure.mgmt.billing.models.ValidateSubscriptionTransferEligibilityResult :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] cls = kwargs.pop("cls", None) # type: ClsType[_models.ValidateSubscriptionTransferEligibilityResult] content_type = content_type or "application/json" _json = None _content = None if isinstance(parameters, (IO, bytes)): _content = parameters else: _json = self._serialize.body(parameters, "TransferBillingSubscriptionRequestProperties") request = build_validate_move_request( billing_account_name=billing_account_name, subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, content=_content, template_url=self.validate_move.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize("ValidateSubscriptionTransferEligibilityResult", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized validate_move.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingSubscriptions/{subscriptionId}/validateMoveEligibility"} # type: ignore
azure-mgmt-billing
/azure_mgmt_billing-6.1.0b1-py3-none-any.whl/azure/mgmt/billing/aio/operations/_billing_subscriptions_operations.py
_billing_subscriptions_operations.py
import sys from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, map_error, ) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling from ... import models as _models from ..._vendor import _convert_request from ...operations._billing_subscriptions_operations import ( build_get_request, build_list_by_billing_account_request, build_list_by_billing_profile_request, build_list_by_customer_request, build_list_by_invoice_section_request, build_move_request, build_update_request, build_validate_move_request, ) if sys.version_info >= (3, 8): from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports else: from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] class BillingSubscriptionsOperations: """ .. warning:: **DO NOT** instantiate this class directly. Instead, you should access the following operations through :class:`~azure.mgmt.billing.aio.BillingManagementClient`'s :attr:`billing_subscriptions` attribute. """ models = _models def __init__(self, *args, **kwargs) -> None: input_args = list(args) self._client = input_args.pop(0) if input_args else kwargs.pop("client") self._config = input_args.pop(0) if input_args else kwargs.pop("config") self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace def list_by_customer( self, billing_account_name: str, customer_name: str, **kwargs: Any ) -> AsyncIterable["_models.BillingSubscription"]: """Lists the subscriptions for a customer. The operation is supported only for billing accounts with agreement type Microsoft Partner Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param customer_name: The ID that uniquely identifies a customer. Required. :type customer_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either BillingSubscription or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.BillingSubscription] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingSubscriptionsListResult] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_by_customer_request( billing_account_name=billing_account_name, customer_name=customer_name, api_version=api_version, template_url=self.list_by_customer.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore else: request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request async def extract_data(pipeline_response): deserialized = self._deserialize("BillingSubscriptionsListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged(get_next, extract_data) list_by_customer.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/customers/{customerName}/billingSubscriptions"} # type: ignore @distributed_trace def list_by_billing_account( self, billing_account_name: str, **kwargs: Any ) -> AsyncIterable["_models.BillingSubscription"]: """Lists the subscriptions for a billing account. The operation is supported for billing accounts with agreement type Microsoft Customer Agreement or Microsoft Partner Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either BillingSubscription or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.BillingSubscription] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingSubscriptionsListResult] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_by_billing_account_request( billing_account_name=billing_account_name, api_version=api_version, template_url=self.list_by_billing_account.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore else: request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request async def extract_data(pipeline_response): deserialized = self._deserialize("BillingSubscriptionsListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged(get_next, extract_data) list_by_billing_account.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingSubscriptions"} # type: ignore @distributed_trace def list_by_billing_profile( self, billing_account_name: str, billing_profile_name: str, **kwargs: Any ) -> AsyncIterable["_models.BillingSubscription"]: """Lists the subscriptions that are billed to a billing profile. The operation is supported for billing accounts with agreement type Microsoft Customer Agreement or Microsoft Partner Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either BillingSubscription or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.BillingSubscription] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingSubscriptionsListResult] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_by_billing_profile_request( billing_account_name=billing_account_name, billing_profile_name=billing_profile_name, api_version=api_version, template_url=self.list_by_billing_profile.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore else: request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request async def extract_data(pipeline_response): deserialized = self._deserialize("BillingSubscriptionsListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged(get_next, extract_data) list_by_billing_profile.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/billingSubscriptions"} # type: ignore @distributed_trace def list_by_invoice_section( self, billing_account_name: str, billing_profile_name: str, invoice_section_name: str, **kwargs: Any ) -> AsyncIterable["_models.BillingSubscription"]: """Lists the subscriptions that are billed to an invoice section. The operation is supported only for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :param invoice_section_name: The ID that uniquely identifies an invoice section. Required. :type invoice_section_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either BillingSubscription or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.BillingSubscription] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingSubscriptionsListResult] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_by_invoice_section_request( billing_account_name=billing_account_name, billing_profile_name=billing_profile_name, invoice_section_name=invoice_section_name, api_version=api_version, template_url=self.list_by_invoice_section.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore else: request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request async def extract_data(pipeline_response): deserialized = self._deserialize("BillingSubscriptionsListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged(get_next, extract_data) list_by_invoice_section.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoiceSections/{invoiceSectionName}/billingSubscriptions"} # type: ignore @distributed_trace_async async def get(self, billing_account_name: str, **kwargs: Any) -> _models.BillingSubscription: """Gets a subscription by its ID. The operation is supported for billing accounts with agreement type Microsoft Customer Agreement and Microsoft Partner Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: BillingSubscription or the result of cls(response) :rtype: ~azure.mgmt.billing.models.BillingSubscription :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingSubscription] request = build_get_request( billing_account_name=billing_account_name, subscription_id=self._config.subscription_id, api_version=api_version, template_url=self.get.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize("BillingSubscription", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingSubscriptions/{subscriptionId}"} # type: ignore @overload async def update( self, billing_account_name: str, parameters: _models.BillingSubscription, *, content_type: str = "application/json", **kwargs: Any ) -> _models.BillingSubscription: """Updates the properties of a billing subscription. Currently, cost center can be updated. The operation is supported only for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param parameters: Request parameters that are provided to the update billing subscription operation. Required. :type parameters: ~azure.mgmt.billing.models.BillingSubscription :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: BillingSubscription or the result of cls(response) :rtype: ~azure.mgmt.billing.models.BillingSubscription :raises ~azure.core.exceptions.HttpResponseError: """ @overload async def update( self, billing_account_name: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any ) -> _models.BillingSubscription: """Updates the properties of a billing subscription. Currently, cost center can be updated. The operation is supported only for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param parameters: Request parameters that are provided to the update billing subscription operation. Required. :type parameters: IO :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: BillingSubscription or the result of cls(response) :rtype: ~azure.mgmt.billing.models.BillingSubscription :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace_async async def update( self, billing_account_name: str, parameters: Union[_models.BillingSubscription, IO], **kwargs: Any ) -> _models.BillingSubscription: """Updates the properties of a billing subscription. Currently, cost center can be updated. The operation is supported only for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param parameters: Request parameters that are provided to the update billing subscription operation. Is either a model type or a IO type. Required. :type parameters: ~azure.mgmt.billing.models.BillingSubscription or IO :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. Default value is None. :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: BillingSubscription or the result of cls(response) :rtype: ~azure.mgmt.billing.models.BillingSubscription :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingSubscription] content_type = content_type or "application/json" _json = None _content = None if isinstance(parameters, (IO, bytes)): _content = parameters else: _json = self._serialize.body(parameters, "BillingSubscription") request = build_update_request( billing_account_name=billing_account_name, subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, content=_content, template_url=self.update.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize("BillingSubscription", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized update.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingSubscriptions/{subscriptionId}"} # type: ignore async def _move_initial( self, billing_account_name: str, parameters: Union[_models.TransferBillingSubscriptionRequestProperties, IO], **kwargs: Any ) -> Optional[_models.BillingSubscription]: error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.BillingSubscription]] content_type = content_type or "application/json" _json = None _content = None if isinstance(parameters, (IO, bytes)): _content = parameters else: _json = self._serialize.body(parameters, "TransferBillingSubscriptionRequestProperties") request = build_move_request( billing_account_name=billing_account_name, subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, content=_content, template_url=self._move_initial.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = None response_headers = {} if response.status_code == 200: deserialized = self._deserialize("BillingSubscription", pipeline_response) if response.status_code == 202: response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) if cls: return cls(pipeline_response, deserialized, response_headers) return deserialized _move_initial.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingSubscriptions/{subscriptionId}/move"} # type: ignore @overload async def begin_move( self, billing_account_name: str, parameters: _models.TransferBillingSubscriptionRequestProperties, *, content_type: str = "application/json", **kwargs: Any ) -> AsyncLROPoller[_models.BillingSubscription]: """Moves a subscription's charges to a new invoice section. The new invoice section must belong to the same billing profile as the existing invoice section. This operation is supported for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param parameters: Request parameters that are provided to the move subscription operation. Required. :type parameters: ~azure.mgmt.billing.models.TransferBillingSubscriptionRequestProperties :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of AsyncLROPoller that returns either BillingSubscription or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.BillingSubscription] :raises ~azure.core.exceptions.HttpResponseError: """ @overload async def begin_move( self, billing_account_name: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any ) -> AsyncLROPoller[_models.BillingSubscription]: """Moves a subscription's charges to a new invoice section. The new invoice section must belong to the same billing profile as the existing invoice section. This operation is supported for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param parameters: Request parameters that are provided to the move subscription operation. Required. :type parameters: IO :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of AsyncLROPoller that returns either BillingSubscription or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.BillingSubscription] :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace_async async def begin_move( self, billing_account_name: str, parameters: Union[_models.TransferBillingSubscriptionRequestProperties, IO], **kwargs: Any ) -> AsyncLROPoller[_models.BillingSubscription]: """Moves a subscription's charges to a new invoice section. The new invoice section must belong to the same billing profile as the existing invoice section. This operation is supported for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param parameters: Request parameters that are provided to the move subscription operation. Is either a model type or a IO type. Required. :type parameters: ~azure.mgmt.billing.models.TransferBillingSubscriptionRequestProperties or IO :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. Default value is None. :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of AsyncLROPoller that returns either BillingSubscription or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.BillingSubscription] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingSubscription] polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod] lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: raw_result = await self._move_initial( # type: ignore billing_account_name=billing_account_name, parameters=parameters, api_version=api_version, content_type=content_type, cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): deserialized = self._deserialize("BillingSubscription", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized if polling is True: polling_method = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) # type: AsyncPollingMethod elif polling is False: polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) else: polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_move.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingSubscriptions/{subscriptionId}/move"} # type: ignore @overload async def validate_move( self, billing_account_name: str, parameters: _models.TransferBillingSubscriptionRequestProperties, *, content_type: str = "application/json", **kwargs: Any ) -> _models.ValidateSubscriptionTransferEligibilityResult: """Validates if a subscription's charges can be moved to a new invoice section. This operation is supported for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param parameters: Request parameters that are provided to the validate move eligibility operation. Required. :type parameters: ~azure.mgmt.billing.models.TransferBillingSubscriptionRequestProperties :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: ValidateSubscriptionTransferEligibilityResult or the result of cls(response) :rtype: ~azure.mgmt.billing.models.ValidateSubscriptionTransferEligibilityResult :raises ~azure.core.exceptions.HttpResponseError: """ @overload async def validate_move( self, billing_account_name: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any ) -> _models.ValidateSubscriptionTransferEligibilityResult: """Validates if a subscription's charges can be moved to a new invoice section. This operation is supported for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param parameters: Request parameters that are provided to the validate move eligibility operation. Required. :type parameters: IO :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: ValidateSubscriptionTransferEligibilityResult or the result of cls(response) :rtype: ~azure.mgmt.billing.models.ValidateSubscriptionTransferEligibilityResult :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace_async async def validate_move( self, billing_account_name: str, parameters: Union[_models.TransferBillingSubscriptionRequestProperties, IO], **kwargs: Any ) -> _models.ValidateSubscriptionTransferEligibilityResult: """Validates if a subscription's charges can be moved to a new invoice section. This operation is supported for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param parameters: Request parameters that are provided to the validate move eligibility operation. Is either a model type or a IO type. Required. :type parameters: ~azure.mgmt.billing.models.TransferBillingSubscriptionRequestProperties or IO :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. Default value is None. :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: ValidateSubscriptionTransferEligibilityResult or the result of cls(response) :rtype: ~azure.mgmt.billing.models.ValidateSubscriptionTransferEligibilityResult :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] cls = kwargs.pop("cls", None) # type: ClsType[_models.ValidateSubscriptionTransferEligibilityResult] content_type = content_type or "application/json" _json = None _content = None if isinstance(parameters, (IO, bytes)): _content = parameters else: _json = self._serialize.body(parameters, "TransferBillingSubscriptionRequestProperties") request = build_validate_move_request( billing_account_name=billing_account_name, subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, content=_content, template_url=self.validate_move.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize("ValidateSubscriptionTransferEligibilityResult", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized validate_move.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingSubscriptions/{subscriptionId}/validateMoveEligibility"} # type: ignore
0.672224
0.082365
import sys from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, map_error, ) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models from ..._vendor import _convert_request from ...operations._reservations_operations import ( build_list_by_billing_account_request, build_list_by_billing_profile_request, ) if sys.version_info >= (3, 8): from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports else: from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] class ReservationsOperations: """ .. warning:: **DO NOT** instantiate this class directly. Instead, you should access the following operations through :class:`~azure.mgmt.billing.aio.BillingManagementClient`'s :attr:`reservations` attribute. """ models = _models def __init__(self, *args, **kwargs) -> None: input_args = list(args) self._client = input_args.pop(0) if input_args else kwargs.pop("client") self._config = input_args.pop(0) if input_args else kwargs.pop("config") self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace def list_by_billing_account( self, billing_account_name: str, filter: Optional[str] = None, orderby: Optional[str] = None, refresh_summary: Optional[str] = None, selected_state: Optional[str] = None, **kwargs: Any ) -> AsyncIterable["_models.Reservation"]: """Lists the reservations for a billing account and the roll up counts of reservations group by provisioning states. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param filter: May be used to filter by reservation properties. The filter supports 'eq', 'or', and 'and'. It does not currently support 'ne', 'gt', 'le', 'ge', or 'not'. Default value is None. :type filter: str :param orderby: May be used to sort order by reservation properties. Default value is None. :type orderby: str :param refresh_summary: To indicate whether to refresh the roll up counts of the reservations group by provisioning states. Default value is None. :type refresh_summary: str :param selected_state: The selected provisioning state. Default value is None. :type selected_state: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either Reservation or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.Reservation] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.ReservationsListResult] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_by_billing_account_request( billing_account_name=billing_account_name, filter=filter, orderby=orderby, refresh_summary=refresh_summary, selected_state=selected_state, api_version=api_version, template_url=self.list_by_billing_account.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore else: request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request async def extract_data(pipeline_response): deserialized = self._deserialize("ReservationsListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged(get_next, extract_data) list_by_billing_account.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/reservations"} # type: ignore @distributed_trace def list_by_billing_profile( self, billing_account_name: str, billing_profile_name: str, filter: Optional[str] = None, orderby: Optional[str] = None, refresh_summary: Optional[str] = None, selected_state: Optional[str] = None, **kwargs: Any ) -> AsyncIterable["_models.Reservation"]: """Lists the reservations for a billing profile and the roll up counts of reservations group by provisioning state. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :param filter: May be used to filter by reservation properties. The filter supports 'eq', 'or', and 'and'. It does not currently support 'ne', 'gt', 'le', 'ge', or 'not'. Default value is None. :type filter: str :param orderby: May be used to sort order by reservation properties. Default value is None. :type orderby: str :param refresh_summary: To indicate whether to refresh the roll up counts of the reservations group by provisioning state. Default value is None. :type refresh_summary: str :param selected_state: The selected provisioning state. Default value is None. :type selected_state: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either Reservation or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.Reservation] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.ReservationsListResult] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_by_billing_profile_request( billing_account_name=billing_account_name, billing_profile_name=billing_profile_name, filter=filter, orderby=orderby, refresh_summary=refresh_summary, selected_state=selected_state, api_version=api_version, template_url=self.list_by_billing_profile.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore else: request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request async def extract_data(pipeline_response): deserialized = self._deserialize("ReservationsListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged(get_next, extract_data) list_by_billing_profile.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/reservations"} # type: ignore
azure-mgmt-billing
/azure_mgmt_billing-6.1.0b1-py3-none-any.whl/azure/mgmt/billing/aio/operations/_reservations_operations.py
_reservations_operations.py
import sys from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, map_error, ) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models from ..._vendor import _convert_request from ...operations._reservations_operations import ( build_list_by_billing_account_request, build_list_by_billing_profile_request, ) if sys.version_info >= (3, 8): from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports else: from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] class ReservationsOperations: """ .. warning:: **DO NOT** instantiate this class directly. Instead, you should access the following operations through :class:`~azure.mgmt.billing.aio.BillingManagementClient`'s :attr:`reservations` attribute. """ models = _models def __init__(self, *args, **kwargs) -> None: input_args = list(args) self._client = input_args.pop(0) if input_args else kwargs.pop("client") self._config = input_args.pop(0) if input_args else kwargs.pop("config") self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace def list_by_billing_account( self, billing_account_name: str, filter: Optional[str] = None, orderby: Optional[str] = None, refresh_summary: Optional[str] = None, selected_state: Optional[str] = None, **kwargs: Any ) -> AsyncIterable["_models.Reservation"]: """Lists the reservations for a billing account and the roll up counts of reservations group by provisioning states. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param filter: May be used to filter by reservation properties. The filter supports 'eq', 'or', and 'and'. It does not currently support 'ne', 'gt', 'le', 'ge', or 'not'. Default value is None. :type filter: str :param orderby: May be used to sort order by reservation properties. Default value is None. :type orderby: str :param refresh_summary: To indicate whether to refresh the roll up counts of the reservations group by provisioning states. Default value is None. :type refresh_summary: str :param selected_state: The selected provisioning state. Default value is None. :type selected_state: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either Reservation or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.Reservation] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.ReservationsListResult] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_by_billing_account_request( billing_account_name=billing_account_name, filter=filter, orderby=orderby, refresh_summary=refresh_summary, selected_state=selected_state, api_version=api_version, template_url=self.list_by_billing_account.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore else: request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request async def extract_data(pipeline_response): deserialized = self._deserialize("ReservationsListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged(get_next, extract_data) list_by_billing_account.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/reservations"} # type: ignore @distributed_trace def list_by_billing_profile( self, billing_account_name: str, billing_profile_name: str, filter: Optional[str] = None, orderby: Optional[str] = None, refresh_summary: Optional[str] = None, selected_state: Optional[str] = None, **kwargs: Any ) -> AsyncIterable["_models.Reservation"]: """Lists the reservations for a billing profile and the roll up counts of reservations group by provisioning state. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :param filter: May be used to filter by reservation properties. The filter supports 'eq', 'or', and 'and'. It does not currently support 'ne', 'gt', 'le', 'ge', or 'not'. Default value is None. :type filter: str :param orderby: May be used to sort order by reservation properties. Default value is None. :type orderby: str :param refresh_summary: To indicate whether to refresh the roll up counts of the reservations group by provisioning state. Default value is None. :type refresh_summary: str :param selected_state: The selected provisioning state. Default value is None. :type selected_state: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either Reservation or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.Reservation] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.ReservationsListResult] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_by_billing_profile_request( billing_account_name=billing_account_name, billing_profile_name=billing_profile_name, filter=filter, orderby=orderby, refresh_summary=refresh_summary, selected_state=selected_state, api_version=api_version, template_url=self.list_by_billing_profile.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore else: request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request async def extract_data(pipeline_response): deserialized = self._deserialize("ReservationsListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged(get_next, extract_data) list_by_billing_profile.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/reservations"} # type: ignore
0.709824
0.118385
import sys from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, overload from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, map_error, ) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.rest import HttpRequest from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models from ..._vendor import _convert_request from ...operations._billing_property_operations import build_get_request, build_update_request if sys.version_info >= (3, 8): from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports else: from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] class BillingPropertyOperations: """ .. warning:: **DO NOT** instantiate this class directly. Instead, you should access the following operations through :class:`~azure.mgmt.billing.aio.BillingManagementClient`'s :attr:`billing_property` attribute. """ models = _models def __init__(self, *args, **kwargs) -> None: input_args = list(args) self._client = input_args.pop(0) if input_args else kwargs.pop("client") self._config = input_args.pop(0) if input_args else kwargs.pop("config") self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace_async async def get(self, **kwargs: Any) -> _models.BillingProperty: """Get the billing properties for a subscription. This operation is not supported for billing accounts with agreement type Enterprise Agreement. :keyword callable cls: A custom type or function that will be passed the direct response :return: BillingProperty or the result of cls(response) :rtype: ~azure.mgmt.billing.models.BillingProperty :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingProperty] request = build_get_request( subscription_id=self._config.subscription_id, api_version=api_version, template_url=self.get.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize("BillingProperty", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Billing/billingProperty/default"} # type: ignore @overload async def update( self, parameters: _models.BillingProperty, *, content_type: str = "application/json", **kwargs: Any ) -> _models.BillingProperty: """Updates the billing property of a subscription. Currently, cost center can be updated. The operation is supported only for billing accounts with agreement type Microsoft Customer Agreement. :param parameters: Request parameters that are provided to the update billing property operation. Required. :type parameters: ~azure.mgmt.billing.models.BillingProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: BillingProperty or the result of cls(response) :rtype: ~azure.mgmt.billing.models.BillingProperty :raises ~azure.core.exceptions.HttpResponseError: """ @overload async def update( self, parameters: IO, *, content_type: str = "application/json", **kwargs: Any ) -> _models.BillingProperty: """Updates the billing property of a subscription. Currently, cost center can be updated. The operation is supported only for billing accounts with agreement type Microsoft Customer Agreement. :param parameters: Request parameters that are provided to the update billing property operation. Required. :type parameters: IO :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: BillingProperty or the result of cls(response) :rtype: ~azure.mgmt.billing.models.BillingProperty :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace_async async def update(self, parameters: Union[_models.BillingProperty, IO], **kwargs: Any) -> _models.BillingProperty: """Updates the billing property of a subscription. Currently, cost center can be updated. The operation is supported only for billing accounts with agreement type Microsoft Customer Agreement. :param parameters: Request parameters that are provided to the update billing property operation. Is either a model type or a IO type. Required. :type parameters: ~azure.mgmt.billing.models.BillingProperty or IO :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. Default value is None. :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: BillingProperty or the result of cls(response) :rtype: ~azure.mgmt.billing.models.BillingProperty :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingProperty] content_type = content_type or "application/json" _json = None _content = None if isinstance(parameters, (IO, bytes)): _content = parameters else: _json = self._serialize.body(parameters, "BillingProperty") request = build_update_request( subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, content=_content, template_url=self.update.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize("BillingProperty", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized update.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Billing/billingProperty/default"} # type: ignore
azure-mgmt-billing
/azure_mgmt_billing-6.1.0b1-py3-none-any.whl/azure/mgmt/billing/aio/operations/_billing_property_operations.py
_billing_property_operations.py
import sys from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, overload from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, map_error, ) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.rest import HttpRequest from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models from ..._vendor import _convert_request from ...operations._billing_property_operations import build_get_request, build_update_request if sys.version_info >= (3, 8): from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports else: from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] class BillingPropertyOperations: """ .. warning:: **DO NOT** instantiate this class directly. Instead, you should access the following operations through :class:`~azure.mgmt.billing.aio.BillingManagementClient`'s :attr:`billing_property` attribute. """ models = _models def __init__(self, *args, **kwargs) -> None: input_args = list(args) self._client = input_args.pop(0) if input_args else kwargs.pop("client") self._config = input_args.pop(0) if input_args else kwargs.pop("config") self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace_async async def get(self, **kwargs: Any) -> _models.BillingProperty: """Get the billing properties for a subscription. This operation is not supported for billing accounts with agreement type Enterprise Agreement. :keyword callable cls: A custom type or function that will be passed the direct response :return: BillingProperty or the result of cls(response) :rtype: ~azure.mgmt.billing.models.BillingProperty :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingProperty] request = build_get_request( subscription_id=self._config.subscription_id, api_version=api_version, template_url=self.get.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize("BillingProperty", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Billing/billingProperty/default"} # type: ignore @overload async def update( self, parameters: _models.BillingProperty, *, content_type: str = "application/json", **kwargs: Any ) -> _models.BillingProperty: """Updates the billing property of a subscription. Currently, cost center can be updated. The operation is supported only for billing accounts with agreement type Microsoft Customer Agreement. :param parameters: Request parameters that are provided to the update billing property operation. Required. :type parameters: ~azure.mgmt.billing.models.BillingProperty :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: BillingProperty or the result of cls(response) :rtype: ~azure.mgmt.billing.models.BillingProperty :raises ~azure.core.exceptions.HttpResponseError: """ @overload async def update( self, parameters: IO, *, content_type: str = "application/json", **kwargs: Any ) -> _models.BillingProperty: """Updates the billing property of a subscription. Currently, cost center can be updated. The operation is supported only for billing accounts with agreement type Microsoft Customer Agreement. :param parameters: Request parameters that are provided to the update billing property operation. Required. :type parameters: IO :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: BillingProperty or the result of cls(response) :rtype: ~azure.mgmt.billing.models.BillingProperty :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace_async async def update(self, parameters: Union[_models.BillingProperty, IO], **kwargs: Any) -> _models.BillingProperty: """Updates the billing property of a subscription. Currently, cost center can be updated. The operation is supported only for billing accounts with agreement type Microsoft Customer Agreement. :param parameters: Request parameters that are provided to the update billing property operation. Is either a model type or a IO type. Required. :type parameters: ~azure.mgmt.billing.models.BillingProperty or IO :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. Default value is None. :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: BillingProperty or the result of cls(response) :rtype: ~azure.mgmt.billing.models.BillingProperty :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingProperty] content_type = content_type or "application/json" _json = None _content = None if isinstance(parameters, (IO, bytes)): _content = parameters else: _json = self._serialize.body(parameters, "BillingProperty") request = build_update_request( subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, content=_content, template_url=self.update.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize("BillingProperty", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized update.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Billing/billingProperty/default"} # type: ignore
0.737914
0.088151
import sys from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, map_error, ) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models from ..._vendor import _convert_request from ...operations._operations import build_list_request if sys.version_info >= (3, 8): from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports else: from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] class Operations: """ .. warning:: **DO NOT** instantiate this class directly. Instead, you should access the following operations through :class:`~azure.mgmt.billing.aio.BillingManagementClient`'s :attr:`operations` attribute. """ models = _models def __init__(self, *args, **kwargs) -> None: input_args = list(args) self._client = input_args.pop(0) if input_args else kwargs.pop("client") self._config = input_args.pop(0) if input_args else kwargs.pop("config") self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace def list(self, **kwargs: Any) -> AsyncIterable["_models.Operation"]: """Lists the available billing REST API operations. :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either Operation or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.Operation] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.OperationListResult] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_request( api_version=api_version, template_url=self.list.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore else: request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request async def extract_data(pipeline_response): deserialized = self._deserialize("OperationListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.OperationsErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged(get_next, extract_data) list.metadata = {"url": "/providers/Microsoft.Billing/operations"} # type: ignore
azure-mgmt-billing
/azure_mgmt_billing-6.1.0b1-py3-none-any.whl/azure/mgmt/billing/aio/operations/_operations.py
_operations.py
import sys from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, map_error, ) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models from ..._vendor import _convert_request from ...operations._operations import build_list_request if sys.version_info >= (3, 8): from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports else: from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] class Operations: """ .. warning:: **DO NOT** instantiate this class directly. Instead, you should access the following operations through :class:`~azure.mgmt.billing.aio.BillingManagementClient`'s :attr:`operations` attribute. """ models = _models def __init__(self, *args, **kwargs) -> None: input_args = list(args) self._client = input_args.pop(0) if input_args else kwargs.pop("client") self._config = input_args.pop(0) if input_args else kwargs.pop("config") self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace def list(self, **kwargs: Any) -> AsyncIterable["_models.Operation"]: """Lists the available billing REST API operations. :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either Operation or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.Operation] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.OperationListResult] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_request( api_version=api_version, template_url=self.list.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore else: request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request async def extract_data(pipeline_response): deserialized = self._deserialize("OperationListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.OperationsErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged(get_next, extract_data) list.metadata = {"url": "/providers/Microsoft.Billing/operations"} # type: ignore
0.637369
0.08698
from ._billing_accounts_operations import BillingAccountsOperations from ._address_operations import AddressOperations from ._available_balances_operations import AvailableBalancesOperations from ._instructions_operations import InstructionsOperations from ._billing_profiles_operations import BillingProfilesOperations from ._customers_operations import CustomersOperations from ._invoice_sections_operations import InvoiceSectionsOperations from ._billing_permissions_operations import BillingPermissionsOperations from ._billing_subscriptions_operations import BillingSubscriptionsOperations from ._products_operations import ProductsOperations from ._invoices_operations import InvoicesOperations from ._transactions_operations import TransactionsOperations from ._policies_operations import PoliciesOperations from ._billing_property_operations import BillingPropertyOperations from ._billing_role_definitions_operations import BillingRoleDefinitionsOperations from ._billing_role_assignments_operations import BillingRoleAssignmentsOperations from ._agreements_operations import AgreementsOperations from ._reservations_operations import ReservationsOperations from ._enrollment_accounts_operations import EnrollmentAccountsOperations from ._billing_periods_operations import BillingPeriodsOperations from ._operations import Operations from ._patch import __all__ as _patch_all from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import from ._patch import patch_sdk as _patch_sdk __all__ = [ "BillingAccountsOperations", "AddressOperations", "AvailableBalancesOperations", "InstructionsOperations", "BillingProfilesOperations", "CustomersOperations", "InvoiceSectionsOperations", "BillingPermissionsOperations", "BillingSubscriptionsOperations", "ProductsOperations", "InvoicesOperations", "TransactionsOperations", "PoliciesOperations", "BillingPropertyOperations", "BillingRoleDefinitionsOperations", "BillingRoleAssignmentsOperations", "AgreementsOperations", "ReservationsOperations", "EnrollmentAccountsOperations", "BillingPeriodsOperations", "Operations", ] __all__.extend([p for p in _patch_all if p not in __all__]) _patch_sdk()
azure-mgmt-billing
/azure_mgmt_billing-6.1.0b1-py3-none-any.whl/azure/mgmt/billing/aio/operations/__init__.py
__init__.py
from ._billing_accounts_operations import BillingAccountsOperations from ._address_operations import AddressOperations from ._available_balances_operations import AvailableBalancesOperations from ._instructions_operations import InstructionsOperations from ._billing_profiles_operations import BillingProfilesOperations from ._customers_operations import CustomersOperations from ._invoice_sections_operations import InvoiceSectionsOperations from ._billing_permissions_operations import BillingPermissionsOperations from ._billing_subscriptions_operations import BillingSubscriptionsOperations from ._products_operations import ProductsOperations from ._invoices_operations import InvoicesOperations from ._transactions_operations import TransactionsOperations from ._policies_operations import PoliciesOperations from ._billing_property_operations import BillingPropertyOperations from ._billing_role_definitions_operations import BillingRoleDefinitionsOperations from ._billing_role_assignments_operations import BillingRoleAssignmentsOperations from ._agreements_operations import AgreementsOperations from ._reservations_operations import ReservationsOperations from ._enrollment_accounts_operations import EnrollmentAccountsOperations from ._billing_periods_operations import BillingPeriodsOperations from ._operations import Operations from ._patch import __all__ as _patch_all from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import from ._patch import patch_sdk as _patch_sdk __all__ = [ "BillingAccountsOperations", "AddressOperations", "AvailableBalancesOperations", "InstructionsOperations", "BillingProfilesOperations", "CustomersOperations", "InvoiceSectionsOperations", "BillingPermissionsOperations", "BillingSubscriptionsOperations", "ProductsOperations", "InvoicesOperations", "TransactionsOperations", "PoliciesOperations", "BillingPropertyOperations", "BillingRoleDefinitionsOperations", "BillingRoleAssignmentsOperations", "AgreementsOperations", "ReservationsOperations", "EnrollmentAccountsOperations", "BillingPeriodsOperations", "Operations", ] __all__.extend([p for p in _patch_all if p not in __all__]) _patch_sdk()
0.437824
0.066448
import sys from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, map_error, ) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling from ... import models as _models from ..._vendor import _convert_request from ...operations._billing_profiles_operations import ( build_create_or_update_request, build_get_request, build_list_by_billing_account_request, ) if sys.version_info >= (3, 8): from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports else: from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] class BillingProfilesOperations: """ .. warning:: **DO NOT** instantiate this class directly. Instead, you should access the following operations through :class:`~azure.mgmt.billing.aio.BillingManagementClient`'s :attr:`billing_profiles` attribute. """ models = _models def __init__(self, *args, **kwargs) -> None: input_args = list(args) self._client = input_args.pop(0) if input_args else kwargs.pop("client") self._config = input_args.pop(0) if input_args else kwargs.pop("config") self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace def list_by_billing_account( self, billing_account_name: str, expand: Optional[str] = None, **kwargs: Any ) -> AsyncIterable["_models.BillingProfile"]: """Lists the billing profiles that a user has access to. The operation is supported for billing accounts with agreement type Microsoft Customer Agreement or Microsoft Partner Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param expand: May be used to expand the invoice sections. Default value is None. :type expand: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either BillingProfile or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.BillingProfile] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingProfileListResult] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_by_billing_account_request( billing_account_name=billing_account_name, expand=expand, api_version=api_version, template_url=self.list_by_billing_account.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore else: request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request async def extract_data(pipeline_response): deserialized = self._deserialize("BillingProfileListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged(get_next, extract_data) list_by_billing_account.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles"} # type: ignore @distributed_trace_async async def get( self, billing_account_name: str, billing_profile_name: str, expand: Optional[str] = None, **kwargs: Any ) -> _models.BillingProfile: """Gets a billing profile by its ID. The operation is supported for billing accounts with agreement type Microsoft Customer Agreement or Microsoft Partner Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :param expand: May be used to expand the invoice sections. Default value is None. :type expand: str :keyword callable cls: A custom type or function that will be passed the direct response :return: BillingProfile or the result of cls(response) :rtype: ~azure.mgmt.billing.models.BillingProfile :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingProfile] request = build_get_request( billing_account_name=billing_account_name, billing_profile_name=billing_profile_name, expand=expand, api_version=api_version, template_url=self.get.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize("BillingProfile", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}"} # type: ignore async def _create_or_update_initial( self, billing_account_name: str, billing_profile_name: str, parameters: Union[_models.BillingProfile, IO], **kwargs: Any ) -> Optional[_models.BillingProfile]: error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.BillingProfile]] content_type = content_type or "application/json" _json = None _content = None if isinstance(parameters, (IO, bytes)): _content = parameters else: _json = self._serialize.body(parameters, "BillingProfile") request = build_create_or_update_request( billing_account_name=billing_account_name, billing_profile_name=billing_profile_name, api_version=api_version, content_type=content_type, json=_json, content=_content, template_url=self._create_or_update_initial.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = None response_headers = {} if response.status_code == 200: deserialized = self._deserialize("BillingProfile", pipeline_response) if response.status_code == 202: response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) if cls: return cls(pipeline_response, deserialized, response_headers) return deserialized _create_or_update_initial.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}"} # type: ignore @overload async def begin_create_or_update( self, billing_account_name: str, billing_profile_name: str, parameters: _models.BillingProfile, *, content_type: str = "application/json", **kwargs: Any ) -> AsyncLROPoller[_models.BillingProfile]: """Creates or updates a billing profile. The operation is supported for billing accounts with agreement type Microsoft Customer Agreement or Microsoft Partner Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :param parameters: The new or updated billing profile. Required. :type parameters: ~azure.mgmt.billing.models.BillingProfile :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of AsyncLROPoller that returns either BillingProfile or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.BillingProfile] :raises ~azure.core.exceptions.HttpResponseError: """ @overload async def begin_create_or_update( self, billing_account_name: str, billing_profile_name: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any ) -> AsyncLROPoller[_models.BillingProfile]: """Creates or updates a billing profile. The operation is supported for billing accounts with agreement type Microsoft Customer Agreement or Microsoft Partner Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :param parameters: The new or updated billing profile. Required. :type parameters: IO :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of AsyncLROPoller that returns either BillingProfile or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.BillingProfile] :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace_async async def begin_create_or_update( self, billing_account_name: str, billing_profile_name: str, parameters: Union[_models.BillingProfile, IO], **kwargs: Any ) -> AsyncLROPoller[_models.BillingProfile]: """Creates or updates a billing profile. The operation is supported for billing accounts with agreement type Microsoft Customer Agreement or Microsoft Partner Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :param parameters: The new or updated billing profile. Is either a model type or a IO type. Required. :type parameters: ~azure.mgmt.billing.models.BillingProfile or IO :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. Default value is None. :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of AsyncLROPoller that returns either BillingProfile or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.BillingProfile] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingProfile] polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod] lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: raw_result = await self._create_or_update_initial( # type: ignore billing_account_name=billing_account_name, billing_profile_name=billing_profile_name, parameters=parameters, api_version=api_version, content_type=content_type, cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): deserialized = self._deserialize("BillingProfile", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized if polling is True: polling_method = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) # type: AsyncPollingMethod elif polling is False: polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) else: polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_create_or_update.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}"} # type: ignore
azure-mgmt-billing
/azure_mgmt_billing-6.1.0b1-py3-none-any.whl/azure/mgmt/billing/aio/operations/_billing_profiles_operations.py
_billing_profiles_operations.py
import sys from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, map_error, ) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling from ... import models as _models from ..._vendor import _convert_request from ...operations._billing_profiles_operations import ( build_create_or_update_request, build_get_request, build_list_by_billing_account_request, ) if sys.version_info >= (3, 8): from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports else: from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] class BillingProfilesOperations: """ .. warning:: **DO NOT** instantiate this class directly. Instead, you should access the following operations through :class:`~azure.mgmt.billing.aio.BillingManagementClient`'s :attr:`billing_profiles` attribute. """ models = _models def __init__(self, *args, **kwargs) -> None: input_args = list(args) self._client = input_args.pop(0) if input_args else kwargs.pop("client") self._config = input_args.pop(0) if input_args else kwargs.pop("config") self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace def list_by_billing_account( self, billing_account_name: str, expand: Optional[str] = None, **kwargs: Any ) -> AsyncIterable["_models.BillingProfile"]: """Lists the billing profiles that a user has access to. The operation is supported for billing accounts with agreement type Microsoft Customer Agreement or Microsoft Partner Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param expand: May be used to expand the invoice sections. Default value is None. :type expand: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either BillingProfile or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.BillingProfile] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingProfileListResult] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_by_billing_account_request( billing_account_name=billing_account_name, expand=expand, api_version=api_version, template_url=self.list_by_billing_account.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore else: request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request async def extract_data(pipeline_response): deserialized = self._deserialize("BillingProfileListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged(get_next, extract_data) list_by_billing_account.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles"} # type: ignore @distributed_trace_async async def get( self, billing_account_name: str, billing_profile_name: str, expand: Optional[str] = None, **kwargs: Any ) -> _models.BillingProfile: """Gets a billing profile by its ID. The operation is supported for billing accounts with agreement type Microsoft Customer Agreement or Microsoft Partner Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :param expand: May be used to expand the invoice sections. Default value is None. :type expand: str :keyword callable cls: A custom type or function that will be passed the direct response :return: BillingProfile or the result of cls(response) :rtype: ~azure.mgmt.billing.models.BillingProfile :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingProfile] request = build_get_request( billing_account_name=billing_account_name, billing_profile_name=billing_profile_name, expand=expand, api_version=api_version, template_url=self.get.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize("BillingProfile", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}"} # type: ignore async def _create_or_update_initial( self, billing_account_name: str, billing_profile_name: str, parameters: Union[_models.BillingProfile, IO], **kwargs: Any ) -> Optional[_models.BillingProfile]: error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.BillingProfile]] content_type = content_type or "application/json" _json = None _content = None if isinstance(parameters, (IO, bytes)): _content = parameters else: _json = self._serialize.body(parameters, "BillingProfile") request = build_create_or_update_request( billing_account_name=billing_account_name, billing_profile_name=billing_profile_name, api_version=api_version, content_type=content_type, json=_json, content=_content, template_url=self._create_or_update_initial.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = None response_headers = {} if response.status_code == 200: deserialized = self._deserialize("BillingProfile", pipeline_response) if response.status_code == 202: response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) if cls: return cls(pipeline_response, deserialized, response_headers) return deserialized _create_or_update_initial.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}"} # type: ignore @overload async def begin_create_or_update( self, billing_account_name: str, billing_profile_name: str, parameters: _models.BillingProfile, *, content_type: str = "application/json", **kwargs: Any ) -> AsyncLROPoller[_models.BillingProfile]: """Creates or updates a billing profile. The operation is supported for billing accounts with agreement type Microsoft Customer Agreement or Microsoft Partner Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :param parameters: The new or updated billing profile. Required. :type parameters: ~azure.mgmt.billing.models.BillingProfile :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of AsyncLROPoller that returns either BillingProfile or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.BillingProfile] :raises ~azure.core.exceptions.HttpResponseError: """ @overload async def begin_create_or_update( self, billing_account_name: str, billing_profile_name: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any ) -> AsyncLROPoller[_models.BillingProfile]: """Creates or updates a billing profile. The operation is supported for billing accounts with agreement type Microsoft Customer Agreement or Microsoft Partner Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :param parameters: The new or updated billing profile. Required. :type parameters: IO :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of AsyncLROPoller that returns either BillingProfile or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.BillingProfile] :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace_async async def begin_create_or_update( self, billing_account_name: str, billing_profile_name: str, parameters: Union[_models.BillingProfile, IO], **kwargs: Any ) -> AsyncLROPoller[_models.BillingProfile]: """Creates or updates a billing profile. The operation is supported for billing accounts with agreement type Microsoft Customer Agreement or Microsoft Partner Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :param parameters: The new or updated billing profile. Is either a model type or a IO type. Required. :type parameters: ~azure.mgmt.billing.models.BillingProfile or IO :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. Default value is None. :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of AsyncLROPoller that returns either BillingProfile or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.BillingProfile] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingProfile] polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod] lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: raw_result = await self._create_or_update_initial( # type: ignore billing_account_name=billing_account_name, billing_profile_name=billing_profile_name, parameters=parameters, api_version=api_version, content_type=content_type, cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): deserialized = self._deserialize("BillingProfile", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized if polling is True: polling_method = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) # type: AsyncPollingMethod elif polling is False: polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) else: polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_create_or_update.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}"} # type: ignore
0.709623
0.106365
import sys from typing import Any, Callable, Dict, Optional, TypeVar from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, map_error, ) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.rest import HttpRequest from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models from ..._vendor import _convert_request from ...operations._available_balances_operations import build_get_request if sys.version_info >= (3, 8): from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports else: from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] class AvailableBalancesOperations: """ .. warning:: **DO NOT** instantiate this class directly. Instead, you should access the following operations through :class:`~azure.mgmt.billing.aio.BillingManagementClient`'s :attr:`available_balances` attribute. """ models = _models def __init__(self, *args, **kwargs) -> None: input_args = list(args) self._client = input_args.pop(0) if input_args else kwargs.pop("client") self._config = input_args.pop(0) if input_args else kwargs.pop("config") self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace_async async def get( self, billing_account_name: str, billing_profile_name: str, **kwargs: Any ) -> _models.AvailableBalance: """The available credit balance for a billing profile. This is the balance that can be used for pay now to settle due or past due invoices. The operation is supported only for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: AvailableBalance or the result of cls(response) :rtype: ~azure.mgmt.billing.models.AvailableBalance :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.AvailableBalance] request = build_get_request( billing_account_name=billing_account_name, billing_profile_name=billing_profile_name, api_version=api_version, template_url=self.get.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize("AvailableBalance", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/availableBalance/default"} # type: ignore
azure-mgmt-billing
/azure_mgmt_billing-6.1.0b1-py3-none-any.whl/azure/mgmt/billing/aio/operations/_available_balances_operations.py
_available_balances_operations.py
import sys from typing import Any, Callable, Dict, Optional, TypeVar from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, map_error, ) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.rest import HttpRequest from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models from ..._vendor import _convert_request from ...operations._available_balances_operations import build_get_request if sys.version_info >= (3, 8): from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports else: from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] class AvailableBalancesOperations: """ .. warning:: **DO NOT** instantiate this class directly. Instead, you should access the following operations through :class:`~azure.mgmt.billing.aio.BillingManagementClient`'s :attr:`available_balances` attribute. """ models = _models def __init__(self, *args, **kwargs) -> None: input_args = list(args) self._client = input_args.pop(0) if input_args else kwargs.pop("client") self._config = input_args.pop(0) if input_args else kwargs.pop("config") self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace_async async def get( self, billing_account_name: str, billing_profile_name: str, **kwargs: Any ) -> _models.AvailableBalance: """The available credit balance for a billing profile. This is the balance that can be used for pay now to settle due or past due invoices. The operation is supported only for billing accounts with agreement type Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: AvailableBalance or the result of cls(response) :rtype: ~azure.mgmt.billing.models.AvailableBalance :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.AvailableBalance] request = build_get_request( billing_account_name=billing_account_name, billing_profile_name=billing_profile_name, api_version=api_version, template_url=self.get.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize("AvailableBalance", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/availableBalance/default"} # type: ignore
0.639061
0.091099
import sys from typing import Any, AsyncIterable, Callable, Dict, IO, List, Optional, TypeVar, Union, cast, overload from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, map_error, ) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling from ... import models as _models from ..._vendor import _convert_request from ...operations._invoices_operations import ( build_download_billing_subscription_invoice_request, build_download_invoice_request, build_download_multiple_billing_profile_invoices_request, build_download_multiple_billing_subscription_invoices_request, build_get_by_id_request, build_get_by_subscription_and_invoice_id_request, build_get_request, build_list_by_billing_account_request, build_list_by_billing_profile_request, build_list_by_billing_subscription_request, ) if sys.version_info >= (3, 8): from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports else: from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] class InvoicesOperations: """ .. warning:: **DO NOT** instantiate this class directly. Instead, you should access the following operations through :class:`~azure.mgmt.billing.aio.BillingManagementClient`'s :attr:`invoices` attribute. """ models = _models def __init__(self, *args, **kwargs) -> None: input_args = list(args) self._client = input_args.pop(0) if input_args else kwargs.pop("client") self._config = input_args.pop(0) if input_args else kwargs.pop("config") self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace def list_by_billing_account( self, billing_account_name: str, period_start_date: str, period_end_date: str, **kwargs: Any ) -> AsyncIterable["_models.Invoice"]: """Lists the invoices for a billing account for a given start date and end date. The operation is supported for billing accounts with agreement type Microsoft Partner Agreement or Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param period_start_date: The start date to fetch the invoices. The date should be specified in MM-DD-YYYY format. Required. :type period_start_date: str :param period_end_date: The end date to fetch the invoices. The date should be specified in MM-DD-YYYY format. Required. :type period_end_date: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either Invoice or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.Invoice] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.InvoiceListResult] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_by_billing_account_request( billing_account_name=billing_account_name, period_start_date=period_start_date, period_end_date=period_end_date, api_version=api_version, template_url=self.list_by_billing_account.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore else: request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request async def extract_data(pipeline_response): deserialized = self._deserialize("InvoiceListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged(get_next, extract_data) list_by_billing_account.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/invoices"} # type: ignore @distributed_trace def list_by_billing_profile( self, billing_account_name: str, billing_profile_name: str, period_start_date: str, period_end_date: str, **kwargs: Any ) -> AsyncIterable["_models.Invoice"]: """Lists the invoices for a billing profile for a given start date and end date. The operation is supported for billing accounts with agreement type Microsoft Partner Agreement or Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :param period_start_date: The start date to fetch the invoices. The date should be specified in MM-DD-YYYY format. Required. :type period_start_date: str :param period_end_date: The end date to fetch the invoices. The date should be specified in MM-DD-YYYY format. Required. :type period_end_date: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either Invoice or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.Invoice] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.InvoiceListResult] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_by_billing_profile_request( billing_account_name=billing_account_name, billing_profile_name=billing_profile_name, period_start_date=period_start_date, period_end_date=period_end_date, api_version=api_version, template_url=self.list_by_billing_profile.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore else: request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request async def extract_data(pipeline_response): deserialized = self._deserialize("InvoiceListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged(get_next, extract_data) list_by_billing_profile.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoices"} # type: ignore @distributed_trace_async async def get(self, billing_account_name: str, invoice_name: str, **kwargs: Any) -> _models.Invoice: """Gets an invoice by billing account name and ID. The operation is supported for billing accounts with agreement type Microsoft Partner Agreement or Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param invoice_name: The ID that uniquely identifies an invoice. Required. :type invoice_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Invoice or the result of cls(response) :rtype: ~azure.mgmt.billing.models.Invoice :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.Invoice] request = build_get_request( billing_account_name=billing_account_name, invoice_name=invoice_name, api_version=api_version, template_url=self.get.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize("Invoice", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/invoices/{invoiceName}"} # type: ignore @distributed_trace_async async def get_by_id(self, invoice_name: str, **kwargs: Any) -> _models.Invoice: """Gets an invoice by ID. The operation is supported for billing accounts with agreement type Microsoft Partner Agreement or Microsoft Customer Agreement. :param invoice_name: The ID that uniquely identifies an invoice. Required. :type invoice_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Invoice or the result of cls(response) :rtype: ~azure.mgmt.billing.models.Invoice :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.Invoice] request = build_get_by_id_request( invoice_name=invoice_name, api_version=api_version, template_url=self.get_by_id.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize("Invoice", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get_by_id.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/default/invoices/{invoiceName}"} # type: ignore async def _download_invoice_initial( self, billing_account_name: str, invoice_name: str, download_token: str, **kwargs: Any ) -> Optional[_models.DownloadUrl]: error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.DownloadUrl]] request = build_download_invoice_request( billing_account_name=billing_account_name, invoice_name=invoice_name, download_token=download_token, api_version=api_version, template_url=self._download_invoice_initial.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = None response_headers = {} if response.status_code == 200: deserialized = self._deserialize("DownloadUrl", pipeline_response) if response.status_code == 202: response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) response_headers["Retry-After"] = self._deserialize("str", response.headers.get("Retry-After")) if cls: return cls(pipeline_response, deserialized, response_headers) return deserialized _download_invoice_initial.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/invoices/{invoiceName}/download"} # type: ignore @distributed_trace_async async def begin_download_invoice( self, billing_account_name: str, invoice_name: str, download_token: str, **kwargs: Any ) -> AsyncLROPoller[_models.DownloadUrl]: """Gets a URL to download an invoice. The operation is supported for billing accounts with agreement type Microsoft Partner Agreement or Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param invoice_name: The ID that uniquely identifies an invoice. Required. :type invoice_name: str :param download_token: Download token with document source and document ID. Required. :type download_token: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of AsyncLROPoller that returns either DownloadUrl or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.DownloadUrl] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.DownloadUrl] polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod] lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: raw_result = await self._download_invoice_initial( # type: ignore billing_account_name=billing_account_name, invoice_name=invoice_name, download_token=download_token, api_version=api_version, cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): deserialized = self._deserialize("DownloadUrl", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized if polling is True: polling_method = cast( AsyncPollingMethod, AsyncARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) ) # type: AsyncPollingMethod elif polling is False: polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) else: polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_download_invoice.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/invoices/{invoiceName}/download"} # type: ignore async def _download_multiple_billing_profile_invoices_initial( self, billing_account_name: str, download_urls: Union[List[str], IO], **kwargs: Any ) -> Optional[_models.DownloadUrl]: error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.DownloadUrl]] content_type = content_type or "application/json" _json = None _content = None if isinstance(download_urls, (IO, bytes)): _content = download_urls else: _json = self._serialize.body(download_urls, "[str]") request = build_download_multiple_billing_profile_invoices_request( billing_account_name=billing_account_name, api_version=api_version, content_type=content_type, json=_json, content=_content, template_url=self._download_multiple_billing_profile_invoices_initial.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = None response_headers = {} if response.status_code == 200: deserialized = self._deserialize("DownloadUrl", pipeline_response) if response.status_code == 202: response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) response_headers["Retry-After"] = self._deserialize("str", response.headers.get("Retry-After")) if cls: return cls(pipeline_response, deserialized, response_headers) return deserialized _download_multiple_billing_profile_invoices_initial.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/downloadDocuments"} # type: ignore @overload async def begin_download_multiple_billing_profile_invoices( self, billing_account_name: str, download_urls: List[str], *, content_type: str = "application/json", **kwargs: Any ) -> AsyncLROPoller[_models.DownloadUrl]: """Gets a URL to download multiple invoice documents (invoice pdf, tax receipts, credit notes) as a zip file. The operation is supported for billing accounts with agreement type Microsoft Partner Agreement or Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param download_urls: An array of download urls for individual documents. Required. :type download_urls: list[str] :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of AsyncLROPoller that returns either DownloadUrl or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.DownloadUrl] :raises ~azure.core.exceptions.HttpResponseError: """ @overload async def begin_download_multiple_billing_profile_invoices( self, billing_account_name: str, download_urls: IO, *, content_type: str = "application/json", **kwargs: Any ) -> AsyncLROPoller[_models.DownloadUrl]: """Gets a URL to download multiple invoice documents (invoice pdf, tax receipts, credit notes) as a zip file. The operation is supported for billing accounts with agreement type Microsoft Partner Agreement or Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param download_urls: An array of download urls for individual documents. Required. :type download_urls: IO :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of AsyncLROPoller that returns either DownloadUrl or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.DownloadUrl] :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace_async async def begin_download_multiple_billing_profile_invoices( self, billing_account_name: str, download_urls: Union[List[str], IO], **kwargs: Any ) -> AsyncLROPoller[_models.DownloadUrl]: """Gets a URL to download multiple invoice documents (invoice pdf, tax receipts, credit notes) as a zip file. The operation is supported for billing accounts with agreement type Microsoft Partner Agreement or Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param download_urls: An array of download urls for individual documents. Is either a list type or a IO type. Required. :type download_urls: list[str] or IO :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. Default value is None. :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of AsyncLROPoller that returns either DownloadUrl or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.DownloadUrl] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] cls = kwargs.pop("cls", None) # type: ClsType[_models.DownloadUrl] polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod] lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: raw_result = await self._download_multiple_billing_profile_invoices_initial( # type: ignore billing_account_name=billing_account_name, download_urls=download_urls, api_version=api_version, content_type=content_type, cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): deserialized = self._deserialize("DownloadUrl", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized if polling is True: polling_method = cast( AsyncPollingMethod, AsyncARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) ) # type: AsyncPollingMethod elif polling is False: polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) else: polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_download_multiple_billing_profile_invoices.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/downloadDocuments"} # type: ignore @distributed_trace def list_by_billing_subscription( self, period_start_date: str, period_end_date: str, **kwargs: Any ) -> AsyncIterable["_models.Invoice"]: """Lists the invoices for a subscription. :param period_start_date: Invoice period start date. Required. :type period_start_date: str :param period_end_date: Invoice period end date. Required. :type period_end_date: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either Invoice or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.Invoice] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.InvoiceListResult] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_by_billing_subscription_request( subscription_id=self._config.subscription_id, period_start_date=period_start_date, period_end_date=period_end_date, api_version=api_version, template_url=self.list_by_billing_subscription.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore else: request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request async def extract_data(pipeline_response): deserialized = self._deserialize("InvoiceListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged(get_next, extract_data) list_by_billing_subscription.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/default/billingSubscriptions/{subscriptionId}/invoices"} # type: ignore @distributed_trace_async async def get_by_subscription_and_invoice_id(self, invoice_name: str, **kwargs: Any) -> _models.Invoice: """Gets an invoice by subscription ID and invoice ID. :param invoice_name: The ID that uniquely identifies an invoice. Required. :type invoice_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Invoice or the result of cls(response) :rtype: ~azure.mgmt.billing.models.Invoice :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.Invoice] request = build_get_by_subscription_and_invoice_id_request( invoice_name=invoice_name, subscription_id=self._config.subscription_id, api_version=api_version, template_url=self.get_by_subscription_and_invoice_id.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize("Invoice", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get_by_subscription_and_invoice_id.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/default/billingSubscriptions/{subscriptionId}/invoices/{invoiceName}"} # type: ignore async def _download_billing_subscription_invoice_initial( self, invoice_name: str, download_token: str, **kwargs: Any ) -> Optional[_models.DownloadUrl]: error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.DownloadUrl]] request = build_download_billing_subscription_invoice_request( invoice_name=invoice_name, subscription_id=self._config.subscription_id, download_token=download_token, api_version=api_version, template_url=self._download_billing_subscription_invoice_initial.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = None response_headers = {} if response.status_code == 200: deserialized = self._deserialize("DownloadUrl", pipeline_response) if response.status_code == 202: response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) response_headers["Retry-After"] = self._deserialize("str", response.headers.get("Retry-After")) if cls: return cls(pipeline_response, deserialized, response_headers) return deserialized _download_billing_subscription_invoice_initial.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/default/billingSubscriptions/{subscriptionId}/invoices/{invoiceName}/download"} # type: ignore @distributed_trace_async async def begin_download_billing_subscription_invoice( self, invoice_name: str, download_token: str, **kwargs: Any ) -> AsyncLROPoller[_models.DownloadUrl]: """Gets a URL to download an invoice. :param invoice_name: The ID that uniquely identifies an invoice. Required. :type invoice_name: str :param download_token: Download token with document source and document ID. Required. :type download_token: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of AsyncLROPoller that returns either DownloadUrl or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.DownloadUrl] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.DownloadUrl] polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod] lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: raw_result = await self._download_billing_subscription_invoice_initial( # type: ignore invoice_name=invoice_name, download_token=download_token, api_version=api_version, cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): deserialized = self._deserialize("DownloadUrl", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized if polling is True: polling_method = cast( AsyncPollingMethod, AsyncARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) ) # type: AsyncPollingMethod elif polling is False: polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) else: polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_download_billing_subscription_invoice.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/default/billingSubscriptions/{subscriptionId}/invoices/{invoiceName}/download"} # type: ignore async def _download_multiple_billing_subscription_invoices_initial( self, download_urls: Union[List[str], IO], **kwargs: Any ) -> Optional[_models.DownloadUrl]: error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.DownloadUrl]] content_type = content_type or "application/json" _json = None _content = None if isinstance(download_urls, (IO, bytes)): _content = download_urls else: _json = self._serialize.body(download_urls, "[str]") request = build_download_multiple_billing_subscription_invoices_request( subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, content=_content, template_url=self._download_multiple_billing_subscription_invoices_initial.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = None response_headers = {} if response.status_code == 200: deserialized = self._deserialize("DownloadUrl", pipeline_response) if response.status_code == 202: response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) response_headers["Retry-After"] = self._deserialize("str", response.headers.get("Retry-After")) if cls: return cls(pipeline_response, deserialized, response_headers) return deserialized _download_multiple_billing_subscription_invoices_initial.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/default/billingSubscriptions/{subscriptionId}/downloadDocuments"} # type: ignore @overload async def begin_download_multiple_billing_subscription_invoices( self, download_urls: List[str], *, content_type: str = "application/json", **kwargs: Any ) -> AsyncLROPoller[_models.DownloadUrl]: """Gets a URL to download multiple invoice documents (invoice pdf, tax receipts, credit notes) as a zip file. :param download_urls: An array of download urls for individual documents. Required. :type download_urls: list[str] :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of AsyncLROPoller that returns either DownloadUrl or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.DownloadUrl] :raises ~azure.core.exceptions.HttpResponseError: """ @overload async def begin_download_multiple_billing_subscription_invoices( self, download_urls: IO, *, content_type: str = "application/json", **kwargs: Any ) -> AsyncLROPoller[_models.DownloadUrl]: """Gets a URL to download multiple invoice documents (invoice pdf, tax receipts, credit notes) as a zip file. :param download_urls: An array of download urls for individual documents. Required. :type download_urls: IO :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of AsyncLROPoller that returns either DownloadUrl or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.DownloadUrl] :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace_async async def begin_download_multiple_billing_subscription_invoices( self, download_urls: Union[List[str], IO], **kwargs: Any ) -> AsyncLROPoller[_models.DownloadUrl]: """Gets a URL to download multiple invoice documents (invoice pdf, tax receipts, credit notes) as a zip file. :param download_urls: An array of download urls for individual documents. Is either a list type or a IO type. Required. :type download_urls: list[str] or IO :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. Default value is None. :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of AsyncLROPoller that returns either DownloadUrl or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.DownloadUrl] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] cls = kwargs.pop("cls", None) # type: ClsType[_models.DownloadUrl] polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod] lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: raw_result = await self._download_multiple_billing_subscription_invoices_initial( # type: ignore download_urls=download_urls, api_version=api_version, content_type=content_type, cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): deserialized = self._deserialize("DownloadUrl", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized if polling is True: polling_method = cast( AsyncPollingMethod, AsyncARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) ) # type: AsyncPollingMethod elif polling is False: polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) else: polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_download_multiple_billing_subscription_invoices.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/default/billingSubscriptions/{subscriptionId}/downloadDocuments"} # type: ignore
azure-mgmt-billing
/azure_mgmt_billing-6.1.0b1-py3-none-any.whl/azure/mgmt/billing/aio/operations/_invoices_operations.py
_invoices_operations.py
import sys from typing import Any, AsyncIterable, Callable, Dict, IO, List, Optional, TypeVar, Union, cast, overload from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, map_error, ) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling from ... import models as _models from ..._vendor import _convert_request from ...operations._invoices_operations import ( build_download_billing_subscription_invoice_request, build_download_invoice_request, build_download_multiple_billing_profile_invoices_request, build_download_multiple_billing_subscription_invoices_request, build_get_by_id_request, build_get_by_subscription_and_invoice_id_request, build_get_request, build_list_by_billing_account_request, build_list_by_billing_profile_request, build_list_by_billing_subscription_request, ) if sys.version_info >= (3, 8): from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports else: from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] class InvoicesOperations: """ .. warning:: **DO NOT** instantiate this class directly. Instead, you should access the following operations through :class:`~azure.mgmt.billing.aio.BillingManagementClient`'s :attr:`invoices` attribute. """ models = _models def __init__(self, *args, **kwargs) -> None: input_args = list(args) self._client = input_args.pop(0) if input_args else kwargs.pop("client") self._config = input_args.pop(0) if input_args else kwargs.pop("config") self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace def list_by_billing_account( self, billing_account_name: str, period_start_date: str, period_end_date: str, **kwargs: Any ) -> AsyncIterable["_models.Invoice"]: """Lists the invoices for a billing account for a given start date and end date. The operation is supported for billing accounts with agreement type Microsoft Partner Agreement or Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param period_start_date: The start date to fetch the invoices. The date should be specified in MM-DD-YYYY format. Required. :type period_start_date: str :param period_end_date: The end date to fetch the invoices. The date should be specified in MM-DD-YYYY format. Required. :type period_end_date: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either Invoice or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.Invoice] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.InvoiceListResult] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_by_billing_account_request( billing_account_name=billing_account_name, period_start_date=period_start_date, period_end_date=period_end_date, api_version=api_version, template_url=self.list_by_billing_account.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore else: request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request async def extract_data(pipeline_response): deserialized = self._deserialize("InvoiceListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged(get_next, extract_data) list_by_billing_account.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/invoices"} # type: ignore @distributed_trace def list_by_billing_profile( self, billing_account_name: str, billing_profile_name: str, period_start_date: str, period_end_date: str, **kwargs: Any ) -> AsyncIterable["_models.Invoice"]: """Lists the invoices for a billing profile for a given start date and end date. The operation is supported for billing accounts with agreement type Microsoft Partner Agreement or Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :param period_start_date: The start date to fetch the invoices. The date should be specified in MM-DD-YYYY format. Required. :type period_start_date: str :param period_end_date: The end date to fetch the invoices. The date should be specified in MM-DD-YYYY format. Required. :type period_end_date: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either Invoice or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.Invoice] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.InvoiceListResult] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_by_billing_profile_request( billing_account_name=billing_account_name, billing_profile_name=billing_profile_name, period_start_date=period_start_date, period_end_date=period_end_date, api_version=api_version, template_url=self.list_by_billing_profile.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore else: request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request async def extract_data(pipeline_response): deserialized = self._deserialize("InvoiceListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged(get_next, extract_data) list_by_billing_profile.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoices"} # type: ignore @distributed_trace_async async def get(self, billing_account_name: str, invoice_name: str, **kwargs: Any) -> _models.Invoice: """Gets an invoice by billing account name and ID. The operation is supported for billing accounts with agreement type Microsoft Partner Agreement or Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param invoice_name: The ID that uniquely identifies an invoice. Required. :type invoice_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Invoice or the result of cls(response) :rtype: ~azure.mgmt.billing.models.Invoice :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.Invoice] request = build_get_request( billing_account_name=billing_account_name, invoice_name=invoice_name, api_version=api_version, template_url=self.get.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize("Invoice", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/invoices/{invoiceName}"} # type: ignore @distributed_trace_async async def get_by_id(self, invoice_name: str, **kwargs: Any) -> _models.Invoice: """Gets an invoice by ID. The operation is supported for billing accounts with agreement type Microsoft Partner Agreement or Microsoft Customer Agreement. :param invoice_name: The ID that uniquely identifies an invoice. Required. :type invoice_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Invoice or the result of cls(response) :rtype: ~azure.mgmt.billing.models.Invoice :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.Invoice] request = build_get_by_id_request( invoice_name=invoice_name, api_version=api_version, template_url=self.get_by_id.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize("Invoice", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get_by_id.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/default/invoices/{invoiceName}"} # type: ignore async def _download_invoice_initial( self, billing_account_name: str, invoice_name: str, download_token: str, **kwargs: Any ) -> Optional[_models.DownloadUrl]: error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.DownloadUrl]] request = build_download_invoice_request( billing_account_name=billing_account_name, invoice_name=invoice_name, download_token=download_token, api_version=api_version, template_url=self._download_invoice_initial.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = None response_headers = {} if response.status_code == 200: deserialized = self._deserialize("DownloadUrl", pipeline_response) if response.status_code == 202: response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) response_headers["Retry-After"] = self._deserialize("str", response.headers.get("Retry-After")) if cls: return cls(pipeline_response, deserialized, response_headers) return deserialized _download_invoice_initial.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/invoices/{invoiceName}/download"} # type: ignore @distributed_trace_async async def begin_download_invoice( self, billing_account_name: str, invoice_name: str, download_token: str, **kwargs: Any ) -> AsyncLROPoller[_models.DownloadUrl]: """Gets a URL to download an invoice. The operation is supported for billing accounts with agreement type Microsoft Partner Agreement or Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param invoice_name: The ID that uniquely identifies an invoice. Required. :type invoice_name: str :param download_token: Download token with document source and document ID. Required. :type download_token: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of AsyncLROPoller that returns either DownloadUrl or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.DownloadUrl] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.DownloadUrl] polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod] lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: raw_result = await self._download_invoice_initial( # type: ignore billing_account_name=billing_account_name, invoice_name=invoice_name, download_token=download_token, api_version=api_version, cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): deserialized = self._deserialize("DownloadUrl", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized if polling is True: polling_method = cast( AsyncPollingMethod, AsyncARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) ) # type: AsyncPollingMethod elif polling is False: polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) else: polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_download_invoice.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/invoices/{invoiceName}/download"} # type: ignore async def _download_multiple_billing_profile_invoices_initial( self, billing_account_name: str, download_urls: Union[List[str], IO], **kwargs: Any ) -> Optional[_models.DownloadUrl]: error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.DownloadUrl]] content_type = content_type or "application/json" _json = None _content = None if isinstance(download_urls, (IO, bytes)): _content = download_urls else: _json = self._serialize.body(download_urls, "[str]") request = build_download_multiple_billing_profile_invoices_request( billing_account_name=billing_account_name, api_version=api_version, content_type=content_type, json=_json, content=_content, template_url=self._download_multiple_billing_profile_invoices_initial.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = None response_headers = {} if response.status_code == 200: deserialized = self._deserialize("DownloadUrl", pipeline_response) if response.status_code == 202: response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) response_headers["Retry-After"] = self._deserialize("str", response.headers.get("Retry-After")) if cls: return cls(pipeline_response, deserialized, response_headers) return deserialized _download_multiple_billing_profile_invoices_initial.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/downloadDocuments"} # type: ignore @overload async def begin_download_multiple_billing_profile_invoices( self, billing_account_name: str, download_urls: List[str], *, content_type: str = "application/json", **kwargs: Any ) -> AsyncLROPoller[_models.DownloadUrl]: """Gets a URL to download multiple invoice documents (invoice pdf, tax receipts, credit notes) as a zip file. The operation is supported for billing accounts with agreement type Microsoft Partner Agreement or Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param download_urls: An array of download urls for individual documents. Required. :type download_urls: list[str] :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of AsyncLROPoller that returns either DownloadUrl or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.DownloadUrl] :raises ~azure.core.exceptions.HttpResponseError: """ @overload async def begin_download_multiple_billing_profile_invoices( self, billing_account_name: str, download_urls: IO, *, content_type: str = "application/json", **kwargs: Any ) -> AsyncLROPoller[_models.DownloadUrl]: """Gets a URL to download multiple invoice documents (invoice pdf, tax receipts, credit notes) as a zip file. The operation is supported for billing accounts with agreement type Microsoft Partner Agreement or Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param download_urls: An array of download urls for individual documents. Required. :type download_urls: IO :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of AsyncLROPoller that returns either DownloadUrl or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.DownloadUrl] :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace_async async def begin_download_multiple_billing_profile_invoices( self, billing_account_name: str, download_urls: Union[List[str], IO], **kwargs: Any ) -> AsyncLROPoller[_models.DownloadUrl]: """Gets a URL to download multiple invoice documents (invoice pdf, tax receipts, credit notes) as a zip file. The operation is supported for billing accounts with agreement type Microsoft Partner Agreement or Microsoft Customer Agreement. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param download_urls: An array of download urls for individual documents. Is either a list type or a IO type. Required. :type download_urls: list[str] or IO :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. Default value is None. :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of AsyncLROPoller that returns either DownloadUrl or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.DownloadUrl] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] cls = kwargs.pop("cls", None) # type: ClsType[_models.DownloadUrl] polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod] lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: raw_result = await self._download_multiple_billing_profile_invoices_initial( # type: ignore billing_account_name=billing_account_name, download_urls=download_urls, api_version=api_version, content_type=content_type, cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): deserialized = self._deserialize("DownloadUrl", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized if polling is True: polling_method = cast( AsyncPollingMethod, AsyncARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) ) # type: AsyncPollingMethod elif polling is False: polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) else: polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_download_multiple_billing_profile_invoices.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/downloadDocuments"} # type: ignore @distributed_trace def list_by_billing_subscription( self, period_start_date: str, period_end_date: str, **kwargs: Any ) -> AsyncIterable["_models.Invoice"]: """Lists the invoices for a subscription. :param period_start_date: Invoice period start date. Required. :type period_start_date: str :param period_end_date: Invoice period end date. Required. :type period_end_date: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either Invoice or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.Invoice] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.InvoiceListResult] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_by_billing_subscription_request( subscription_id=self._config.subscription_id, period_start_date=period_start_date, period_end_date=period_end_date, api_version=api_version, template_url=self.list_by_billing_subscription.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore else: request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request async def extract_data(pipeline_response): deserialized = self._deserialize("InvoiceListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged(get_next, extract_data) list_by_billing_subscription.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/default/billingSubscriptions/{subscriptionId}/invoices"} # type: ignore @distributed_trace_async async def get_by_subscription_and_invoice_id(self, invoice_name: str, **kwargs: Any) -> _models.Invoice: """Gets an invoice by subscription ID and invoice ID. :param invoice_name: The ID that uniquely identifies an invoice. Required. :type invoice_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Invoice or the result of cls(response) :rtype: ~azure.mgmt.billing.models.Invoice :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.Invoice] request = build_get_by_subscription_and_invoice_id_request( invoice_name=invoice_name, subscription_id=self._config.subscription_id, api_version=api_version, template_url=self.get_by_subscription_and_invoice_id.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize("Invoice", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get_by_subscription_and_invoice_id.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/default/billingSubscriptions/{subscriptionId}/invoices/{invoiceName}"} # type: ignore async def _download_billing_subscription_invoice_initial( self, invoice_name: str, download_token: str, **kwargs: Any ) -> Optional[_models.DownloadUrl]: error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.DownloadUrl]] request = build_download_billing_subscription_invoice_request( invoice_name=invoice_name, subscription_id=self._config.subscription_id, download_token=download_token, api_version=api_version, template_url=self._download_billing_subscription_invoice_initial.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = None response_headers = {} if response.status_code == 200: deserialized = self._deserialize("DownloadUrl", pipeline_response) if response.status_code == 202: response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) response_headers["Retry-After"] = self._deserialize("str", response.headers.get("Retry-After")) if cls: return cls(pipeline_response, deserialized, response_headers) return deserialized _download_billing_subscription_invoice_initial.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/default/billingSubscriptions/{subscriptionId}/invoices/{invoiceName}/download"} # type: ignore @distributed_trace_async async def begin_download_billing_subscription_invoice( self, invoice_name: str, download_token: str, **kwargs: Any ) -> AsyncLROPoller[_models.DownloadUrl]: """Gets a URL to download an invoice. :param invoice_name: The ID that uniquely identifies an invoice. Required. :type invoice_name: str :param download_token: Download token with document source and document ID. Required. :type download_token: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of AsyncLROPoller that returns either DownloadUrl or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.DownloadUrl] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] cls = kwargs.pop("cls", None) # type: ClsType[_models.DownloadUrl] polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod] lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: raw_result = await self._download_billing_subscription_invoice_initial( # type: ignore invoice_name=invoice_name, download_token=download_token, api_version=api_version, cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): deserialized = self._deserialize("DownloadUrl", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized if polling is True: polling_method = cast( AsyncPollingMethod, AsyncARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) ) # type: AsyncPollingMethod elif polling is False: polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) else: polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_download_billing_subscription_invoice.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/default/billingSubscriptions/{subscriptionId}/invoices/{invoiceName}/download"} # type: ignore async def _download_multiple_billing_subscription_invoices_initial( self, download_urls: Union[List[str], IO], **kwargs: Any ) -> Optional[_models.DownloadUrl]: error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.DownloadUrl]] content_type = content_type or "application/json" _json = None _content = None if isinstance(download_urls, (IO, bytes)): _content = download_urls else: _json = self._serialize.body(download_urls, "[str]") request = build_download_multiple_billing_subscription_invoices_request( subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, content=_content, template_url=self._download_multiple_billing_subscription_invoices_initial.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = None response_headers = {} if response.status_code == 200: deserialized = self._deserialize("DownloadUrl", pipeline_response) if response.status_code == 202: response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) response_headers["Retry-After"] = self._deserialize("str", response.headers.get("Retry-After")) if cls: return cls(pipeline_response, deserialized, response_headers) return deserialized _download_multiple_billing_subscription_invoices_initial.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/default/billingSubscriptions/{subscriptionId}/downloadDocuments"} # type: ignore @overload async def begin_download_multiple_billing_subscription_invoices( self, download_urls: List[str], *, content_type: str = "application/json", **kwargs: Any ) -> AsyncLROPoller[_models.DownloadUrl]: """Gets a URL to download multiple invoice documents (invoice pdf, tax receipts, credit notes) as a zip file. :param download_urls: An array of download urls for individual documents. Required. :type download_urls: list[str] :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of AsyncLROPoller that returns either DownloadUrl or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.DownloadUrl] :raises ~azure.core.exceptions.HttpResponseError: """ @overload async def begin_download_multiple_billing_subscription_invoices( self, download_urls: IO, *, content_type: str = "application/json", **kwargs: Any ) -> AsyncLROPoller[_models.DownloadUrl]: """Gets a URL to download multiple invoice documents (invoice pdf, tax receipts, credit notes) as a zip file. :param download_urls: An array of download urls for individual documents. Required. :type download_urls: IO :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of AsyncLROPoller that returns either DownloadUrl or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.DownloadUrl] :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace_async async def begin_download_multiple_billing_subscription_invoices( self, download_urls: Union[List[str], IO], **kwargs: Any ) -> AsyncLROPoller[_models.DownloadUrl]: """Gets a URL to download multiple invoice documents (invoice pdf, tax receipts, credit notes) as a zip file. :param download_urls: An array of download urls for individual documents. Is either a list type or a IO type. Required. :type download_urls: list[str] or IO :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. Default value is None. :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of AsyncLROPoller that returns either DownloadUrl or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.DownloadUrl] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] cls = kwargs.pop("cls", None) # type: ClsType[_models.DownloadUrl] polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod] lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: raw_result = await self._download_multiple_billing_subscription_invoices_initial( # type: ignore download_urls=download_urls, api_version=api_version, content_type=content_type, cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): deserialized = self._deserialize("DownloadUrl", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized if polling is True: polling_method = cast( AsyncPollingMethod, AsyncARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) ) # type: AsyncPollingMethod elif polling is False: polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) else: polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_download_multiple_billing_subscription_invoices.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/default/billingSubscriptions/{subscriptionId}/downloadDocuments"} # type: ignore
0.695855
0.101233
import sys from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, map_error, ) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models from ..._vendor import _convert_request from ...operations._enrollment_accounts_operations import build_get_request, build_list_request if sys.version_info >= (3, 8): from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports else: from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] class EnrollmentAccountsOperations: """ .. warning:: **DO NOT** instantiate this class directly. Instead, you should access the following operations through :class:`~azure.mgmt.billing.aio.BillingManagementClient`'s :attr:`enrollment_accounts` attribute. """ models = _models def __init__(self, *args, **kwargs) -> None: input_args = list(args) self._client = input_args.pop(0) if input_args else kwargs.pop("client") self._config = input_args.pop(0) if input_args else kwargs.pop("config") self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace def list(self, **kwargs: Any) -> AsyncIterable["_models.EnrollmentAccountSummary"]: """Lists the enrollment accounts the caller has access to. :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either EnrollmentAccountSummary or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.EnrollmentAccountSummary] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop( "api_version", _params.pop("api-version", "2018-03-01-preview") ) # type: Literal["2018-03-01-preview"] cls = kwargs.pop("cls", None) # type: ClsType[_models.EnrollmentAccountListResult] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_request( api_version=api_version, template_url=self.list.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore else: request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request async def extract_data(pipeline_response): deserialized = self._deserialize("EnrollmentAccountListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged(get_next, extract_data) list.metadata = {"url": "/providers/Microsoft.Billing/enrollmentAccounts"} # type: ignore @distributed_trace_async async def get(self, name: str, **kwargs: Any) -> _models.EnrollmentAccountSummary: """Gets a enrollment account by name. :param name: Enrollment Account name. Required. :type name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: EnrollmentAccountSummary or the result of cls(response) :rtype: ~azure.mgmt.billing.models.EnrollmentAccountSummary :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop( "api_version", _params.pop("api-version", "2018-03-01-preview") ) # type: Literal["2018-03-01-preview"] cls = kwargs.pop("cls", None) # type: ClsType[_models.EnrollmentAccountSummary] request = build_get_request( name=name, api_version=api_version, template_url=self.get.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize("EnrollmentAccountSummary", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get.metadata = {"url": "/providers/Microsoft.Billing/enrollmentAccounts/{name}"} # type: ignore
azure-mgmt-billing
/azure_mgmt_billing-6.1.0b1-py3-none-any.whl/azure/mgmt/billing/aio/operations/_enrollment_accounts_operations.py
_enrollment_accounts_operations.py
import sys from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, map_error, ) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models from ..._vendor import _convert_request from ...operations._enrollment_accounts_operations import build_get_request, build_list_request if sys.version_info >= (3, 8): from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports else: from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] class EnrollmentAccountsOperations: """ .. warning:: **DO NOT** instantiate this class directly. Instead, you should access the following operations through :class:`~azure.mgmt.billing.aio.BillingManagementClient`'s :attr:`enrollment_accounts` attribute. """ models = _models def __init__(self, *args, **kwargs) -> None: input_args = list(args) self._client = input_args.pop(0) if input_args else kwargs.pop("client") self._config = input_args.pop(0) if input_args else kwargs.pop("config") self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace def list(self, **kwargs: Any) -> AsyncIterable["_models.EnrollmentAccountSummary"]: """Lists the enrollment accounts the caller has access to. :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either EnrollmentAccountSummary or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.EnrollmentAccountSummary] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop( "api_version", _params.pop("api-version", "2018-03-01-preview") ) # type: Literal["2018-03-01-preview"] cls = kwargs.pop("cls", None) # type: ClsType[_models.EnrollmentAccountListResult] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_request( api_version=api_version, template_url=self.list.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore else: request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request async def extract_data(pipeline_response): deserialized = self._deserialize("EnrollmentAccountListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged(get_next, extract_data) list.metadata = {"url": "/providers/Microsoft.Billing/enrollmentAccounts"} # type: ignore @distributed_trace_async async def get(self, name: str, **kwargs: Any) -> _models.EnrollmentAccountSummary: """Gets a enrollment account by name. :param name: Enrollment Account name. Required. :type name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: EnrollmentAccountSummary or the result of cls(response) :rtype: ~azure.mgmt.billing.models.EnrollmentAccountSummary :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop( "api_version", _params.pop("api-version", "2018-03-01-preview") ) # type: Literal["2018-03-01-preview"] cls = kwargs.pop("cls", None) # type: ClsType[_models.EnrollmentAccountSummary] request = build_get_request( name=name, api_version=api_version, template_url=self.get.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize("EnrollmentAccountSummary", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get.metadata = {"url": "/providers/Microsoft.Billing/enrollmentAccounts/{name}"} # type: ignore
0.681727
0.081996
import sys from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, overload from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, map_error, ) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.rest import HttpRequest from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models from ..._vendor import _convert_request from ...operations._address_operations import build_validate_request if sys.version_info >= (3, 8): from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports else: from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] class AddressOperations: """ .. warning:: **DO NOT** instantiate this class directly. Instead, you should access the following operations through :class:`~azure.mgmt.billing.aio.BillingManagementClient`'s :attr:`address` attribute. """ models = _models def __init__(self, *args, **kwargs) -> None: input_args = list(args) self._client = input_args.pop(0) if input_args else kwargs.pop("client") self._config = input_args.pop(0) if input_args else kwargs.pop("config") self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @overload async def validate( self, address: _models.AddressDetails, *, content_type: str = "application/json", **kwargs: Any ) -> _models.ValidateAddressResponse: """Validates an address. Use the operation to validate an address before using it as soldTo or a billTo address. :param address: Required. :type address: ~azure.mgmt.billing.models.AddressDetails :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: ValidateAddressResponse or the result of cls(response) :rtype: ~azure.mgmt.billing.models.ValidateAddressResponse :raises ~azure.core.exceptions.HttpResponseError: """ @overload async def validate( self, address: IO, *, content_type: str = "application/json", **kwargs: Any ) -> _models.ValidateAddressResponse: """Validates an address. Use the operation to validate an address before using it as soldTo or a billTo address. :param address: Required. :type address: IO :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: ValidateAddressResponse or the result of cls(response) :rtype: ~azure.mgmt.billing.models.ValidateAddressResponse :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace_async async def validate( self, address: Union[_models.AddressDetails, IO], **kwargs: Any ) -> _models.ValidateAddressResponse: """Validates an address. Use the operation to validate an address before using it as soldTo or a billTo address. :param address: Is either a model type or a IO type. Required. :type address: ~azure.mgmt.billing.models.AddressDetails or IO :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. Default value is None. :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: ValidateAddressResponse or the result of cls(response) :rtype: ~azure.mgmt.billing.models.ValidateAddressResponse :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] cls = kwargs.pop("cls", None) # type: ClsType[_models.ValidateAddressResponse] content_type = content_type or "application/json" _json = None _content = None if isinstance(address, (IO, bytes)): _content = address else: _json = self._serialize.body(address, "AddressDetails") request = build_validate_request( api_version=api_version, content_type=content_type, json=_json, content=_content, template_url=self.validate.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize("ValidateAddressResponse", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized validate.metadata = {"url": "/providers/Microsoft.Billing/validateAddress"} # type: ignore
azure-mgmt-billing
/azure_mgmt_billing-6.1.0b1-py3-none-any.whl/azure/mgmt/billing/aio/operations/_address_operations.py
_address_operations.py
import sys from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, overload from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, map_error, ) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.rest import HttpRequest from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models from ..._vendor import _convert_request from ...operations._address_operations import build_validate_request if sys.version_info >= (3, 8): from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports else: from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] class AddressOperations: """ .. warning:: **DO NOT** instantiate this class directly. Instead, you should access the following operations through :class:`~azure.mgmt.billing.aio.BillingManagementClient`'s :attr:`address` attribute. """ models = _models def __init__(self, *args, **kwargs) -> None: input_args = list(args) self._client = input_args.pop(0) if input_args else kwargs.pop("client") self._config = input_args.pop(0) if input_args else kwargs.pop("config") self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @overload async def validate( self, address: _models.AddressDetails, *, content_type: str = "application/json", **kwargs: Any ) -> _models.ValidateAddressResponse: """Validates an address. Use the operation to validate an address before using it as soldTo or a billTo address. :param address: Required. :type address: ~azure.mgmt.billing.models.AddressDetails :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: ValidateAddressResponse or the result of cls(response) :rtype: ~azure.mgmt.billing.models.ValidateAddressResponse :raises ~azure.core.exceptions.HttpResponseError: """ @overload async def validate( self, address: IO, *, content_type: str = "application/json", **kwargs: Any ) -> _models.ValidateAddressResponse: """Validates an address. Use the operation to validate an address before using it as soldTo or a billTo address. :param address: Required. :type address: IO :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: ValidateAddressResponse or the result of cls(response) :rtype: ~azure.mgmt.billing.models.ValidateAddressResponse :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace_async async def validate( self, address: Union[_models.AddressDetails, IO], **kwargs: Any ) -> _models.ValidateAddressResponse: """Validates an address. Use the operation to validate an address before using it as soldTo or a billTo address. :param address: Is either a model type or a IO type. Required. :type address: ~azure.mgmt.billing.models.AddressDetails or IO :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. Default value is None. :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: ValidateAddressResponse or the result of cls(response) :rtype: ~azure.mgmt.billing.models.ValidateAddressResponse :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: Literal["2020-05-01"] content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] cls = kwargs.pop("cls", None) # type: ClsType[_models.ValidateAddressResponse] content_type = content_type or "application/json" _json = None _content = None if isinstance(address, (IO, bytes)): _content = address else: _json = self._serialize.body(address, "AddressDetails") request = build_validate_request( api_version=api_version, content_type=content_type, json=_json, content=_content, template_url=self.validate.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize("ValidateAddressResponse", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized validate.metadata = {"url": "/providers/Microsoft.Billing/validateAddress"} # type: ignore
0.758689
0.112259
import datetime from typing import Dict, List, Optional, TYPE_CHECKING, Union from .. import _serialization if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from .. import models as _models class AddressDetails(_serialization.Model): # pylint: disable=too-many-instance-attributes """Address details. All required parameters must be populated in order to send to Azure. :ivar first_name: First name. :vartype first_name: str :ivar middle_name: Middle name. :vartype middle_name: str :ivar last_name: Last name. :vartype last_name: str :ivar company_name: Company name. :vartype company_name: str :ivar address_line1: Address line 1. Required. :vartype address_line1: str :ivar address_line2: Address line 2. :vartype address_line2: str :ivar address_line3: Address line 3. :vartype address_line3: str :ivar city: Address city. :vartype city: str :ivar district: Address district. :vartype district: str :ivar region: Address region. :vartype region: str :ivar country: Country code uses ISO2, 2-digit format. Required. :vartype country: str :ivar postal_code: Postal code. :vartype postal_code: str :ivar email: Email address. :vartype email: str :ivar phone_number: Phone number. :vartype phone_number: str """ _validation = { "address_line1": {"required": True}, "country": {"required": True}, } _attribute_map = { "first_name": {"key": "firstName", "type": "str"}, "middle_name": {"key": "middleName", "type": "str"}, "last_name": {"key": "lastName", "type": "str"}, "company_name": {"key": "companyName", "type": "str"}, "address_line1": {"key": "addressLine1", "type": "str"}, "address_line2": {"key": "addressLine2", "type": "str"}, "address_line3": {"key": "addressLine3", "type": "str"}, "city": {"key": "city", "type": "str"}, "district": {"key": "district", "type": "str"}, "region": {"key": "region", "type": "str"}, "country": {"key": "country", "type": "str"}, "postal_code": {"key": "postalCode", "type": "str"}, "email": {"key": "email", "type": "str"}, "phone_number": {"key": "phoneNumber", "type": "str"}, } def __init__( self, *, address_line1: str, country: str, first_name: Optional[str] = None, middle_name: Optional[str] = None, last_name: Optional[str] = None, company_name: Optional[str] = None, address_line2: Optional[str] = None, address_line3: Optional[str] = None, city: Optional[str] = None, district: Optional[str] = None, region: Optional[str] = None, postal_code: Optional[str] = None, email: Optional[str] = None, phone_number: Optional[str] = None, **kwargs ): """ :keyword first_name: First name. :paramtype first_name: str :keyword middle_name: Middle name. :paramtype middle_name: str :keyword last_name: Last name. :paramtype last_name: str :keyword company_name: Company name. :paramtype company_name: str :keyword address_line1: Address line 1. Required. :paramtype address_line1: str :keyword address_line2: Address line 2. :paramtype address_line2: str :keyword address_line3: Address line 3. :paramtype address_line3: str :keyword city: Address city. :paramtype city: str :keyword district: Address district. :paramtype district: str :keyword region: Address region. :paramtype region: str :keyword country: Country code uses ISO2, 2-digit format. Required. :paramtype country: str :keyword postal_code: Postal code. :paramtype postal_code: str :keyword email: Email address. :paramtype email: str :keyword phone_number: Phone number. :paramtype phone_number: str """ super().__init__(**kwargs) self.first_name = first_name self.middle_name = middle_name self.last_name = last_name self.company_name = company_name self.address_line1 = address_line1 self.address_line2 = address_line2 self.address_line3 = address_line3 self.city = city self.district = district self.region = region self.country = country self.postal_code = postal_code self.email = email self.phone_number = phone_number class Resource(_serialization.Model): """The Resource model definition. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: Resource Id. :vartype id: str :ivar name: Resource name. :vartype name: str :ivar type: Resource type. :vartype type: str """ _validation = { "id": {"readonly": True}, "name": {"readonly": True}, "type": {"readonly": True}, } _attribute_map = { "id": {"key": "id", "type": "str"}, "name": {"key": "name", "type": "str"}, "type": {"key": "type", "type": "str"}, } def __init__(self, **kwargs): """ """ super().__init__(**kwargs) self.id = None self.name = None self.type = None class Agreement(Resource): # pylint: disable=too-many-instance-attributes """An agreement. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: Resource Id. :vartype id: str :ivar name: Resource name. :vartype name: str :ivar type: Resource type. :vartype type: str :ivar agreement_link: The URL to download the agreement. :vartype agreement_link: str :ivar category: The category of the agreement signed by a customer. Known values are: "MicrosoftCustomerAgreement", "AffiliatePurchaseTerms", and "Other". :vartype category: str or ~azure.mgmt.billing.models.Category :ivar acceptance_mode: The mode of acceptance for an agreement. Known values are: "ClickToAccept", "ESignEmbedded", and "ESignOffline". :vartype acceptance_mode: str or ~azure.mgmt.billing.models.AcceptanceMode :ivar billing_profile_info: The list of billing profiles associated with agreement and present only for specific agreements. :vartype billing_profile_info: ~azure.mgmt.billing.models.BillingProfileInfo :ivar effective_date: The date from which the agreement is effective. :vartype effective_date: ~datetime.datetime :ivar expiration_date: The date when the agreement expires. :vartype expiration_date: ~datetime.datetime :ivar participants: The list of participants that participates in acceptance of an agreement. :vartype participants: list[~azure.mgmt.billing.models.Participants] :ivar status: The current status of the agreement. :vartype status: str """ _validation = { "id": {"readonly": True}, "name": {"readonly": True}, "type": {"readonly": True}, "agreement_link": {"readonly": True}, "category": {"readonly": True}, "acceptance_mode": {"readonly": True}, "billing_profile_info": {"readonly": True}, "effective_date": {"readonly": True}, "expiration_date": {"readonly": True}, "status": {"readonly": True}, } _attribute_map = { "id": {"key": "id", "type": "str"}, "name": {"key": "name", "type": "str"}, "type": {"key": "type", "type": "str"}, "agreement_link": {"key": "properties.agreementLink", "type": "str"}, "category": {"key": "properties.category", "type": "str"}, "acceptance_mode": {"key": "properties.acceptanceMode", "type": "str"}, "billing_profile_info": {"key": "properties.billingProfileInfo", "type": "BillingProfileInfo"}, "effective_date": {"key": "properties.effectiveDate", "type": "iso-8601"}, "expiration_date": {"key": "properties.expirationDate", "type": "iso-8601"}, "participants": {"key": "properties.participants", "type": "[Participants]"}, "status": {"key": "properties.status", "type": "str"}, } def __init__(self, *, participants: Optional[List["_models.Participants"]] = None, **kwargs): """ :keyword participants: The list of participants that participates in acceptance of an agreement. :paramtype participants: list[~azure.mgmt.billing.models.Participants] """ super().__init__(**kwargs) self.agreement_link = None self.category = None self.acceptance_mode = None self.billing_profile_info = None self.effective_date = None self.expiration_date = None self.participants = participants self.status = None class AgreementListResult(_serialization.Model): """Result of listing agreements. Variables are only populated by the server, and will be ignored when sending a request. :ivar value: The list of agreements. :vartype value: list[~azure.mgmt.billing.models.Agreement] :ivar next_link: The link (url) to the next page of results. :vartype next_link: str """ _validation = { "value": {"readonly": True}, "next_link": {"readonly": True}, } _attribute_map = { "value": {"key": "value", "type": "[Agreement]"}, "next_link": {"key": "nextLink", "type": "str"}, } def __init__(self, **kwargs): """ """ super().__init__(**kwargs) self.value = None self.next_link = None class Amount(_serialization.Model): """The amount. Variables are only populated by the server, and will be ignored when sending a request. :ivar currency: The currency for the amount value. :vartype currency: str :ivar value: Amount value. :vartype value: float """ _validation = { "currency": {"readonly": True}, } _attribute_map = { "currency": {"key": "currency", "type": "str"}, "value": {"key": "value", "type": "float"}, } def __init__(self, *, value: Optional[float] = None, **kwargs): """ :keyword value: Amount value. :paramtype value: float """ super().__init__(**kwargs) self.currency = None self.value = value class AvailableBalance(Resource): """The latest Azure credit balance. This is the balance available for pay now. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: Resource Id. :vartype id: str :ivar name: Resource name. :vartype name: str :ivar type: Resource type. :vartype type: str :ivar amount: Balance amount. :vartype amount: ~azure.mgmt.billing.models.Amount """ _validation = { "id": {"readonly": True}, "name": {"readonly": True}, "type": {"readonly": True}, "amount": {"readonly": True}, } _attribute_map = { "id": {"key": "id", "type": "str"}, "name": {"key": "name", "type": "str"}, "type": {"key": "type", "type": "str"}, "amount": {"key": "properties.amount", "type": "Amount"}, } def __init__(self, **kwargs): """ """ super().__init__(**kwargs) self.amount = None class AzurePlan(_serialization.Model): """Details of the Azure plan. Variables are only populated by the server, and will be ignored when sending a request. :ivar sku_id: The sku id. :vartype sku_id: str :ivar sku_description: The sku description. :vartype sku_description: str """ _validation = { "sku_description": {"readonly": True}, } _attribute_map = { "sku_id": {"key": "skuId", "type": "str"}, "sku_description": {"key": "skuDescription", "type": "str"}, } def __init__(self, *, sku_id: Optional[str] = None, **kwargs): """ :keyword sku_id: The sku id. :paramtype sku_id: str """ super().__init__(**kwargs) self.sku_id = sku_id self.sku_description = None class BillingAccount(Resource): # pylint: disable=too-many-instance-attributes """A billing account. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: Resource Id. :vartype id: str :ivar name: Resource name. :vartype name: str :ivar type: Resource type. :vartype type: str :ivar display_name: The billing account name. :vartype display_name: str :ivar sold_to: The address of the individual or organization that is responsible for the billing account. :vartype sold_to: ~azure.mgmt.billing.models.AddressDetails :ivar agreement_type: The type of agreement. Known values are: "MicrosoftCustomerAgreement", "EnterpriseAgreement", "MicrosoftOnlineServicesProgram", and "MicrosoftPartnerAgreement". :vartype agreement_type: str or ~azure.mgmt.billing.models.AgreementType :ivar account_type: The type of customer. Known values are: "Enterprise", "Individual", and "Partner". :vartype account_type: str or ~azure.mgmt.billing.models.AccountType :ivar account_status: The current status of the billing account. Known values are: "Active", "Deleted", "Disabled", "Expired", "Transferred", "Extended", and "Terminated". :vartype account_status: str or ~azure.mgmt.billing.models.AccountStatus :ivar billing_profiles: The billing profiles associated with the billing account. By default this is not populated, unless it's specified in $expand. :vartype billing_profiles: ~azure.mgmt.billing.models.BillingProfilesOnExpand :ivar enrollment_details: The details about the associated legacy enrollment. By default this is not populated, unless it's specified in $expand. :vartype enrollment_details: ~azure.mgmt.billing.models.Enrollment :ivar departments: The departments associated to the enrollment. :vartype departments: list[~azure.mgmt.billing.models.Department] :ivar enrollment_accounts: The accounts associated to the enrollment. :vartype enrollment_accounts: list[~azure.mgmt.billing.models.EnrollmentAccount] :ivar has_read_access: Indicates whether user has read access to the billing account. :vartype has_read_access: bool :ivar notification_email_address: Notification email address, only for legacy accounts. :vartype notification_email_address: str """ _validation = { "id": {"readonly": True}, "name": {"readonly": True}, "type": {"readonly": True}, "agreement_type": {"readonly": True}, "account_type": {"readonly": True}, "account_status": {"readonly": True}, "enrollment_details": {"readonly": True}, "has_read_access": {"readonly": True}, } _attribute_map = { "id": {"key": "id", "type": "str"}, "name": {"key": "name", "type": "str"}, "type": {"key": "type", "type": "str"}, "display_name": {"key": "properties.displayName", "type": "str"}, "sold_to": {"key": "properties.soldTo", "type": "AddressDetails"}, "agreement_type": {"key": "properties.agreementType", "type": "str"}, "account_type": {"key": "properties.accountType", "type": "str"}, "account_status": {"key": "properties.accountStatus", "type": "str"}, "billing_profiles": {"key": "properties.billingProfiles", "type": "BillingProfilesOnExpand"}, "enrollment_details": {"key": "properties.enrollmentDetails", "type": "Enrollment"}, "departments": {"key": "properties.departments", "type": "[Department]"}, "enrollment_accounts": {"key": "properties.enrollmentAccounts", "type": "[EnrollmentAccount]"}, "has_read_access": {"key": "properties.hasReadAccess", "type": "bool"}, "notification_email_address": {"key": "properties.notificationEmailAddress", "type": "str"}, } def __init__( self, *, display_name: Optional[str] = None, sold_to: Optional["_models.AddressDetails"] = None, billing_profiles: Optional["_models.BillingProfilesOnExpand"] = None, departments: Optional[List["_models.Department"]] = None, enrollment_accounts: Optional[List["_models.EnrollmentAccount"]] = None, notification_email_address: Optional[str] = None, **kwargs ): """ :keyword display_name: The billing account name. :paramtype display_name: str :keyword sold_to: The address of the individual or organization that is responsible for the billing account. :paramtype sold_to: ~azure.mgmt.billing.models.AddressDetails :keyword billing_profiles: The billing profiles associated with the billing account. By default this is not populated, unless it's specified in $expand. :paramtype billing_profiles: ~azure.mgmt.billing.models.BillingProfilesOnExpand :keyword departments: The departments associated to the enrollment. :paramtype departments: list[~azure.mgmt.billing.models.Department] :keyword enrollment_accounts: The accounts associated to the enrollment. :paramtype enrollment_accounts: list[~azure.mgmt.billing.models.EnrollmentAccount] :keyword notification_email_address: Notification email address, only for legacy accounts. :paramtype notification_email_address: str """ super().__init__(**kwargs) self.display_name = display_name self.sold_to = sold_to self.agreement_type = None self.account_type = None self.account_status = None self.billing_profiles = billing_profiles self.enrollment_details = None self.departments = departments self.enrollment_accounts = enrollment_accounts self.has_read_access = None self.notification_email_address = notification_email_address class BillingAccountListResult(_serialization.Model): """The list of billing accounts. Variables are only populated by the server, and will be ignored when sending a request. :ivar value: The list of billing accounts. :vartype value: list[~azure.mgmt.billing.models.BillingAccount] :ivar next_link: The link (url) to the next page of results. :vartype next_link: str """ _validation = { "value": {"readonly": True}, "next_link": {"readonly": True}, } _attribute_map = { "value": {"key": "value", "type": "[BillingAccount]"}, "next_link": {"key": "nextLink", "type": "str"}, } def __init__(self, **kwargs): """ """ super().__init__(**kwargs) self.value = None self.next_link = None class BillingAccountUpdateRequest(_serialization.Model): # pylint: disable=too-many-instance-attributes """The request properties of the billing account that can be updated. Variables are only populated by the server, and will be ignored when sending a request. :ivar display_name: The billing account name. :vartype display_name: str :ivar sold_to: The address of the individual or organization that is responsible for the billing account. :vartype sold_to: ~azure.mgmt.billing.models.AddressDetails :ivar agreement_type: The type of agreement. Known values are: "MicrosoftCustomerAgreement", "EnterpriseAgreement", "MicrosoftOnlineServicesProgram", and "MicrosoftPartnerAgreement". :vartype agreement_type: str or ~azure.mgmt.billing.models.AgreementType :ivar account_type: The type of customer. Known values are: "Enterprise", "Individual", and "Partner". :vartype account_type: str or ~azure.mgmt.billing.models.AccountType :ivar account_status: The current status of the billing account. Known values are: "Active", "Deleted", "Disabled", "Expired", "Transferred", "Extended", and "Terminated". :vartype account_status: str or ~azure.mgmt.billing.models.AccountStatus :ivar billing_profiles: The billing profiles associated with the billing account. By default this is not populated, unless it's specified in $expand. :vartype billing_profiles: ~azure.mgmt.billing.models.BillingProfilesOnExpand :ivar enrollment_details: The details about the associated legacy enrollment. By default this is not populated, unless it's specified in $expand. :vartype enrollment_details: ~azure.mgmt.billing.models.Enrollment :ivar departments: The departments associated to the enrollment. :vartype departments: list[~azure.mgmt.billing.models.Department] :ivar enrollment_accounts: The accounts associated to the enrollment. :vartype enrollment_accounts: list[~azure.mgmt.billing.models.EnrollmentAccount] :ivar has_read_access: Indicates whether user has read access to the billing account. :vartype has_read_access: bool :ivar notification_email_address: Notification email address, only for legacy accounts. :vartype notification_email_address: str """ _validation = { "agreement_type": {"readonly": True}, "account_type": {"readonly": True}, "account_status": {"readonly": True}, "enrollment_details": {"readonly": True}, "has_read_access": {"readonly": True}, } _attribute_map = { "display_name": {"key": "properties.displayName", "type": "str"}, "sold_to": {"key": "properties.soldTo", "type": "AddressDetails"}, "agreement_type": {"key": "properties.agreementType", "type": "str"}, "account_type": {"key": "properties.accountType", "type": "str"}, "account_status": {"key": "properties.accountStatus", "type": "str"}, "billing_profiles": {"key": "properties.billingProfiles", "type": "BillingProfilesOnExpand"}, "enrollment_details": {"key": "properties.enrollmentDetails", "type": "Enrollment"}, "departments": {"key": "properties.departments", "type": "[Department]"}, "enrollment_accounts": {"key": "properties.enrollmentAccounts", "type": "[EnrollmentAccount]"}, "has_read_access": {"key": "properties.hasReadAccess", "type": "bool"}, "notification_email_address": {"key": "properties.notificationEmailAddress", "type": "str"}, } def __init__( self, *, display_name: Optional[str] = None, sold_to: Optional["_models.AddressDetails"] = None, billing_profiles: Optional["_models.BillingProfilesOnExpand"] = None, departments: Optional[List["_models.Department"]] = None, enrollment_accounts: Optional[List["_models.EnrollmentAccount"]] = None, notification_email_address: Optional[str] = None, **kwargs ): """ :keyword display_name: The billing account name. :paramtype display_name: str :keyword sold_to: The address of the individual or organization that is responsible for the billing account. :paramtype sold_to: ~azure.mgmt.billing.models.AddressDetails :keyword billing_profiles: The billing profiles associated with the billing account. By default this is not populated, unless it's specified in $expand. :paramtype billing_profiles: ~azure.mgmt.billing.models.BillingProfilesOnExpand :keyword departments: The departments associated to the enrollment. :paramtype departments: list[~azure.mgmt.billing.models.Department] :keyword enrollment_accounts: The accounts associated to the enrollment. :paramtype enrollment_accounts: list[~azure.mgmt.billing.models.EnrollmentAccount] :keyword notification_email_address: Notification email address, only for legacy accounts. :paramtype notification_email_address: str """ super().__init__(**kwargs) self.display_name = display_name self.sold_to = sold_to self.agreement_type = None self.account_type = None self.account_status = None self.billing_profiles = billing_profiles self.enrollment_details = None self.departments = departments self.enrollment_accounts = enrollment_accounts self.has_read_access = None self.notification_email_address = notification_email_address class BillingPeriod(Resource): """A billing period resource. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: Resource Id. :vartype id: str :ivar name: Resource name. :vartype name: str :ivar type: Resource type. :vartype type: str :ivar billing_period_start_date: The start of the date range covered by the billing period. :vartype billing_period_start_date: ~datetime.date :ivar billing_period_end_date: The end of the date range covered by the billing period. :vartype billing_period_end_date: ~datetime.date :ivar invoice_ids: Array of invoice ids that associated with. :vartype invoice_ids: list[str] """ _validation = { "id": {"readonly": True}, "name": {"readonly": True}, "type": {"readonly": True}, "billing_period_start_date": {"readonly": True}, "billing_period_end_date": {"readonly": True}, "invoice_ids": {"readonly": True}, } _attribute_map = { "id": {"key": "id", "type": "str"}, "name": {"key": "name", "type": "str"}, "type": {"key": "type", "type": "str"}, "billing_period_start_date": {"key": "properties.billingPeriodStartDate", "type": "date"}, "billing_period_end_date": {"key": "properties.billingPeriodEndDate", "type": "date"}, "invoice_ids": {"key": "properties.invoiceIds", "type": "[str]"}, } def __init__(self, **kwargs): """ """ super().__init__(**kwargs) self.billing_period_start_date = None self.billing_period_end_date = None self.invoice_ids = None class BillingPeriodsListResult(_serialization.Model): """Result of listing billing periods. It contains a list of available billing periods in reverse chronological order. Variables are only populated by the server, and will be ignored when sending a request. :ivar value: The list of billing periods. :vartype value: list[~azure.mgmt.billing.models.BillingPeriod] :ivar next_link: The link (url) to the next page of results. :vartype next_link: str """ _validation = { "value": {"readonly": True}, "next_link": {"readonly": True}, } _attribute_map = { "value": {"key": "value", "type": "[BillingPeriod]"}, "next_link": {"key": "nextLink", "type": "str"}, } def __init__(self, **kwargs): """ """ super().__init__(**kwargs) self.value = None self.next_link = None class BillingPermissionsListResult(_serialization.Model): """Result of list billingPermissions a caller has on a billing account. Variables are only populated by the server, and will be ignored when sending a request. :ivar value: The list of billingPermissions a caller has on a billing account. :vartype value: list[~azure.mgmt.billing.models.BillingPermissionsProperties] :ivar next_link: The link (url) to the next page of results. :vartype next_link: str """ _validation = { "value": {"readonly": True}, "next_link": {"readonly": True}, } _attribute_map = { "value": {"key": "value", "type": "[BillingPermissionsProperties]"}, "next_link": {"key": "nextLink", "type": "str"}, } def __init__(self, **kwargs): """ """ super().__init__(**kwargs) self.value = None self.next_link = None class BillingPermissionsProperties(_serialization.Model): """The set of allowed action and not allowed actions a caller has on a billing account. Variables are only populated by the server, and will be ignored when sending a request. :ivar actions: The set of actions that the caller is allowed to perform. :vartype actions: list[str] :ivar not_actions: The set of actions that the caller is not allowed to perform. :vartype not_actions: list[str] """ _validation = { "actions": {"readonly": True}, "not_actions": {"readonly": True}, } _attribute_map = { "actions": {"key": "actions", "type": "[str]"}, "not_actions": {"key": "notActions", "type": "[str]"}, } def __init__(self, **kwargs): """ """ super().__init__(**kwargs) self.actions = None self.not_actions = None class BillingProfile(Resource): # pylint: disable=too-many-instance-attributes """A billing profile. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: Resource Id. :vartype id: str :ivar name: Resource name. :vartype name: str :ivar type: Resource type. :vartype type: str :ivar display_name: The name of the billing profile. :vartype display_name: str :ivar po_number: The purchase order name that will appear on the invoices generated for the billing profile. :vartype po_number: str :ivar billing_relationship_type: Identifies which services and purchases are paid by a billing profile. Known values are: "Direct", "IndirectCustomer", "IndirectPartner", and "CSPPartner". :vartype billing_relationship_type: str or ~azure.mgmt.billing.models.BillingRelationshipType :ivar bill_to: Billing address. :vartype bill_to: ~azure.mgmt.billing.models.AddressDetails :ivar indirect_relationship_info: Identifies the billing profile that is linked to another billing profile in indirect purchase motion. :vartype indirect_relationship_info: ~azure.mgmt.billing.models.IndirectRelationshipInfo :ivar invoice_email_opt_in: Flag controlling whether the invoices for the billing profile are sent through email. :vartype invoice_email_opt_in: bool :ivar invoice_day: The day of the month when the invoice for the billing profile is generated. :vartype invoice_day: int :ivar currency: The currency in which the charges for the billing profile are billed. :vartype currency: str :ivar enabled_azure_plans: Information about the enabled azure plans. :vartype enabled_azure_plans: list[~azure.mgmt.billing.models.AzurePlan] :ivar invoice_sections: The invoice sections associated to the billing profile. By default this is not populated, unless it's specified in $expand. :vartype invoice_sections: ~azure.mgmt.billing.models.InvoiceSectionsOnExpand :ivar has_read_access: Indicates whether user has read access to the billing profile. :vartype has_read_access: bool :ivar system_id: The system generated unique identifier for a billing profile. :vartype system_id: str :ivar status: The status of the billing profile. Known values are: "Active", "Disabled", and "Warned". :vartype status: str or ~azure.mgmt.billing.models.BillingProfileStatus :ivar status_reason_code: Reason for the specified billing profile status. Known values are: "PastDue", "SpendingLimitReached", and "SpendingLimitExpired". :vartype status_reason_code: str or ~azure.mgmt.billing.models.StatusReasonCode :ivar spending_limit: The billing profile spending limit. Known values are: "Off" and "On". :vartype spending_limit: str or ~azure.mgmt.billing.models.SpendingLimit :ivar target_clouds: Identifies the cloud environments that are associated with a billing profile. This is a system managed optional field and gets updated as the billing profile gets associated with accounts in various clouds. :vartype target_clouds: list[str or ~azure.mgmt.billing.models.TargetCloud] :ivar tags: Tags of billing profiles. :vartype tags: dict[str, str] """ _validation = { "id": {"readonly": True}, "name": {"readonly": True}, "type": {"readonly": True}, "billing_relationship_type": {"readonly": True}, "indirect_relationship_info": {"readonly": True}, "invoice_day": {"readonly": True}, "currency": {"readonly": True}, "has_read_access": {"readonly": True}, "system_id": {"readonly": True}, "status": {"readonly": True}, "status_reason_code": {"readonly": True}, "spending_limit": {"readonly": True}, "target_clouds": {"readonly": True}, } _attribute_map = { "id": {"key": "id", "type": "str"}, "name": {"key": "name", "type": "str"}, "type": {"key": "type", "type": "str"}, "display_name": {"key": "properties.displayName", "type": "str"}, "po_number": {"key": "properties.poNumber", "type": "str"}, "billing_relationship_type": {"key": "properties.billingRelationshipType", "type": "str"}, "bill_to": {"key": "properties.billTo", "type": "AddressDetails"}, "indirect_relationship_info": { "key": "properties.indirectRelationshipInfo", "type": "IndirectRelationshipInfo", }, "invoice_email_opt_in": {"key": "properties.invoiceEmailOptIn", "type": "bool"}, "invoice_day": {"key": "properties.invoiceDay", "type": "int"}, "currency": {"key": "properties.currency", "type": "str"}, "enabled_azure_plans": {"key": "properties.enabledAzurePlans", "type": "[AzurePlan]"}, "invoice_sections": {"key": "properties.invoiceSections", "type": "InvoiceSectionsOnExpand"}, "has_read_access": {"key": "properties.hasReadAccess", "type": "bool"}, "system_id": {"key": "properties.systemId", "type": "str"}, "status": {"key": "properties.status", "type": "str"}, "status_reason_code": {"key": "properties.statusReasonCode", "type": "str"}, "spending_limit": {"key": "properties.spendingLimit", "type": "str"}, "target_clouds": {"key": "properties.targetClouds", "type": "[str]"}, "tags": {"key": "properties.tags", "type": "{str}"}, } def __init__( self, *, display_name: Optional[str] = None, po_number: Optional[str] = None, bill_to: Optional["_models.AddressDetails"] = None, invoice_email_opt_in: Optional[bool] = None, enabled_azure_plans: Optional[List["_models.AzurePlan"]] = None, invoice_sections: Optional["_models.InvoiceSectionsOnExpand"] = None, tags: Optional[Dict[str, str]] = None, **kwargs ): """ :keyword display_name: The name of the billing profile. :paramtype display_name: str :keyword po_number: The purchase order name that will appear on the invoices generated for the billing profile. :paramtype po_number: str :keyword bill_to: Billing address. :paramtype bill_to: ~azure.mgmt.billing.models.AddressDetails :keyword invoice_email_opt_in: Flag controlling whether the invoices for the billing profile are sent through email. :paramtype invoice_email_opt_in: bool :keyword enabled_azure_plans: Information about the enabled azure plans. :paramtype enabled_azure_plans: list[~azure.mgmt.billing.models.AzurePlan] :keyword invoice_sections: The invoice sections associated to the billing profile. By default this is not populated, unless it's specified in $expand. :paramtype invoice_sections: ~azure.mgmt.billing.models.InvoiceSectionsOnExpand :keyword tags: Tags of billing profiles. :paramtype tags: dict[str, str] """ super().__init__(**kwargs) self.display_name = display_name self.po_number = po_number self.billing_relationship_type = None self.bill_to = bill_to self.indirect_relationship_info = None self.invoice_email_opt_in = invoice_email_opt_in self.invoice_day = None self.currency = None self.enabled_azure_plans = enabled_azure_plans self.invoice_sections = invoice_sections self.has_read_access = None self.system_id = None self.status = None self.status_reason_code = None self.spending_limit = None self.target_clouds = None self.tags = tags class BillingProfileCreationRequest(_serialization.Model): """The request parameters for creating a new billing profile. :ivar display_name: The name of the billing profile. :vartype display_name: str :ivar po_number: The purchase order name that will appear on the invoices generated for the billing profile. :vartype po_number: str :ivar bill_to: The address of the individual or organization that is responsible for the billing profile. :vartype bill_to: ~azure.mgmt.billing.models.AddressDetails :ivar invoice_email_opt_in: Flag controlling whether the invoices for the billing profile are sent through email. :vartype invoice_email_opt_in: bool :ivar enabled_azure_plans: Enabled azure plans for the billing profile. :vartype enabled_azure_plans: list[~azure.mgmt.billing.models.AzurePlan] """ _attribute_map = { "display_name": {"key": "displayName", "type": "str"}, "po_number": {"key": "poNumber", "type": "str"}, "bill_to": {"key": "billTo", "type": "AddressDetails"}, "invoice_email_opt_in": {"key": "invoiceEmailOptIn", "type": "bool"}, "enabled_azure_plans": {"key": "enabledAzurePlans", "type": "[AzurePlan]"}, } def __init__( self, *, display_name: Optional[str] = None, po_number: Optional[str] = None, bill_to: Optional["_models.AddressDetails"] = None, invoice_email_opt_in: Optional[bool] = None, enabled_azure_plans: Optional[List["_models.AzurePlan"]] = None, **kwargs ): """ :keyword display_name: The name of the billing profile. :paramtype display_name: str :keyword po_number: The purchase order name that will appear on the invoices generated for the billing profile. :paramtype po_number: str :keyword bill_to: The address of the individual or organization that is responsible for the billing profile. :paramtype bill_to: ~azure.mgmt.billing.models.AddressDetails :keyword invoice_email_opt_in: Flag controlling whether the invoices for the billing profile are sent through email. :paramtype invoice_email_opt_in: bool :keyword enabled_azure_plans: Enabled azure plans for the billing profile. :paramtype enabled_azure_plans: list[~azure.mgmt.billing.models.AzurePlan] """ super().__init__(**kwargs) self.display_name = display_name self.po_number = po_number self.bill_to = bill_to self.invoice_email_opt_in = invoice_email_opt_in self.enabled_azure_plans = enabled_azure_plans class BillingProfileInfo(_serialization.Model): """Details about billing profile associated with agreement and available only for specific agreements. :ivar billing_profile_id: The unique identifier for the billing profile. :vartype billing_profile_id: str :ivar billing_profile_display_name: The name of the billing profile. :vartype billing_profile_display_name: str :ivar indirect_relationship_organization_name: Billing account name. This property is available for a specific type of agreement. :vartype indirect_relationship_organization_name: str """ _attribute_map = { "billing_profile_id": {"key": "billingProfileId", "type": "str"}, "billing_profile_display_name": {"key": "billingProfileDisplayName", "type": "str"}, "indirect_relationship_organization_name": {"key": "indirectRelationshipOrganizationName", "type": "str"}, } def __init__( self, *, billing_profile_id: Optional[str] = None, billing_profile_display_name: Optional[str] = None, indirect_relationship_organization_name: Optional[str] = None, **kwargs ): """ :keyword billing_profile_id: The unique identifier for the billing profile. :paramtype billing_profile_id: str :keyword billing_profile_display_name: The name of the billing profile. :paramtype billing_profile_display_name: str :keyword indirect_relationship_organization_name: Billing account name. This property is available for a specific type of agreement. :paramtype indirect_relationship_organization_name: str """ super().__init__(**kwargs) self.billing_profile_id = billing_profile_id self.billing_profile_display_name = billing_profile_display_name self.indirect_relationship_organization_name = indirect_relationship_organization_name class BillingProfileListResult(_serialization.Model): """The list of billing profiles. Variables are only populated by the server, and will be ignored when sending a request. :ivar value: The list of billing profiles. :vartype value: list[~azure.mgmt.billing.models.BillingProfile] :ivar total_count: Total number of records. :vartype total_count: int :ivar next_link: The link (url) to the next page of results. :vartype next_link: str """ _validation = { "value": {"readonly": True}, "total_count": {"readonly": True}, "next_link": {"readonly": True}, } _attribute_map = { "value": {"key": "value", "type": "[BillingProfile]"}, "total_count": {"key": "totalCount", "type": "int"}, "next_link": {"key": "nextLink", "type": "str"}, } def __init__(self, **kwargs): """ """ super().__init__(**kwargs) self.value = None self.total_count = None self.next_link = None class BillingProfilesOnExpand(_serialization.Model): """The billing profiles associated with the billing account. By default this is not populated, unless it's specified in $expand. Variables are only populated by the server, and will be ignored when sending a request. :ivar has_more_results: Indicates whether there are more billing profiles than the ones listed in this collection. The collection lists a maximum of 50 billing profiles. To get all billing profiles, use the list billing profiles API. :vartype has_more_results: bool :ivar value: The billing profiles associated with the billing account. :vartype value: list[~azure.mgmt.billing.models.BillingProfile] """ _validation = { "has_more_results": {"readonly": True}, } _attribute_map = { "has_more_results": {"key": "hasMoreResults", "type": "bool"}, "value": {"key": "value", "type": "[BillingProfile]"}, } def __init__(self, *, value: Optional[List["_models.BillingProfile"]] = None, **kwargs): """ :keyword value: The billing profiles associated with the billing account. :paramtype value: list[~azure.mgmt.billing.models.BillingProfile] """ super().__init__(**kwargs) self.has_more_results = None self.value = value class BillingProperty(Resource): # pylint: disable=too-many-instance-attributes """A billing property. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: Resource Id. :vartype id: str :ivar name: Resource name. :vartype name: str :ivar type: Resource type. :vartype type: str :ivar account_admin_notification_email_address: The email address on which the account admin gets all Azure notifications. :vartype account_admin_notification_email_address: str :ivar billing_tenant_id: The Azure AD tenant ID of the billing account for the subscription. :vartype billing_tenant_id: str :ivar billing_account_id: The ID of the billing account to which the subscription is billed. :vartype billing_account_id: str :ivar billing_account_display_name: The name of the billing account to which the subscription is billed. :vartype billing_account_display_name: str :ivar billing_profile_id: The ID of the billing profile to which the subscription is billed. :vartype billing_profile_id: str :ivar billing_profile_display_name: The name of the billing profile to which the subscription is billed. :vartype billing_profile_display_name: str :ivar billing_profile_status: The status of the billing profile. Known values are: "Active", "Disabled", and "Warned". :vartype billing_profile_status: str or ~azure.mgmt.billing.models.BillingProfileStatus :ivar billing_profile_status_reason_code: Reason for the specified billing profile status. Known values are: "PastDue", "SpendingLimitReached", and "SpendingLimitExpired". :vartype billing_profile_status_reason_code: str or ~azure.mgmt.billing.models.BillingProfileStatusReasonCode :ivar billing_profile_spending_limit: The billing profile spending limit. Known values are: "Off" and "On". :vartype billing_profile_spending_limit: str or ~azure.mgmt.billing.models.BillingProfileSpendingLimit :ivar cost_center: The cost center applied to the subscription. :vartype cost_center: str :ivar invoice_section_id: The ID of the invoice section to which the subscription is billed. :vartype invoice_section_id: str :ivar invoice_section_display_name: The name of the invoice section to which the subscription is billed. :vartype invoice_section_display_name: str :ivar is_account_admin: Indicates whether user is the account admin. :vartype is_account_admin: bool :ivar product_id: The product ID of the Azure plan. :vartype product_id: str :ivar product_name: The product name of the Azure plan. :vartype product_name: str :ivar sku_id: The sku ID of the Azure plan for the subscription. :vartype sku_id: str :ivar sku_description: The sku description of the Azure plan for the subscription. :vartype sku_description: str """ _validation = { "id": {"readonly": True}, "name": {"readonly": True}, "type": {"readonly": True}, "account_admin_notification_email_address": {"readonly": True}, "billing_tenant_id": {"readonly": True}, "billing_account_id": {"readonly": True}, "billing_account_display_name": {"readonly": True}, "billing_profile_id": {"readonly": True}, "billing_profile_display_name": {"readonly": True}, "billing_profile_status": {"readonly": True}, "billing_profile_status_reason_code": {"readonly": True}, "billing_profile_spending_limit": {"readonly": True}, "invoice_section_id": {"readonly": True}, "invoice_section_display_name": {"readonly": True}, "is_account_admin": {"readonly": True}, "product_id": {"readonly": True}, "product_name": {"readonly": True}, "sku_id": {"readonly": True}, "sku_description": {"readonly": True}, } _attribute_map = { "id": {"key": "id", "type": "str"}, "name": {"key": "name", "type": "str"}, "type": {"key": "type", "type": "str"}, "account_admin_notification_email_address": { "key": "properties.accountAdminNotificationEmailAddress", "type": "str", }, "billing_tenant_id": {"key": "properties.billingTenantId", "type": "str"}, "billing_account_id": {"key": "properties.billingAccountId", "type": "str"}, "billing_account_display_name": {"key": "properties.billingAccountDisplayName", "type": "str"}, "billing_profile_id": {"key": "properties.billingProfileId", "type": "str"}, "billing_profile_display_name": {"key": "properties.billingProfileDisplayName", "type": "str"}, "billing_profile_status": {"key": "properties.billingProfileStatus", "type": "str"}, "billing_profile_status_reason_code": {"key": "properties.billingProfileStatusReasonCode", "type": "str"}, "billing_profile_spending_limit": {"key": "properties.billingProfileSpendingLimit", "type": "str"}, "cost_center": {"key": "properties.costCenter", "type": "str"}, "invoice_section_id": {"key": "properties.invoiceSectionId", "type": "str"}, "invoice_section_display_name": {"key": "properties.invoiceSectionDisplayName", "type": "str"}, "is_account_admin": {"key": "properties.isAccountAdmin", "type": "bool"}, "product_id": {"key": "properties.productId", "type": "str"}, "product_name": {"key": "properties.productName", "type": "str"}, "sku_id": {"key": "properties.skuId", "type": "str"}, "sku_description": {"key": "properties.skuDescription", "type": "str"}, } def __init__(self, *, cost_center: Optional[str] = None, **kwargs): """ :keyword cost_center: The cost center applied to the subscription. :paramtype cost_center: str """ super().__init__(**kwargs) self.account_admin_notification_email_address = None self.billing_tenant_id = None self.billing_account_id = None self.billing_account_display_name = None self.billing_profile_id = None self.billing_profile_display_name = None self.billing_profile_status = None self.billing_profile_status_reason_code = None self.billing_profile_spending_limit = None self.cost_center = cost_center self.invoice_section_id = None self.invoice_section_display_name = None self.is_account_admin = None self.product_id = None self.product_name = None self.sku_id = None self.sku_description = None class BillingRoleAssignment(Resource): # pylint: disable=too-many-instance-attributes """The role assignment. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: Resource Id. :vartype id: str :ivar name: Resource name. :vartype name: str :ivar type: Resource type. :vartype type: str :ivar created_on: The date the role assignment was created. :vartype created_on: str :ivar created_by_principal_tenant_id: The tenant Id of the user who created the role assignment. :vartype created_by_principal_tenant_id: str :ivar created_by_principal_id: The principal Id of the user who created the role assignment. :vartype created_by_principal_id: str :ivar created_by_user_email_address: The email address of the user who created the role assignment. :vartype created_by_user_email_address: str :ivar principal_id: The principal id of the user to whom the role was assigned. :vartype principal_id: str :ivar principal_tenant_id: The principal tenant id of the user to whom the role was assigned. :vartype principal_tenant_id: str :ivar role_definition_id: The ID of the role definition. :vartype role_definition_id: str :ivar scope: The scope at which the role was assigned. :vartype scope: str :ivar user_authentication_type: The authentication type. :vartype user_authentication_type: str :ivar user_email_address: The email address of the user. :vartype user_email_address: str """ _validation = { "id": {"readonly": True}, "name": {"readonly": True}, "type": {"readonly": True}, "created_on": {"readonly": True}, "created_by_principal_tenant_id": {"readonly": True}, "created_by_principal_id": {"readonly": True}, "created_by_user_email_address": {"readonly": True}, "scope": {"readonly": True}, } _attribute_map = { "id": {"key": "id", "type": "str"}, "name": {"key": "name", "type": "str"}, "type": {"key": "type", "type": "str"}, "created_on": {"key": "properties.createdOn", "type": "str"}, "created_by_principal_tenant_id": {"key": "properties.createdByPrincipalTenantId", "type": "str"}, "created_by_principal_id": {"key": "properties.createdByPrincipalId", "type": "str"}, "created_by_user_email_address": {"key": "properties.createdByUserEmailAddress", "type": "str"}, "principal_id": {"key": "properties.principalId", "type": "str"}, "principal_tenant_id": {"key": "properties.principalTenantId", "type": "str"}, "role_definition_id": {"key": "properties.roleDefinitionId", "type": "str"}, "scope": {"key": "properties.scope", "type": "str"}, "user_authentication_type": {"key": "properties.userAuthenticationType", "type": "str"}, "user_email_address": {"key": "properties.userEmailAddress", "type": "str"}, } def __init__( self, *, principal_id: Optional[str] = None, principal_tenant_id: Optional[str] = None, role_definition_id: Optional[str] = None, user_authentication_type: Optional[str] = None, user_email_address: Optional[str] = None, **kwargs ): """ :keyword principal_id: The principal id of the user to whom the role was assigned. :paramtype principal_id: str :keyword principal_tenant_id: The principal tenant id of the user to whom the role was assigned. :paramtype principal_tenant_id: str :keyword role_definition_id: The ID of the role definition. :paramtype role_definition_id: str :keyword user_authentication_type: The authentication type. :paramtype user_authentication_type: str :keyword user_email_address: The email address of the user. :paramtype user_email_address: str """ super().__init__(**kwargs) self.created_on = None self.created_by_principal_tenant_id = None self.created_by_principal_id = None self.created_by_user_email_address = None self.principal_id = principal_id self.principal_tenant_id = principal_tenant_id self.role_definition_id = role_definition_id self.scope = None self.user_authentication_type = user_authentication_type self.user_email_address = user_email_address class BillingRoleAssignmentListResult(_serialization.Model): """The list of role assignments. Variables are only populated by the server, and will be ignored when sending a request. :ivar value: The list of role assignments. :vartype value: list[~azure.mgmt.billing.models.BillingRoleAssignment] :ivar next_link: The link (url) to the next page of results. :vartype next_link: str """ _validation = { "value": {"readonly": True}, "next_link": {"readonly": True}, } _attribute_map = { "value": {"key": "value", "type": "[BillingRoleAssignment]"}, "next_link": {"key": "nextLink", "type": "str"}, } def __init__(self, **kwargs): """ """ super().__init__(**kwargs) self.value = None self.next_link = None class BillingRoleDefinition(Resource): """The properties of a role definition. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: Resource Id. :vartype id: str :ivar name: Resource name. :vartype name: str :ivar type: Resource type. :vartype type: str :ivar description: The role description. :vartype description: str :ivar permissions: The billingPermissions the role has. :vartype permissions: list[~azure.mgmt.billing.models.BillingPermissionsProperties] :ivar role_name: The name of the role. :vartype role_name: str """ _validation = { "id": {"readonly": True}, "name": {"readonly": True}, "type": {"readonly": True}, "description": {"readonly": True}, "role_name": {"readonly": True}, } _attribute_map = { "id": {"key": "id", "type": "str"}, "name": {"key": "name", "type": "str"}, "type": {"key": "type", "type": "str"}, "description": {"key": "properties.description", "type": "str"}, "permissions": {"key": "properties.permissions", "type": "[BillingPermissionsProperties]"}, "role_name": {"key": "properties.roleName", "type": "str"}, } def __init__(self, *, permissions: Optional[List["_models.BillingPermissionsProperties"]] = None, **kwargs): """ :keyword permissions: The billingPermissions the role has. :paramtype permissions: list[~azure.mgmt.billing.models.BillingPermissionsProperties] """ super().__init__(**kwargs) self.description = None self.permissions = permissions self.role_name = None class BillingRoleDefinitionListResult(_serialization.Model): """The list of role definitions. Variables are only populated by the server, and will be ignored when sending a request. :ivar value: The role definitions. :vartype value: list[~azure.mgmt.billing.models.BillingRoleDefinition] :ivar next_link: The link (url) to the next page of results. :vartype next_link: str """ _validation = { "value": {"readonly": True}, "next_link": {"readonly": True}, } _attribute_map = { "value": {"key": "value", "type": "[BillingRoleDefinition]"}, "next_link": {"key": "nextLink", "type": "str"}, } def __init__(self, **kwargs): """ """ super().__init__(**kwargs) self.value = None self.next_link = None class BillingSubscription(Resource): # pylint: disable=too-many-instance-attributes """A billing subscription. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: Resource Id. :vartype id: str :ivar name: Resource name. :vartype name: str :ivar type: Resource type. :vartype type: str :ivar display_name: The name of the subscription. :vartype display_name: str :ivar subscription_id: The ID of the subscription. :vartype subscription_id: str :ivar subscription_billing_status: The current billing status of the subscription. Known values are: "Active", "Inactive", "Abandoned", "Deleted", and "Warning". :vartype subscription_billing_status: str or ~azure.mgmt.billing.models.BillingSubscriptionStatusType :ivar last_month_charges: The last month charges. :vartype last_month_charges: ~azure.mgmt.billing.models.Amount :ivar month_to_date_charges: The current month to date charges. :vartype month_to_date_charges: ~azure.mgmt.billing.models.Amount :ivar billing_profile_id: The ID of the billing profile to which the subscription is billed. :vartype billing_profile_id: str :ivar billing_profile_display_name: The name of the billing profile to which the subscription is billed. :vartype billing_profile_display_name: str :ivar cost_center: The cost center applied to the subscription. :vartype cost_center: str :ivar customer_id: The ID of the customer for whom the subscription was created. The field is applicable only for Microsoft Partner Agreement billing account. :vartype customer_id: str :ivar customer_display_name: The name of the customer for whom the subscription was created. The field is applicable only for Microsoft Partner Agreement billing account. :vartype customer_display_name: str :ivar invoice_section_id: The ID of the invoice section to which the subscription is billed. :vartype invoice_section_id: str :ivar invoice_section_display_name: The name of the invoice section to which the subscription is billed. :vartype invoice_section_display_name: str :ivar reseller: Reseller for this subscription. :vartype reseller: ~azure.mgmt.billing.models.Reseller :ivar sku_id: The sku ID of the Azure plan for the subscription. :vartype sku_id: str :ivar sku_description: The sku description of the Azure plan for the subscription. :vartype sku_description: str :ivar suspension_reasons: The suspension reason for a subscription. Applies only to subscriptions in Microsoft Online Services Program billing accounts. :vartype suspension_reasons: list[str] """ _validation = { "id": {"readonly": True}, "name": {"readonly": True}, "type": {"readonly": True}, "display_name": {"readonly": True}, "subscription_id": {"readonly": True}, "last_month_charges": {"readonly": True}, "month_to_date_charges": {"readonly": True}, "billing_profile_id": {"readonly": True}, "billing_profile_display_name": {"readonly": True}, "customer_id": {"readonly": True}, "customer_display_name": {"readonly": True}, "invoice_section_id": {"readonly": True}, "invoice_section_display_name": {"readonly": True}, "reseller": {"readonly": True}, "sku_description": {"readonly": True}, "suspension_reasons": {"readonly": True}, } _attribute_map = { "id": {"key": "id", "type": "str"}, "name": {"key": "name", "type": "str"}, "type": {"key": "type", "type": "str"}, "display_name": {"key": "properties.displayName", "type": "str"}, "subscription_id": {"key": "properties.subscriptionId", "type": "str"}, "subscription_billing_status": {"key": "properties.subscriptionBillingStatus", "type": "str"}, "last_month_charges": {"key": "properties.lastMonthCharges", "type": "Amount"}, "month_to_date_charges": {"key": "properties.monthToDateCharges", "type": "Amount"}, "billing_profile_id": {"key": "properties.billingProfileId", "type": "str"}, "billing_profile_display_name": {"key": "properties.billingProfileDisplayName", "type": "str"}, "cost_center": {"key": "properties.costCenter", "type": "str"}, "customer_id": {"key": "properties.customerId", "type": "str"}, "customer_display_name": {"key": "properties.customerDisplayName", "type": "str"}, "invoice_section_id": {"key": "properties.invoiceSectionId", "type": "str"}, "invoice_section_display_name": {"key": "properties.invoiceSectionDisplayName", "type": "str"}, "reseller": {"key": "properties.reseller", "type": "Reseller"}, "sku_id": {"key": "properties.skuId", "type": "str"}, "sku_description": {"key": "properties.skuDescription", "type": "str"}, "suspension_reasons": {"key": "properties.suspensionReasons", "type": "[str]"}, } def __init__( self, *, subscription_billing_status: Optional[Union[str, "_models.BillingSubscriptionStatusType"]] = None, cost_center: Optional[str] = None, sku_id: Optional[str] = None, **kwargs ): """ :keyword subscription_billing_status: The current billing status of the subscription. Known values are: "Active", "Inactive", "Abandoned", "Deleted", and "Warning". :paramtype subscription_billing_status: str or ~azure.mgmt.billing.models.BillingSubscriptionStatusType :keyword cost_center: The cost center applied to the subscription. :paramtype cost_center: str :keyword sku_id: The sku ID of the Azure plan for the subscription. :paramtype sku_id: str """ super().__init__(**kwargs) self.display_name = None self.subscription_id = None self.subscription_billing_status = subscription_billing_status self.last_month_charges = None self.month_to_date_charges = None self.billing_profile_id = None self.billing_profile_display_name = None self.cost_center = cost_center self.customer_id = None self.customer_display_name = None self.invoice_section_id = None self.invoice_section_display_name = None self.reseller = None self.sku_id = sku_id self.sku_description = None self.suspension_reasons = None class BillingSubscriptionsListResult(_serialization.Model): """The list of billing subscriptions. Variables are only populated by the server, and will be ignored when sending a request. :ivar value: The list of billing subscriptions. :vartype value: list[~azure.mgmt.billing.models.BillingSubscription] :ivar total_count: Total number of records. :vartype total_count: int :ivar next_link: The link (url) to the next page of results. :vartype next_link: str """ _validation = { "value": {"readonly": True}, "total_count": {"readonly": True}, "next_link": {"readonly": True}, } _attribute_map = { "value": {"key": "value", "type": "[BillingSubscription]"}, "total_count": {"key": "totalCount", "type": "int"}, "next_link": {"key": "nextLink", "type": "str"}, } def __init__(self, **kwargs): """ """ super().__init__(**kwargs) self.value = None self.total_count = None self.next_link = None class Customer(Resource): """A partner's customer. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: Resource Id. :vartype id: str :ivar name: Resource name. :vartype name: str :ivar type: Resource type. :vartype type: str :ivar billing_profile_id: The ID of the billing profile for the invoice section. :vartype billing_profile_id: str :ivar billing_profile_display_name: The name of the billing profile for the invoice section. :vartype billing_profile_display_name: str :ivar display_name: The name of the customer. :vartype display_name: str :ivar enabled_azure_plans: Azure plans enabled for the customer. :vartype enabled_azure_plans: list[~azure.mgmt.billing.models.AzurePlan] :ivar resellers: The list of resellers for which an Azure plan is enabled for the customer. :vartype resellers: list[~azure.mgmt.billing.models.Reseller] """ _validation = { "id": {"readonly": True}, "name": {"readonly": True}, "type": {"readonly": True}, "billing_profile_id": {"readonly": True}, "billing_profile_display_name": {"readonly": True}, } _attribute_map = { "id": {"key": "id", "type": "str"}, "name": {"key": "name", "type": "str"}, "type": {"key": "type", "type": "str"}, "billing_profile_id": {"key": "properties.billingProfileId", "type": "str"}, "billing_profile_display_name": {"key": "properties.billingProfileDisplayName", "type": "str"}, "display_name": {"key": "properties.displayName", "type": "str"}, "enabled_azure_plans": {"key": "properties.enabledAzurePlans", "type": "[AzurePlan]"}, "resellers": {"key": "properties.resellers", "type": "[Reseller]"}, } def __init__( self, *, display_name: Optional[str] = None, enabled_azure_plans: Optional[List["_models.AzurePlan"]] = None, resellers: Optional[List["_models.Reseller"]] = None, **kwargs ): """ :keyword display_name: The name of the customer. :paramtype display_name: str :keyword enabled_azure_plans: Azure plans enabled for the customer. :paramtype enabled_azure_plans: list[~azure.mgmt.billing.models.AzurePlan] :keyword resellers: The list of resellers for which an Azure plan is enabled for the customer. :paramtype resellers: list[~azure.mgmt.billing.models.Reseller] """ super().__init__(**kwargs) self.billing_profile_id = None self.billing_profile_display_name = None self.display_name = display_name self.enabled_azure_plans = enabled_azure_plans self.resellers = resellers class CustomerListResult(_serialization.Model): """The list of customers. Variables are only populated by the server, and will be ignored when sending a request. :ivar value: The list of customers. :vartype value: list[~azure.mgmt.billing.models.Customer] :ivar total_count: Total number of records. :vartype total_count: int :ivar next_link: The link (url) to the next page of results. :vartype next_link: str """ _validation = { "value": {"readonly": True}, "total_count": {"readonly": True}, "next_link": {"readonly": True}, } _attribute_map = { "value": {"key": "value", "type": "[Customer]"}, "total_count": {"key": "totalCount", "type": "int"}, "next_link": {"key": "nextLink", "type": "str"}, } def __init__(self, **kwargs): """ """ super().__init__(**kwargs) self.value = None self.total_count = None self.next_link = None class CustomerPolicy(Resource): """The customer's Policy. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: Resource Id. :vartype id: str :ivar name: Resource name. :vartype name: str :ivar type: Resource type. :vartype type: str :ivar view_charges: The policy that controls whether the users in customer's organization can view charges at pay-as-you-go prices. Known values are: "Allowed" and "NotAllowed". :vartype view_charges: str or ~azure.mgmt.billing.models.ViewCharges """ _validation = { "id": {"readonly": True}, "name": {"readonly": True}, "type": {"readonly": True}, } _attribute_map = { "id": {"key": "id", "type": "str"}, "name": {"key": "name", "type": "str"}, "type": {"key": "type", "type": "str"}, "view_charges": {"key": "properties.viewCharges", "type": "str"}, } def __init__(self, *, view_charges: Optional[Union[str, "_models.ViewCharges"]] = None, **kwargs): """ :keyword view_charges: The policy that controls whether the users in customer's organization can view charges at pay-as-you-go prices. Known values are: "Allowed" and "NotAllowed". :paramtype view_charges: str or ~azure.mgmt.billing.models.ViewCharges """ super().__init__(**kwargs) self.view_charges = view_charges class Department(Resource): """A department. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: Resource Id. :vartype id: str :ivar name: Resource name. :vartype name: str :ivar type: Resource type. :vartype type: str :ivar department_name: The name of the department. :vartype department_name: str :ivar cost_center: The cost center associated with the department. :vartype cost_center: str :ivar status: The status of the department. :vartype status: str :ivar enrollment_accounts: Associated enrollment accounts. By default this is not populated, unless it's specified in $expand. :vartype enrollment_accounts: list[~azure.mgmt.billing.models.EnrollmentAccount] """ _validation = { "id": {"readonly": True}, "name": {"readonly": True}, "type": {"readonly": True}, } _attribute_map = { "id": {"key": "id", "type": "str"}, "name": {"key": "name", "type": "str"}, "type": {"key": "type", "type": "str"}, "department_name": {"key": "properties.departmentName", "type": "str"}, "cost_center": {"key": "properties.costCenter", "type": "str"}, "status": {"key": "properties.status", "type": "str"}, "enrollment_accounts": {"key": "properties.enrollmentAccounts", "type": "[EnrollmentAccount]"}, } def __init__( self, *, department_name: Optional[str] = None, cost_center: Optional[str] = None, status: Optional[str] = None, enrollment_accounts: Optional[List["_models.EnrollmentAccount"]] = None, **kwargs ): """ :keyword department_name: The name of the department. :paramtype department_name: str :keyword cost_center: The cost center associated with the department. :paramtype cost_center: str :keyword status: The status of the department. :paramtype status: str :keyword enrollment_accounts: Associated enrollment accounts. By default this is not populated, unless it's specified in $expand. :paramtype enrollment_accounts: list[~azure.mgmt.billing.models.EnrollmentAccount] """ super().__init__(**kwargs) self.department_name = department_name self.cost_center = cost_center self.status = status self.enrollment_accounts = enrollment_accounts class Document(_serialization.Model): """The properties of a document. Variables are only populated by the server, and will be ignored when sending a request. :ivar kind: The type of the document. Known values are: "Invoice", "VoidNote", "TaxReceipt", and "CreditNote". :vartype kind: str or ~azure.mgmt.billing.models.DocumentType :ivar url: Document URL. :vartype url: str :ivar source: The source of the document. ENF for Brazil and DRS for rest of the world. Known values are: "DRS" and "ENF". :vartype source: str or ~azure.mgmt.billing.models.DocumentSource """ _validation = { "kind": {"readonly": True}, "url": {"readonly": True}, "source": {"readonly": True}, } _attribute_map = { "kind": {"key": "kind", "type": "str"}, "url": {"key": "url", "type": "str"}, "source": {"key": "source", "type": "str"}, } def __init__(self, **kwargs): """ """ super().__init__(**kwargs) self.kind = None self.url = None self.source = None class DownloadUrl(_serialization.Model): """A secure URL that can be used to download a an entity until the URL expires. Variables are only populated by the server, and will be ignored when sending a request. :ivar expiry_time: The time in UTC when the download URL will expire. :vartype expiry_time: ~datetime.datetime :ivar url: The URL to the PDF file. :vartype url: str """ _validation = { "expiry_time": {"readonly": True}, "url": {"readonly": True}, } _attribute_map = { "expiry_time": {"key": "expiryTime", "type": "iso-8601"}, "url": {"key": "url", "type": "str"}, } def __init__(self, **kwargs): """ """ super().__init__(**kwargs) self.expiry_time = None self.url = None class Enrollment(_serialization.Model): """The properties of an enrollment. Variables are only populated by the server, and will be ignored when sending a request. :ivar start_date: The start date of the enrollment. :vartype start_date: ~datetime.datetime :ivar end_date: The end date of the enrollment. :vartype end_date: ~datetime.datetime :ivar currency: The billing currency for the enrollment. :vartype currency: str :ivar channel: The channel type of the enrollment. :vartype channel: str :ivar policies: The policies for Enterprise Agreement enrollments. :vartype policies: ~azure.mgmt.billing.models.EnrollmentPolicies :ivar language: The language for the enrollment. :vartype language: str :ivar country_code: The country code of the enrollment. :vartype country_code: str :ivar status: The current status of the enrollment. :vartype status: str :ivar billing_cycle: The billing cycle for the enrollment. :vartype billing_cycle: str """ _validation = { "currency": {"readonly": True}, "channel": {"readonly": True}, "policies": {"readonly": True}, "language": {"readonly": True}, "country_code": {"readonly": True}, "status": {"readonly": True}, "billing_cycle": {"readonly": True}, } _attribute_map = { "start_date": {"key": "startDate", "type": "iso-8601"}, "end_date": {"key": "endDate", "type": "iso-8601"}, "currency": {"key": "currency", "type": "str"}, "channel": {"key": "channel", "type": "str"}, "policies": {"key": "policies", "type": "EnrollmentPolicies"}, "language": {"key": "language", "type": "str"}, "country_code": {"key": "countryCode", "type": "str"}, "status": {"key": "status", "type": "str"}, "billing_cycle": {"key": "billingCycle", "type": "str"}, } def __init__( self, *, start_date: Optional[datetime.datetime] = None, end_date: Optional[datetime.datetime] = None, **kwargs ): """ :keyword start_date: The start date of the enrollment. :paramtype start_date: ~datetime.datetime :keyword end_date: The end date of the enrollment. :paramtype end_date: ~datetime.datetime """ super().__init__(**kwargs) self.start_date = start_date self.end_date = end_date self.currency = None self.channel = None self.policies = None self.language = None self.country_code = None self.status = None self.billing_cycle = None class EnrollmentAccount(Resource): # pylint: disable=too-many-instance-attributes """An enrollment account. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: Resource Id. :vartype id: str :ivar name: Resource name. :vartype name: str :ivar type: Resource type. :vartype type: str :ivar account_name: The name of the enrollment account. :vartype account_name: str :ivar cost_center: The cost center associated with the enrollment account. :vartype cost_center: str :ivar account_owner: The owner of the enrollment account. :vartype account_owner: str :ivar account_owner_email: The enrollment account owner email address. :vartype account_owner_email: str :ivar status: The status of the enrollment account. :vartype status: str :ivar start_date: The start date of the enrollment account. :vartype start_date: ~datetime.datetime :ivar end_date: The end date of the enrollment account. :vartype end_date: ~datetime.datetime :ivar department: Associated department. By default this is not populated, unless it's specified in $expand. :vartype department: ~azure.mgmt.billing.models.Department """ _validation = { "id": {"readonly": True}, "name": {"readonly": True}, "type": {"readonly": True}, } _attribute_map = { "id": {"key": "id", "type": "str"}, "name": {"key": "name", "type": "str"}, "type": {"key": "type", "type": "str"}, "account_name": {"key": "properties.accountName", "type": "str"}, "cost_center": {"key": "properties.costCenter", "type": "str"}, "account_owner": {"key": "properties.accountOwner", "type": "str"}, "account_owner_email": {"key": "properties.accountOwnerEmail", "type": "str"}, "status": {"key": "properties.status", "type": "str"}, "start_date": {"key": "properties.startDate", "type": "iso-8601"}, "end_date": {"key": "properties.endDate", "type": "iso-8601"}, "department": {"key": "properties.department", "type": "Department"}, } def __init__( self, *, account_name: Optional[str] = None, cost_center: Optional[str] = None, account_owner: Optional[str] = None, account_owner_email: Optional[str] = None, status: Optional[str] = None, start_date: Optional[datetime.datetime] = None, end_date: Optional[datetime.datetime] = None, department: Optional["_models.Department"] = None, **kwargs ): """ :keyword account_name: The name of the enrollment account. :paramtype account_name: str :keyword cost_center: The cost center associated with the enrollment account. :paramtype cost_center: str :keyword account_owner: The owner of the enrollment account. :paramtype account_owner: str :keyword account_owner_email: The enrollment account owner email address. :paramtype account_owner_email: str :keyword status: The status of the enrollment account. :paramtype status: str :keyword start_date: The start date of the enrollment account. :paramtype start_date: ~datetime.datetime :keyword end_date: The end date of the enrollment account. :paramtype end_date: ~datetime.datetime :keyword department: Associated department. By default this is not populated, unless it's specified in $expand. :paramtype department: ~azure.mgmt.billing.models.Department """ super().__init__(**kwargs) self.account_name = account_name self.cost_center = cost_center self.account_owner = account_owner self.account_owner_email = account_owner_email self.status = status self.start_date = start_date self.end_date = end_date self.department = department class EnrollmentAccountContext(_serialization.Model): """The enrollment account context. :ivar cost_center: The cost center associated with the enrollment account. :vartype cost_center: str :ivar start_date: The start date of the enrollment account. :vartype start_date: ~datetime.datetime :ivar end_date: The end date of the enrollment account. :vartype end_date: ~datetime.datetime :ivar enrollment_account_name: The ID of the enrollment account. :vartype enrollment_account_name: str """ _attribute_map = { "cost_center": {"key": "costCenter", "type": "str"}, "start_date": {"key": "startDate", "type": "iso-8601"}, "end_date": {"key": "endDate", "type": "iso-8601"}, "enrollment_account_name": {"key": "enrollmentAccountName", "type": "str"}, } def __init__( self, *, cost_center: Optional[str] = None, start_date: Optional[datetime.datetime] = None, end_date: Optional[datetime.datetime] = None, enrollment_account_name: Optional[str] = None, **kwargs ): """ :keyword cost_center: The cost center associated with the enrollment account. :paramtype cost_center: str :keyword start_date: The start date of the enrollment account. :paramtype start_date: ~datetime.datetime :keyword end_date: The end date of the enrollment account. :paramtype end_date: ~datetime.datetime :keyword enrollment_account_name: The ID of the enrollment account. :paramtype enrollment_account_name: str """ super().__init__(**kwargs) self.cost_center = cost_center self.start_date = start_date self.end_date = end_date self.enrollment_account_name = enrollment_account_name class EnrollmentAccountListResult(_serialization.Model): """Result of listing enrollment accounts. Variables are only populated by the server, and will be ignored when sending a request. :ivar value: The list of enrollment accounts. :vartype value: list[~azure.mgmt.billing.models.EnrollmentAccountSummary] :ivar next_link: The link (url) to the next page of results. :vartype next_link: str """ _validation = { "value": {"readonly": True}, "next_link": {"readonly": True}, } _attribute_map = { "value": {"key": "value", "type": "[EnrollmentAccountSummary]"}, "next_link": {"key": "nextLink", "type": "str"}, } def __init__(self, **kwargs): """ """ super().__init__(**kwargs) self.value = None self.next_link = None class EnrollmentAccountSummary(Resource): """An enrollment account resource. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: Resource Id. :vartype id: str :ivar name: Resource name. :vartype name: str :ivar type: Resource type. :vartype type: str :ivar principal_name: The account owner's principal name. :vartype principal_name: str """ _validation = { "id": {"readonly": True}, "name": {"readonly": True}, "type": {"readonly": True}, "principal_name": {"readonly": True}, } _attribute_map = { "id": {"key": "id", "type": "str"}, "name": {"key": "name", "type": "str"}, "type": {"key": "type", "type": "str"}, "principal_name": {"key": "properties.principalName", "type": "str"}, } def __init__(self, **kwargs): """ """ super().__init__(**kwargs) self.principal_name = None class EnrollmentPolicies(_serialization.Model): """The policies for Enterprise Agreement enrollments. Variables are only populated by the server, and will be ignored when sending a request. :ivar account_owner_view_charges: The policy that controls whether Account Owners can view charges. :vartype account_owner_view_charges: bool :ivar department_admin_view_charges: The policy that controls whether Department Administrators can view charges. :vartype department_admin_view_charges: bool :ivar marketplace_enabled: The policy that controls whether Azure marketplace purchases are allowed in the enrollment. :vartype marketplace_enabled: bool :ivar reserved_instances_enabled: The policy that controls whether Azure reservation purchases are allowed in the enrollment. :vartype reserved_instances_enabled: bool """ _validation = { "account_owner_view_charges": {"readonly": True}, "department_admin_view_charges": {"readonly": True}, "marketplace_enabled": {"readonly": True}, "reserved_instances_enabled": {"readonly": True}, } _attribute_map = { "account_owner_view_charges": {"key": "accountOwnerViewCharges", "type": "bool"}, "department_admin_view_charges": {"key": "departmentAdminViewCharges", "type": "bool"}, "marketplace_enabled": {"key": "marketplaceEnabled", "type": "bool"}, "reserved_instances_enabled": {"key": "reservedInstancesEnabled", "type": "bool"}, } def __init__(self, **kwargs): """ """ super().__init__(**kwargs) self.account_owner_view_charges = None self.department_admin_view_charges = None self.marketplace_enabled = None self.reserved_instances_enabled = None class ErrorDetails(_serialization.Model): """The details of the error. Variables are only populated by the server, and will be ignored when sending a request. :ivar code: Error code. :vartype code: str :ivar message: Error message indicating why the operation failed. :vartype message: str :ivar target: The target of the particular error. :vartype target: str :ivar details: The sub details of the error. :vartype details: list[~azure.mgmt.billing.models.ErrorSubDetailsItem] """ _validation = { "code": {"readonly": True}, "message": {"readonly": True}, "target": {"readonly": True}, "details": {"readonly": True}, } _attribute_map = { "code": {"key": "code", "type": "str"}, "message": {"key": "message", "type": "str"}, "target": {"key": "target", "type": "str"}, "details": {"key": "details", "type": "[ErrorSubDetailsItem]"}, } def __init__(self, **kwargs): """ """ super().__init__(**kwargs) self.code = None self.message = None self.target = None self.details = None class ErrorResponse(_serialization.Model): """Error response indicates that the service is not able to process the incoming request. The reason is provided in the error message. :ivar error: The details of the error. :vartype error: ~azure.mgmt.billing.models.ErrorDetails """ _attribute_map = { "error": {"key": "error", "type": "ErrorDetails"}, } def __init__(self, *, error: Optional["_models.ErrorDetails"] = None, **kwargs): """ :keyword error: The details of the error. :paramtype error: ~azure.mgmt.billing.models.ErrorDetails """ super().__init__(**kwargs) self.error = error class ErrorSubDetailsItem(_serialization.Model): """ErrorSubDetailsItem. Variables are only populated by the server, and will be ignored when sending a request. :ivar code: Error code. :vartype code: str :ivar message: Error message indicating why the operation failed. :vartype message: str :ivar target: The target of the particular error. :vartype target: str """ _validation = { "code": {"readonly": True}, "message": {"readonly": True}, "target": {"readonly": True}, } _attribute_map = { "code": {"key": "code", "type": "str"}, "message": {"key": "message", "type": "str"}, "target": {"key": "target", "type": "str"}, } def __init__(self, **kwargs): """ """ super().__init__(**kwargs) self.code = None self.message = None self.target = None class IndirectRelationshipInfo(_serialization.Model): """The billing profile details of the partner of the customer for an indirect motion. :ivar billing_account_name: The billing account name of the partner or the customer for an indirect motion. :vartype billing_account_name: str :ivar billing_profile_name: The billing profile name of the partner or the customer for an indirect motion. :vartype billing_profile_name: str :ivar display_name: The display name of the partner or customer for an indirect motion. :vartype display_name: str """ _attribute_map = { "billing_account_name": {"key": "billingAccountName", "type": "str"}, "billing_profile_name": {"key": "billingProfileName", "type": "str"}, "display_name": {"key": "displayName", "type": "str"}, } def __init__( self, *, billing_account_name: Optional[str] = None, billing_profile_name: Optional[str] = None, display_name: Optional[str] = None, **kwargs ): """ :keyword billing_account_name: The billing account name of the partner or the customer for an indirect motion. :paramtype billing_account_name: str :keyword billing_profile_name: The billing profile name of the partner or the customer for an indirect motion. :paramtype billing_profile_name: str :keyword display_name: The display name of the partner or customer for an indirect motion. :paramtype display_name: str """ super().__init__(**kwargs) self.billing_account_name = billing_account_name self.billing_profile_name = billing_profile_name self.display_name = display_name class Instruction(Resource): """An instruction. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: Resource Id. :vartype id: str :ivar name: Resource name. :vartype name: str :ivar type: Resource type. :vartype type: str :ivar amount: The amount budgeted for this billing instruction. :vartype amount: float :ivar start_date: The date this billing instruction goes into effect. :vartype start_date: ~datetime.datetime :ivar end_date: The date this billing instruction is no longer in effect. :vartype end_date: ~datetime.datetime :ivar creation_date: The date this billing instruction was created. :vartype creation_date: ~datetime.datetime """ _validation = { "id": {"readonly": True}, "name": {"readonly": True}, "type": {"readonly": True}, } _attribute_map = { "id": {"key": "id", "type": "str"}, "name": {"key": "name", "type": "str"}, "type": {"key": "type", "type": "str"}, "amount": {"key": "properties.amount", "type": "float"}, "start_date": {"key": "properties.startDate", "type": "iso-8601"}, "end_date": {"key": "properties.endDate", "type": "iso-8601"}, "creation_date": {"key": "properties.creationDate", "type": "iso-8601"}, } def __init__( self, *, amount: Optional[float] = None, start_date: Optional[datetime.datetime] = None, end_date: Optional[datetime.datetime] = None, creation_date: Optional[datetime.datetime] = None, **kwargs ): """ :keyword amount: The amount budgeted for this billing instruction. :paramtype amount: float :keyword start_date: The date this billing instruction goes into effect. :paramtype start_date: ~datetime.datetime :keyword end_date: The date this billing instruction is no longer in effect. :paramtype end_date: ~datetime.datetime :keyword creation_date: The date this billing instruction was created. :paramtype creation_date: ~datetime.datetime """ super().__init__(**kwargs) self.amount = amount self.start_date = start_date self.end_date = end_date self.creation_date = creation_date class InstructionListResult(_serialization.Model): """The list of billing instructions used during invoice generation. Variables are only populated by the server, and will be ignored when sending a request. :ivar value: The list of billing instructions used during invoice generation. :vartype value: list[~azure.mgmt.billing.models.Instruction] :ivar next_link: The link (url) to the next page of results. :vartype next_link: str """ _validation = { "value": {"readonly": True}, "next_link": {"readonly": True}, } _attribute_map = { "value": {"key": "value", "type": "[Instruction]"}, "next_link": {"key": "nextLink", "type": "str"}, } def __init__(self, **kwargs): """ """ super().__init__(**kwargs) self.value = None self.next_link = None class Invoice(Resource): # pylint: disable=too-many-instance-attributes """An invoice. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: Resource Id. :vartype id: str :ivar name: Resource name. :vartype name: str :ivar type: Resource type. :vartype type: str :ivar due_date: The due date for the invoice. :vartype due_date: ~datetime.datetime :ivar invoice_date: The date when the invoice was generated. :vartype invoice_date: ~datetime.datetime :ivar status: The current status of the invoice. Known values are: "Due", "OverDue", "Paid", and "Void". :vartype status: str or ~azure.mgmt.billing.models.InvoiceStatus :ivar amount_due: The amount due as of now. :vartype amount_due: ~azure.mgmt.billing.models.Amount :ivar azure_prepayment_applied: The amount of Azure prepayment applied to the charges. This field is applicable to billing accounts with agreement type Microsoft Customer Agreement. :vartype azure_prepayment_applied: ~azure.mgmt.billing.models.Amount :ivar billed_amount: The total charges for the invoice billing period. :vartype billed_amount: ~azure.mgmt.billing.models.Amount :ivar credit_amount: The total refund for returns and cancellations during the invoice billing period. This field is applicable to billing accounts with agreement type Microsoft Customer Agreement. :vartype credit_amount: ~azure.mgmt.billing.models.Amount :ivar free_azure_credit_applied: The amount of free Azure credits applied to the charges. This field is applicable to billing accounts with agreement type Microsoft Customer Agreement. :vartype free_azure_credit_applied: ~azure.mgmt.billing.models.Amount :ivar sub_total: The pre-tax amount due. This field is applicable to billing accounts with agreement type Microsoft Customer Agreement. :vartype sub_total: ~azure.mgmt.billing.models.Amount :ivar tax_amount: The amount of tax charged for the billing period. This field is applicable to billing accounts with agreement type Microsoft Customer Agreement. :vartype tax_amount: ~azure.mgmt.billing.models.Amount :ivar total_amount: The amount due when the invoice was generated. This field is applicable to billing accounts with agreement type Microsoft Customer Agreement. :vartype total_amount: ~azure.mgmt.billing.models.Amount :ivar invoice_period_start_date: The start date of the billing period for which the invoice is generated. :vartype invoice_period_start_date: ~datetime.datetime :ivar invoice_period_end_date: The end date of the billing period for which the invoice is generated. :vartype invoice_period_end_date: ~datetime.datetime :ivar invoice_type: Invoice type. Known values are: "AzureService", "AzureMarketplace", and "AzureSupport". :vartype invoice_type: str or ~azure.mgmt.billing.models.InvoiceType :ivar is_monthly_invoice: Specifies if the invoice is generated as part of monthly invoicing cycle or not. This field is applicable to billing accounts with agreement type Microsoft Customer Agreement. :vartype is_monthly_invoice: bool :ivar billing_profile_id: The ID of the billing profile for which the invoice is generated. :vartype billing_profile_id: str :ivar billing_profile_display_name: The name of the billing profile for which the invoice is generated. :vartype billing_profile_display_name: str :ivar purchase_order_number: An optional purchase order number for the invoice. :vartype purchase_order_number: str :ivar documents: List of documents available to download such as invoice and tax receipt. :vartype documents: list[~azure.mgmt.billing.models.Document] :ivar payments: List of payments. :vartype payments: list[~azure.mgmt.billing.models.PaymentProperties] :ivar rebill_details: Rebill details for an invoice. :vartype rebill_details: dict[str, ~azure.mgmt.billing.models.RebillDetails] :ivar document_type: The type of the document. Known values are: "Invoice" and "CreditNote". :vartype document_type: str or ~azure.mgmt.billing.models.InvoiceDocumentType :ivar billed_document_id: The Id of the active invoice which is originally billed after this invoice was voided. This field is applicable to the void invoices only. :vartype billed_document_id: str :ivar credit_for_document_id: The Id of the invoice which got voided and this credit note was issued as a result. This field is applicable to the credit notes only. :vartype credit_for_document_id: str :ivar subscription_id: The ID of the subscription for which the invoice is generated. :vartype subscription_id: str """ _validation = { "id": {"readonly": True}, "name": {"readonly": True}, "type": {"readonly": True}, "due_date": {"readonly": True}, "invoice_date": {"readonly": True}, "status": {"readonly": True}, "amount_due": {"readonly": True}, "azure_prepayment_applied": {"readonly": True}, "billed_amount": {"readonly": True}, "credit_amount": {"readonly": True}, "free_azure_credit_applied": {"readonly": True}, "sub_total": {"readonly": True}, "tax_amount": {"readonly": True}, "total_amount": {"readonly": True}, "invoice_period_start_date": {"readonly": True}, "invoice_period_end_date": {"readonly": True}, "invoice_type": {"readonly": True}, "is_monthly_invoice": {"readonly": True}, "billing_profile_id": {"readonly": True}, "billing_profile_display_name": {"readonly": True}, "purchase_order_number": {"readonly": True}, "documents": {"readonly": True}, "payments": {"readonly": True}, "rebill_details": {"readonly": True}, "document_type": {"readonly": True}, "billed_document_id": {"readonly": True}, "credit_for_document_id": {"readonly": True}, "subscription_id": {"readonly": True}, } _attribute_map = { "id": {"key": "id", "type": "str"}, "name": {"key": "name", "type": "str"}, "type": {"key": "type", "type": "str"}, "due_date": {"key": "properties.dueDate", "type": "iso-8601"}, "invoice_date": {"key": "properties.invoiceDate", "type": "iso-8601"}, "status": {"key": "properties.status", "type": "str"}, "amount_due": {"key": "properties.amountDue", "type": "Amount"}, "azure_prepayment_applied": {"key": "properties.azurePrepaymentApplied", "type": "Amount"}, "billed_amount": {"key": "properties.billedAmount", "type": "Amount"}, "credit_amount": {"key": "properties.creditAmount", "type": "Amount"}, "free_azure_credit_applied": {"key": "properties.freeAzureCreditApplied", "type": "Amount"}, "sub_total": {"key": "properties.subTotal", "type": "Amount"}, "tax_amount": {"key": "properties.taxAmount", "type": "Amount"}, "total_amount": {"key": "properties.totalAmount", "type": "Amount"}, "invoice_period_start_date": {"key": "properties.invoicePeriodStartDate", "type": "iso-8601"}, "invoice_period_end_date": {"key": "properties.invoicePeriodEndDate", "type": "iso-8601"}, "invoice_type": {"key": "properties.invoiceType", "type": "str"}, "is_monthly_invoice": {"key": "properties.isMonthlyInvoice", "type": "bool"}, "billing_profile_id": {"key": "properties.billingProfileId", "type": "str"}, "billing_profile_display_name": {"key": "properties.billingProfileDisplayName", "type": "str"}, "purchase_order_number": {"key": "properties.purchaseOrderNumber", "type": "str"}, "documents": {"key": "properties.documents", "type": "[Document]"}, "payments": {"key": "properties.payments", "type": "[PaymentProperties]"}, "rebill_details": {"key": "properties.rebillDetails", "type": "{RebillDetails}"}, "document_type": {"key": "properties.documentType", "type": "str"}, "billed_document_id": {"key": "properties.billedDocumentId", "type": "str"}, "credit_for_document_id": {"key": "properties.creditForDocumentId", "type": "str"}, "subscription_id": {"key": "properties.subscriptionId", "type": "str"}, } def __init__(self, **kwargs): # pylint: disable=too-many-locals """ """ super().__init__(**kwargs) self.due_date = None self.invoice_date = None self.status = None self.amount_due = None self.azure_prepayment_applied = None self.billed_amount = None self.credit_amount = None self.free_azure_credit_applied = None self.sub_total = None self.tax_amount = None self.total_amount = None self.invoice_period_start_date = None self.invoice_period_end_date = None self.invoice_type = None self.is_monthly_invoice = None self.billing_profile_id = None self.billing_profile_display_name = None self.purchase_order_number = None self.documents = None self.payments = None self.rebill_details = None self.document_type = None self.billed_document_id = None self.credit_for_document_id = None self.subscription_id = None class InvoiceListResult(_serialization.Model): """The list of invoices. Variables are only populated by the server, and will be ignored when sending a request. :ivar value: The list of invoices. :vartype value: list[~azure.mgmt.billing.models.Invoice] :ivar next_link: The link (url) to the next page of results. :vartype next_link: str :ivar total_count: Total number of records. :vartype total_count: int """ _validation = { "value": {"readonly": True}, "next_link": {"readonly": True}, "total_count": {"readonly": True}, } _attribute_map = { "value": {"key": "value", "type": "[Invoice]"}, "next_link": {"key": "nextLink", "type": "str"}, "total_count": {"key": "totalCount", "type": "int"}, } def __init__(self, **kwargs): """ """ super().__init__(**kwargs) self.value = None self.next_link = None self.total_count = None class InvoiceSection(Resource): """An invoice section. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: Resource Id. :vartype id: str :ivar name: Resource name. :vartype name: str :ivar type: Resource type. :vartype type: str :ivar display_name: The name of the invoice section. :vartype display_name: str :ivar labels: Dictionary of metadata associated with the invoice section. :vartype labels: dict[str, str] :ivar state: Identifies the state of an invoice section. Known values are: "Active" and "Restricted". :vartype state: str or ~azure.mgmt.billing.models.InvoiceSectionState :ivar system_id: The system generated unique identifier for an invoice section. :vartype system_id: str :ivar tags: Dictionary of metadata associated with the invoice section. Maximum key/value length supported of 256 characters. Keys/value should not empty value nor null. Keys can not contain < > % & ? /. :vartype tags: dict[str, str] :ivar target_cloud: Identifies the cloud environments that are associated with an invoice section. This is a system managed optional field and gets updated as the invoice section gets associated with accounts in various clouds. Known values are: "USGov", "USNat", and "USSec". :vartype target_cloud: str or ~azure.mgmt.billing.models.TargetCloud """ _validation = { "id": {"readonly": True}, "name": {"readonly": True}, "type": {"readonly": True}, "state": {"readonly": True}, "system_id": {"readonly": True}, "target_cloud": {"readonly": True}, } _attribute_map = { "id": {"key": "id", "type": "str"}, "name": {"key": "name", "type": "str"}, "type": {"key": "type", "type": "str"}, "display_name": {"key": "properties.displayName", "type": "str"}, "labels": {"key": "properties.labels", "type": "{str}"}, "state": {"key": "properties.state", "type": "str"}, "system_id": {"key": "properties.systemId", "type": "str"}, "tags": {"key": "properties.tags", "type": "{str}"}, "target_cloud": {"key": "properties.targetCloud", "type": "str"}, } def __init__( self, *, display_name: Optional[str] = None, labels: Optional[Dict[str, str]] = None, tags: Optional[Dict[str, str]] = None, **kwargs ): """ :keyword display_name: The name of the invoice section. :paramtype display_name: str :keyword labels: Dictionary of metadata associated with the invoice section. :paramtype labels: dict[str, str] :keyword tags: Dictionary of metadata associated with the invoice section. Maximum key/value length supported of 256 characters. Keys/value should not empty value nor null. Keys can not contain < > % & ? /. :paramtype tags: dict[str, str] """ super().__init__(**kwargs) self.display_name = display_name self.labels = labels self.state = None self.system_id = None self.tags = tags self.target_cloud = None class InvoiceSectionCreationRequest(_serialization.Model): """The properties of the invoice section. :ivar display_name: The name of the invoice section. :vartype display_name: str """ _attribute_map = { "display_name": {"key": "displayName", "type": "str"}, } def __init__(self, *, display_name: Optional[str] = None, **kwargs): """ :keyword display_name: The name of the invoice section. :paramtype display_name: str """ super().__init__(**kwargs) self.display_name = display_name class InvoiceSectionListResult(_serialization.Model): """The list of invoice sections. Variables are only populated by the server, and will be ignored when sending a request. :ivar value: The list of invoice sections. :vartype value: list[~azure.mgmt.billing.models.InvoiceSection] :ivar total_count: Total number of records. :vartype total_count: int :ivar next_link: The link (url) to the next page of results. :vartype next_link: str """ _validation = { "value": {"readonly": True}, "total_count": {"readonly": True}, "next_link": {"readonly": True}, } _attribute_map = { "value": {"key": "value", "type": "[InvoiceSection]"}, "total_count": {"key": "totalCount", "type": "int"}, "next_link": {"key": "nextLink", "type": "str"}, } def __init__(self, **kwargs): """ """ super().__init__(**kwargs) self.value = None self.total_count = None self.next_link = None class InvoiceSectionListWithCreateSubPermissionResult(_serialization.Model): """The list of invoice section properties with create subscription permission. Variables are only populated by the server, and will be ignored when sending a request. :ivar value: The list of invoice section properties with create subscription permission. :vartype value: list[~azure.mgmt.billing.models.InvoiceSectionWithCreateSubPermission] :ivar next_link: The link (url) to the next page of results. :vartype next_link: str """ _validation = { "next_link": {"readonly": True}, } _attribute_map = { "value": {"key": "value", "type": "[InvoiceSectionWithCreateSubPermission]"}, "next_link": {"key": "nextLink", "type": "str"}, } def __init__(self, *, value: Optional[List["_models.InvoiceSectionWithCreateSubPermission"]] = None, **kwargs): """ :keyword value: The list of invoice section properties with create subscription permission. :paramtype value: list[~azure.mgmt.billing.models.InvoiceSectionWithCreateSubPermission] """ super().__init__(**kwargs) self.value = value self.next_link = None class InvoiceSectionsOnExpand(_serialization.Model): """The invoice sections associated to the billing profile. By default this is not populated, unless it's specified in $expand. Variables are only populated by the server, and will be ignored when sending a request. :ivar has_more_results: Indicates whether there are more invoice sections than the ones listed in this collection. The collection lists a maximum of 50 invoice sections. To get all invoice sections, use the list invoice sections API. :vartype has_more_results: bool :ivar value: The invoice sections associated to the billing profile. :vartype value: list[~azure.mgmt.billing.models.InvoiceSection] """ _validation = { "has_more_results": {"readonly": True}, } _attribute_map = { "has_more_results": {"key": "hasMoreResults", "type": "bool"}, "value": {"key": "value", "type": "[InvoiceSection]"}, } def __init__(self, *, value: Optional[List["_models.InvoiceSection"]] = None, **kwargs): """ :keyword value: The invoice sections associated to the billing profile. :paramtype value: list[~azure.mgmt.billing.models.InvoiceSection] """ super().__init__(**kwargs) self.has_more_results = None self.value = value class InvoiceSectionWithCreateSubPermission(_serialization.Model): """Invoice section properties with create subscription permission. Variables are only populated by the server, and will be ignored when sending a request. :ivar invoice_section_id: The ID of the invoice section. :vartype invoice_section_id: str :ivar invoice_section_display_name: The name of the invoice section. :vartype invoice_section_display_name: str :ivar invoice_section_system_id: The system generated unique identifier for an invoice section. :vartype invoice_section_system_id: str :ivar billing_profile_id: The ID of the billing profile for the invoice section. :vartype billing_profile_id: str :ivar billing_profile_display_name: The name of the billing profile for the invoice section. :vartype billing_profile_display_name: str :ivar billing_profile_status: The status of the billing profile. Known values are: "Active", "Disabled", and "Warned". :vartype billing_profile_status: str or ~azure.mgmt.billing.models.BillingProfileStatus :ivar billing_profile_status_reason_code: Reason for the specified billing profile status. Known values are: "PastDue", "SpendingLimitReached", and "SpendingLimitExpired". :vartype billing_profile_status_reason_code: str or ~azure.mgmt.billing.models.StatusReasonCodeForBillingProfile :ivar billing_profile_spending_limit: The billing profile spending limit. Known values are: "Off" and "On". :vartype billing_profile_spending_limit: str or ~azure.mgmt.billing.models.SpendingLimitForBillingProfile :ivar billing_profile_system_id: The system generated unique identifier for a billing profile. :vartype billing_profile_system_id: str :ivar enabled_azure_plans: Enabled azure plans for the associated billing profile. :vartype enabled_azure_plans: list[~azure.mgmt.billing.models.AzurePlan] """ _validation = { "invoice_section_id": {"readonly": True}, "invoice_section_display_name": {"readonly": True}, "invoice_section_system_id": {"readonly": True}, "billing_profile_id": {"readonly": True}, "billing_profile_display_name": {"readonly": True}, "billing_profile_status": {"readonly": True}, "billing_profile_status_reason_code": {"readonly": True}, "billing_profile_spending_limit": {"readonly": True}, "billing_profile_system_id": {"readonly": True}, } _attribute_map = { "invoice_section_id": {"key": "invoiceSectionId", "type": "str"}, "invoice_section_display_name": {"key": "invoiceSectionDisplayName", "type": "str"}, "invoice_section_system_id": {"key": "invoiceSectionSystemId", "type": "str"}, "billing_profile_id": {"key": "billingProfileId", "type": "str"}, "billing_profile_display_name": {"key": "billingProfileDisplayName", "type": "str"}, "billing_profile_status": {"key": "billingProfileStatus", "type": "str"}, "billing_profile_status_reason_code": {"key": "billingProfileStatusReasonCode", "type": "str"}, "billing_profile_spending_limit": {"key": "billingProfileSpendingLimit", "type": "str"}, "billing_profile_system_id": {"key": "billingProfileSystemId", "type": "str"}, "enabled_azure_plans": {"key": "enabledAzurePlans", "type": "[AzurePlan]"}, } def __init__(self, *, enabled_azure_plans: Optional[List["_models.AzurePlan"]] = None, **kwargs): """ :keyword enabled_azure_plans: Enabled azure plans for the associated billing profile. :paramtype enabled_azure_plans: list[~azure.mgmt.billing.models.AzurePlan] """ super().__init__(**kwargs) self.invoice_section_id = None self.invoice_section_display_name = None self.invoice_section_system_id = None self.billing_profile_id = None self.billing_profile_display_name = None self.billing_profile_status = None self.billing_profile_status_reason_code = None self.billing_profile_spending_limit = None self.billing_profile_system_id = None self.enabled_azure_plans = enabled_azure_plans class Operation(_serialization.Model): """A Billing REST API operation. Variables are only populated by the server, and will be ignored when sending a request. :ivar name: Operation name: {provider}/{resource}/{operation}. :vartype name: str :ivar is_data_action: Identifies if the operation is a data operation. :vartype is_data_action: bool :ivar display: The object that represents the operation. :vartype display: ~azure.mgmt.billing.models.OperationDisplay """ _validation = { "name": {"readonly": True}, "is_data_action": {"readonly": True}, } _attribute_map = { "name": {"key": "name", "type": "str"}, "is_data_action": {"key": "isDataAction", "type": "bool"}, "display": {"key": "display", "type": "OperationDisplay"}, } def __init__(self, *, display: Optional["_models.OperationDisplay"] = None, **kwargs): """ :keyword display: The object that represents the operation. :paramtype display: ~azure.mgmt.billing.models.OperationDisplay """ super().__init__(**kwargs) self.name = None self.is_data_action = None self.display = display class OperationDisplay(_serialization.Model): """The object that represents the operation. Variables are only populated by the server, and will be ignored when sending a request. :ivar provider: Service provider: Microsoft.Billing. :vartype provider: str :ivar resource: Resource on which the operation is performed such as invoice and billing subscription. :vartype resource: str :ivar operation: Operation type such as read, write and delete. :vartype operation: str :ivar description: Description of operation. :vartype description: str """ _validation = { "provider": {"readonly": True}, "resource": {"readonly": True}, "operation": {"readonly": True}, "description": {"readonly": True}, } _attribute_map = { "provider": {"key": "provider", "type": "str"}, "resource": {"key": "resource", "type": "str"}, "operation": {"key": "operation", "type": "str"}, "description": {"key": "description", "type": "str"}, } def __init__(self, **kwargs): """ """ super().__init__(**kwargs) self.provider = None self.resource = None self.operation = None self.description = None class OperationListResult(_serialization.Model): """The list of billing operations and a URL link to get the next set of results. Variables are only populated by the server, and will be ignored when sending a request. :ivar value: The list of billing operations supported by the Microsoft.Billing resource provider. :vartype value: list[~azure.mgmt.billing.models.Operation] :ivar next_link: URL to get the next set of operation list results if there are any. :vartype next_link: str """ _validation = { "value": {"readonly": True}, "next_link": {"readonly": True}, } _attribute_map = { "value": {"key": "value", "type": "[Operation]"}, "next_link": {"key": "nextLink", "type": "str"}, } def __init__(self, **kwargs): """ """ super().__init__(**kwargs) self.value = None self.next_link = None class OperationsErrorDetails(_serialization.Model): """The details of the error. Variables are only populated by the server, and will be ignored when sending a request. :ivar code: Error code. :vartype code: str :ivar message: Error message indicating why the operation failed. :vartype message: str :ivar target: The target of the particular error. :vartype target: str """ _validation = { "code": {"readonly": True}, "message": {"readonly": True}, "target": {"readonly": True}, } _attribute_map = { "code": {"key": "code", "type": "str"}, "message": {"key": "message", "type": "str"}, "target": {"key": "target", "type": "str"}, } def __init__(self, **kwargs): """ """ super().__init__(**kwargs) self.code = None self.message = None self.target = None class OperationsErrorResponse(_serialization.Model): """Error response indicates that the service is not able to process the incoming request. The reason is provided in the error message. :ivar error: The details of the error. :vartype error: ~azure.mgmt.billing.models.OperationsErrorDetails """ _attribute_map = { "error": {"key": "error", "type": "OperationsErrorDetails"}, } def __init__(self, *, error: Optional["_models.OperationsErrorDetails"] = None, **kwargs): """ :keyword error: The details of the error. :paramtype error: ~azure.mgmt.billing.models.OperationsErrorDetails """ super().__init__(**kwargs) self.error = error class Participants(_serialization.Model): """The details about a participant. Variables are only populated by the server, and will be ignored when sending a request. :ivar status: The acceptance status of the participant. :vartype status: str :ivar status_date: The date when the status got changed. :vartype status_date: ~datetime.datetime :ivar email: The email address of the participant. :vartype email: str """ _validation = { "status": {"readonly": True}, "status_date": {"readonly": True}, "email": {"readonly": True}, } _attribute_map = { "status": {"key": "status", "type": "str"}, "status_date": {"key": "statusDate", "type": "iso-8601"}, "email": {"key": "email", "type": "str"}, } def __init__(self, **kwargs): """ """ super().__init__(**kwargs) self.status = None self.status_date = None self.email = None class PaymentProperties(_serialization.Model): """The properties of a payment. Variables are only populated by the server, and will be ignored when sending a request. :ivar payment_type: The type of payment. :vartype payment_type: str :ivar amount: The paid amount. :vartype amount: ~azure.mgmt.billing.models.Amount :ivar date: The date when the payment was made. :vartype date: ~datetime.datetime :ivar payment_method_family: The family of payment method. Known values are: "Credits", "CheckWire", "CreditCard", and "None". :vartype payment_method_family: str or ~azure.mgmt.billing.models.PaymentMethodFamily :ivar payment_method_type: The type of payment method. :vartype payment_method_type: str """ _validation = { "payment_type": {"readonly": True}, "amount": {"readonly": True}, "date": {"readonly": True}, "payment_method_type": {"readonly": True}, } _attribute_map = { "payment_type": {"key": "paymentType", "type": "str"}, "amount": {"key": "amount", "type": "Amount"}, "date": {"key": "date", "type": "iso-8601"}, "payment_method_family": {"key": "paymentMethodFamily", "type": "str"}, "payment_method_type": {"key": "paymentMethodType", "type": "str"}, } def __init__(self, *, payment_method_family: Optional[Union[str, "_models.PaymentMethodFamily"]] = None, **kwargs): """ :keyword payment_method_family: The family of payment method. Known values are: "Credits", "CheckWire", "CreditCard", and "None". :paramtype payment_method_family: str or ~azure.mgmt.billing.models.PaymentMethodFamily """ super().__init__(**kwargs) self.payment_type = None self.amount = None self.date = None self.payment_method_family = payment_method_family self.payment_method_type = None class Policy(Resource): """A policy. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: Resource Id. :vartype id: str :ivar name: Resource name. :vartype name: str :ivar type: Resource type. :vartype type: str :ivar marketplace_purchases: The policy that controls whether Azure marketplace purchases are allowed for a billing profile. Known values are: "AllAllowed", "OnlyFreeAllowed", and "NotAllowed". :vartype marketplace_purchases: str or ~azure.mgmt.billing.models.MarketplacePurchasesPolicy :ivar reservation_purchases: The policy that controls whether Azure reservation purchases are allowed for a billing profile. Known values are: "Allowed" and "NotAllowed". :vartype reservation_purchases: str or ~azure.mgmt.billing.models.ReservationPurchasesPolicy :ivar view_charges: The policy that controls whether users with Azure RBAC access to a subscription can view its charges. Known values are: "Allowed" and "NotAllowed". :vartype view_charges: str or ~azure.mgmt.billing.models.ViewChargesPolicy """ _validation = { "id": {"readonly": True}, "name": {"readonly": True}, "type": {"readonly": True}, } _attribute_map = { "id": {"key": "id", "type": "str"}, "name": {"key": "name", "type": "str"}, "type": {"key": "type", "type": "str"}, "marketplace_purchases": {"key": "properties.marketplacePurchases", "type": "str"}, "reservation_purchases": {"key": "properties.reservationPurchases", "type": "str"}, "view_charges": {"key": "properties.viewCharges", "type": "str"}, } def __init__( self, *, marketplace_purchases: Optional[Union[str, "_models.MarketplacePurchasesPolicy"]] = None, reservation_purchases: Optional[Union[str, "_models.ReservationPurchasesPolicy"]] = None, view_charges: Optional[Union[str, "_models.ViewChargesPolicy"]] = None, **kwargs ): """ :keyword marketplace_purchases: The policy that controls whether Azure marketplace purchases are allowed for a billing profile. Known values are: "AllAllowed", "OnlyFreeAllowed", and "NotAllowed". :paramtype marketplace_purchases: str or ~azure.mgmt.billing.models.MarketplacePurchasesPolicy :keyword reservation_purchases: The policy that controls whether Azure reservation purchases are allowed for a billing profile. Known values are: "Allowed" and "NotAllowed". :paramtype reservation_purchases: str or ~azure.mgmt.billing.models.ReservationPurchasesPolicy :keyword view_charges: The policy that controls whether users with Azure RBAC access to a subscription can view its charges. Known values are: "Allowed" and "NotAllowed". :paramtype view_charges: str or ~azure.mgmt.billing.models.ViewChargesPolicy """ super().__init__(**kwargs) self.marketplace_purchases = marketplace_purchases self.reservation_purchases = reservation_purchases self.view_charges = view_charges class Product(Resource): # pylint: disable=too-many-instance-attributes """A product. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: Resource Id. :vartype id: str :ivar name: Resource name. :vartype name: str :ivar type: Resource type. :vartype type: str :ivar auto_renew: Indicates whether auto renewal is turned on or off for a product. Known values are: "Off" and "On". :vartype auto_renew: str or ~azure.mgmt.billing.models.AutoRenew :ivar display_name: The display name of the product. :vartype display_name: str :ivar purchase_date: The date when the product was purchased. :vartype purchase_date: ~datetime.datetime :ivar product_type_id: The ID of the type of product. :vartype product_type_id: str :ivar product_type: The description of the type of product. :vartype product_type: str :ivar status: The current status of the product. Known values are: "Active", "Inactive", "PastDue", "Expiring", "Expired", "Disabled", "Cancelled", and "AutoRenew". :vartype status: str or ~azure.mgmt.billing.models.ProductStatusType :ivar end_date: The date when the product will be renewed or canceled. :vartype end_date: ~datetime.datetime :ivar billing_frequency: The frequency at which the product will be billed. Known values are: "OneTime", "Monthly", and "UsageBased". :vartype billing_frequency: str or ~azure.mgmt.billing.models.BillingFrequency :ivar last_charge: The last month charges. :vartype last_charge: ~azure.mgmt.billing.models.Amount :ivar last_charge_date: The date of the last charge. :vartype last_charge_date: ~datetime.datetime :ivar quantity: The quantity purchased for the product. :vartype quantity: float :ivar sku_id: The sku ID of the product. :vartype sku_id: str :ivar sku_description: The sku description of the product. :vartype sku_description: str :ivar tenant_id: The id of the tenant in which the product is used. :vartype tenant_id: str :ivar availability_id: The availability of the product. :vartype availability_id: str :ivar invoice_section_id: The ID of the invoice section to which the product is billed. :vartype invoice_section_id: str :ivar invoice_section_display_name: The name of the invoice section to which the product is billed. :vartype invoice_section_display_name: str :ivar billing_profile_id: The ID of the billing profile to which the product is billed. :vartype billing_profile_id: str :ivar billing_profile_display_name: The name of the billing profile to which the product is billed. :vartype billing_profile_display_name: str :ivar customer_id: The ID of the customer for whom the product was purchased. The field is applicable only for Microsoft Partner Agreement billing account. :vartype customer_id: str :ivar customer_display_name: The name of the customer for whom the product was purchased. The field is applicable only for Microsoft Partner Agreement billing account. :vartype customer_display_name: str :ivar reseller: Reseller for this product. :vartype reseller: ~azure.mgmt.billing.models.Reseller """ _validation = { "id": {"readonly": True}, "name": {"readonly": True}, "type": {"readonly": True}, "display_name": {"readonly": True}, "purchase_date": {"readonly": True}, "product_type_id": {"readonly": True}, "product_type": {"readonly": True}, "end_date": {"readonly": True}, "last_charge": {"readonly": True}, "last_charge_date": {"readonly": True}, "quantity": {"readonly": True}, "sku_id": {"readonly": True}, "sku_description": {"readonly": True}, "tenant_id": {"readonly": True}, "availability_id": {"readonly": True}, "invoice_section_id": {"readonly": True}, "invoice_section_display_name": {"readonly": True}, "billing_profile_id": {"readonly": True}, "billing_profile_display_name": {"readonly": True}, "customer_id": {"readonly": True}, "customer_display_name": {"readonly": True}, "reseller": {"readonly": True}, } _attribute_map = { "id": {"key": "id", "type": "str"}, "name": {"key": "name", "type": "str"}, "type": {"key": "type", "type": "str"}, "auto_renew": {"key": "properties.autoRenew", "type": "str"}, "display_name": {"key": "properties.displayName", "type": "str"}, "purchase_date": {"key": "properties.purchaseDate", "type": "iso-8601"}, "product_type_id": {"key": "properties.productTypeId", "type": "str"}, "product_type": {"key": "properties.productType", "type": "str"}, "status": {"key": "properties.status", "type": "str"}, "end_date": {"key": "properties.endDate", "type": "iso-8601"}, "billing_frequency": {"key": "properties.billingFrequency", "type": "str"}, "last_charge": {"key": "properties.lastCharge", "type": "Amount"}, "last_charge_date": {"key": "properties.lastChargeDate", "type": "iso-8601"}, "quantity": {"key": "properties.quantity", "type": "float"}, "sku_id": {"key": "properties.skuId", "type": "str"}, "sku_description": {"key": "properties.skuDescription", "type": "str"}, "tenant_id": {"key": "properties.tenantId", "type": "str"}, "availability_id": {"key": "properties.availabilityId", "type": "str"}, "invoice_section_id": {"key": "properties.invoiceSectionId", "type": "str"}, "invoice_section_display_name": {"key": "properties.invoiceSectionDisplayName", "type": "str"}, "billing_profile_id": {"key": "properties.billingProfileId", "type": "str"}, "billing_profile_display_name": {"key": "properties.billingProfileDisplayName", "type": "str"}, "customer_id": {"key": "properties.customerId", "type": "str"}, "customer_display_name": {"key": "properties.customerDisplayName", "type": "str"}, "reseller": {"key": "properties.reseller", "type": "Reseller"}, } def __init__( # pylint: disable=too-many-locals self, *, auto_renew: Optional[Union[str, "_models.AutoRenew"]] = None, status: Optional[Union[str, "_models.ProductStatusType"]] = None, billing_frequency: Optional[Union[str, "_models.BillingFrequency"]] = None, **kwargs ): """ :keyword auto_renew: Indicates whether auto renewal is turned on or off for a product. Known values are: "Off" and "On". :paramtype auto_renew: str or ~azure.mgmt.billing.models.AutoRenew :keyword status: The current status of the product. Known values are: "Active", "Inactive", "PastDue", "Expiring", "Expired", "Disabled", "Cancelled", and "AutoRenew". :paramtype status: str or ~azure.mgmt.billing.models.ProductStatusType :keyword billing_frequency: The frequency at which the product will be billed. Known values are: "OneTime", "Monthly", and "UsageBased". :paramtype billing_frequency: str or ~azure.mgmt.billing.models.BillingFrequency """ super().__init__(**kwargs) self.auto_renew = auto_renew self.display_name = None self.purchase_date = None self.product_type_id = None self.product_type = None self.status = status self.end_date = None self.billing_frequency = billing_frequency self.last_charge = None self.last_charge_date = None self.quantity = None self.sku_id = None self.sku_description = None self.tenant_id = None self.availability_id = None self.invoice_section_id = None self.invoice_section_display_name = None self.billing_profile_id = None self.billing_profile_display_name = None self.customer_id = None self.customer_display_name = None self.reseller = None class ProductsListResult(_serialization.Model): """The list of products. It contains a list of available product summaries in reverse chronological order by purchase date. Variables are only populated by the server, and will be ignored when sending a request. :ivar value: The list of products. :vartype value: list[~azure.mgmt.billing.models.Product] :ivar total_count: Total number of records. :vartype total_count: int :ivar next_link: The link (url) to the next page of results. :vartype next_link: str """ _validation = { "value": {"readonly": True}, "total_count": {"readonly": True}, "next_link": {"readonly": True}, } _attribute_map = { "value": {"key": "value", "type": "[Product]"}, "total_count": {"key": "totalCount", "type": "int"}, "next_link": {"key": "nextLink", "type": "str"}, } def __init__(self, **kwargs): """ """ super().__init__(**kwargs) self.value = None self.total_count = None self.next_link = None class RebillDetails(_serialization.Model): """The rebill details of an invoice. Variables are only populated by the server, and will be ignored when sending a request. :ivar credit_note_document_id: The ID of credit note. :vartype credit_note_document_id: str :ivar invoice_document_id: The ID of invoice. :vartype invoice_document_id: str :ivar rebill_details: Rebill details for an invoice. :vartype rebill_details: dict[str, ~azure.mgmt.billing.models.RebillDetails] """ _validation = { "credit_note_document_id": {"readonly": True}, "invoice_document_id": {"readonly": True}, "rebill_details": {"readonly": True}, } _attribute_map = { "credit_note_document_id": {"key": "creditNoteDocumentId", "type": "str"}, "invoice_document_id": {"key": "invoiceDocumentId", "type": "str"}, "rebill_details": {"key": "rebillDetails", "type": "{RebillDetails}"}, } def __init__(self, **kwargs): """ """ super().__init__(**kwargs) self.credit_note_document_id = None self.invoice_document_id = None self.rebill_details = None class Reseller(_serialization.Model): """Details of the reseller. Variables are only populated by the server, and will be ignored when sending a request. :ivar reseller_id: The MPN ID of the reseller. :vartype reseller_id: str :ivar description: The name of the reseller. :vartype description: str """ _validation = { "reseller_id": {"readonly": True}, "description": {"readonly": True}, } _attribute_map = { "reseller_id": {"key": "resellerId", "type": "str"}, "description": {"key": "description", "type": "str"}, } def __init__(self, **kwargs): """ """ super().__init__(**kwargs) self.reseller_id = None self.description = None class Reservation(_serialization.Model): # pylint: disable=too-many-instance-attributes """The definition of the reservation. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: The id of the reservation. :vartype id: str :ivar name: The name of the reservation. :vartype name: str :ivar type: The type of the reservation. :vartype type: str :ivar location: The location of the reservation. :vartype location: str :ivar sku: The sku information associated to this reservation. :vartype sku: ~azure.mgmt.billing.models.ReservationSkuProperty :ivar applied_scopes: The array of applied scopes of a reservation. Will be null if the reservation is in Shared scope. :vartype applied_scopes: list[str] :ivar applied_scope_type: The applied scope type of the reservation. :vartype applied_scope_type: str :ivar reserved_resource_type: The reserved source type of the reservation, e.g. virtual machine. :vartype reserved_resource_type: str :ivar quantity: The number of the reservation. :vartype quantity: float :ivar provisioning_state: The provisioning state of the reservation, e.g. Succeeded. :vartype provisioning_state: str :ivar expiry_date: The expiry date of the reservation. :vartype expiry_date: str :ivar provisioning_sub_state: The provisioning state of the reservation, e.g. Succeeded. :vartype provisioning_sub_state: str :ivar display_name: The display name of the reservation. :vartype display_name: str :ivar display_provisioning_state: The provisioning state of the reservation for display, e.g. Succeeded. :vartype display_provisioning_state: str :ivar user_friendly_renew_state: The renew state of the reservation for display, e.g. On. :vartype user_friendly_renew_state: str :ivar user_friendly_applied_scope_type: The applied scope type of the reservation for display, e.g. Shared. :vartype user_friendly_applied_scope_type: str :ivar effective_date_time: The effective date time of the reservation. :vartype effective_date_time: str :ivar sku_description: The sku description of the reservation. :vartype sku_description: str :ivar term: The term of the reservation, e.g. P1Y. :vartype term: str :ivar renew: The renew state of the reservation. :vartype renew: bool :ivar renew_source: The renew source of the reservation. :vartype renew_source: str :ivar utilization: Reservation utilization. :vartype utilization: ~azure.mgmt.billing.models.ReservationPropertyUtilization """ _validation = { "id": {"readonly": True}, "name": {"readonly": True}, "type": {"readonly": True}, "location": {"readonly": True}, "applied_scope_type": {"readonly": True}, "reserved_resource_type": {"readonly": True}, "quantity": {"readonly": True}, "provisioning_state": {"readonly": True}, "expiry_date": {"readonly": True}, "provisioning_sub_state": {"readonly": True}, "display_name": {"readonly": True}, "display_provisioning_state": {"readonly": True}, "user_friendly_renew_state": {"readonly": True}, "user_friendly_applied_scope_type": {"readonly": True}, "effective_date_time": {"readonly": True}, "sku_description": {"readonly": True}, "term": {"readonly": True}, "renew": {"readonly": True}, "renew_source": {"readonly": True}, "utilization": {"readonly": True}, } _attribute_map = { "id": {"key": "id", "type": "str"}, "name": {"key": "name", "type": "str"}, "type": {"key": "type", "type": "str"}, "location": {"key": "location", "type": "str"}, "sku": {"key": "sku", "type": "ReservationSkuProperty"}, "applied_scopes": {"key": "properties.appliedScopes", "type": "[str]"}, "applied_scope_type": {"key": "properties.appliedScopeType", "type": "str"}, "reserved_resource_type": {"key": "properties.reservedResourceType", "type": "str"}, "quantity": {"key": "properties.quantity", "type": "float"}, "provisioning_state": {"key": "properties.provisioningState", "type": "str"}, "expiry_date": {"key": "properties.expiryDate", "type": "str"}, "provisioning_sub_state": {"key": "properties.provisioningSubState", "type": "str"}, "display_name": {"key": "properties.displayName", "type": "str"}, "display_provisioning_state": {"key": "properties.displayProvisioningState", "type": "str"}, "user_friendly_renew_state": {"key": "properties.userFriendlyRenewState", "type": "str"}, "user_friendly_applied_scope_type": {"key": "properties.userFriendlyAppliedScopeType", "type": "str"}, "effective_date_time": {"key": "properties.effectiveDateTime", "type": "str"}, "sku_description": {"key": "properties.skuDescription", "type": "str"}, "term": {"key": "properties.term", "type": "str"}, "renew": {"key": "properties.renew", "type": "bool"}, "renew_source": {"key": "properties.renewSource", "type": "str"}, "utilization": {"key": "properties.utilization", "type": "ReservationPropertyUtilization"}, } def __init__( self, *, sku: Optional["_models.ReservationSkuProperty"] = None, applied_scopes: Optional[List[str]] = None, **kwargs ): """ :keyword sku: The sku information associated to this reservation. :paramtype sku: ~azure.mgmt.billing.models.ReservationSkuProperty :keyword applied_scopes: The array of applied scopes of a reservation. Will be null if the reservation is in Shared scope. :paramtype applied_scopes: list[str] """ super().__init__(**kwargs) self.id = None self.name = None self.type = None self.location = None self.sku = sku self.applied_scopes = applied_scopes self.applied_scope_type = None self.reserved_resource_type = None self.quantity = None self.provisioning_state = None self.expiry_date = None self.provisioning_sub_state = None self.display_name = None self.display_provisioning_state = None self.user_friendly_renew_state = None self.user_friendly_applied_scope_type = None self.effective_date_time = None self.sku_description = None self.term = None self.renew = None self.renew_source = None self.utilization = None class ReservationPropertyUtilization(_serialization.Model): """Reservation utilization. Variables are only populated by the server, and will be ignored when sending a request. :ivar trend: The number of days trend for a reservation. :vartype trend: str :ivar aggregates: The array of aggregates of a reservation's utilization. :vartype aggregates: list[~azure.mgmt.billing.models.ReservationUtilizationAggregates] """ _validation = { "trend": {"readonly": True}, } _attribute_map = { "trend": {"key": "trend", "type": "str"}, "aggregates": {"key": "aggregates", "type": "[ReservationUtilizationAggregates]"}, } def __init__(self, *, aggregates: Optional[List["_models.ReservationUtilizationAggregates"]] = None, **kwargs): """ :keyword aggregates: The array of aggregates of a reservation's utilization. :paramtype aggregates: list[~azure.mgmt.billing.models.ReservationUtilizationAggregates] """ super().__init__(**kwargs) self.trend = None self.aggregates = aggregates class ReservationSkuProperty(_serialization.Model): """The property of reservation sku object. Variables are only populated by the server, and will be ignored when sending a request. :ivar name: The name of the reservation sku. :vartype name: str """ _validation = { "name": {"readonly": True}, } _attribute_map = { "name": {"key": "name", "type": "str"}, } def __init__(self, **kwargs): """ """ super().__init__(**kwargs) self.name = None class ReservationsListResult(_serialization.Model): """The list of reservations and summary of roll out count of reservations in each state. Variables are only populated by the server, and will be ignored when sending a request. :ivar value: The list of reservations. :vartype value: list[~azure.mgmt.billing.models.Reservation] :ivar next_link: The link (url) to the next page of results. :vartype next_link: str :ivar summary: The roll out count summary of the reservations. :vartype summary: ~azure.mgmt.billing.models.ReservationSummary """ _validation = { "value": {"readonly": True}, "next_link": {"readonly": True}, } _attribute_map = { "value": {"key": "value", "type": "[Reservation]"}, "next_link": {"key": "nextLink", "type": "str"}, "summary": {"key": "summary", "type": "ReservationSummary"}, } def __init__(self, *, summary: Optional["_models.ReservationSummary"] = None, **kwargs): """ :keyword summary: The roll out count summary of the reservations. :paramtype summary: ~azure.mgmt.billing.models.ReservationSummary """ super().__init__(**kwargs) self.value = None self.next_link = None self.summary = summary class ReservationSummary(_serialization.Model): """The roll up count summary of reservations in each state. Variables are only populated by the server, and will be ignored when sending a request. :ivar succeeded_count: The number of reservation in Succeeded state. :vartype succeeded_count: float :ivar failed_count: The number of reservation in Failed state. :vartype failed_count: float :ivar expiring_count: The number of reservation in Expiring state. :vartype expiring_count: float :ivar expired_count: The number of reservation in Expired state. :vartype expired_count: float :ivar pending_count: The number of reservation in Pending state. :vartype pending_count: float :ivar cancelled_count: The number of reservation in Cancelled state. :vartype cancelled_count: float """ _validation = { "succeeded_count": {"readonly": True}, "failed_count": {"readonly": True}, "expiring_count": {"readonly": True}, "expired_count": {"readonly": True}, "pending_count": {"readonly": True}, "cancelled_count": {"readonly": True}, } _attribute_map = { "succeeded_count": {"key": "succeededCount", "type": "float"}, "failed_count": {"key": "failedCount", "type": "float"}, "expiring_count": {"key": "expiringCount", "type": "float"}, "expired_count": {"key": "expiredCount", "type": "float"}, "pending_count": {"key": "pendingCount", "type": "float"}, "cancelled_count": {"key": "cancelledCount", "type": "float"}, } def __init__(self, **kwargs): """ """ super().__init__(**kwargs) self.succeeded_count = None self.failed_count = None self.expiring_count = None self.expired_count = None self.pending_count = None self.cancelled_count = None class ReservationUtilizationAggregates(_serialization.Model): """The aggregate values of reservation utilization. Variables are only populated by the server, and will be ignored when sending a request. :ivar grain: The grain of the aggregate. :vartype grain: float :ivar grain_unit: The grain unit of the aggregate. :vartype grain_unit: str :ivar value: The aggregate value. :vartype value: float :ivar value_unit: The aggregate value unit. :vartype value_unit: str """ _validation = { "grain": {"readonly": True}, "grain_unit": {"readonly": True}, "value": {"readonly": True}, "value_unit": {"readonly": True}, } _attribute_map = { "grain": {"key": "grain", "type": "float"}, "grain_unit": {"key": "grainUnit", "type": "str"}, "value": {"key": "value", "type": "float"}, "value_unit": {"key": "valueUnit", "type": "str"}, } def __init__(self, **kwargs): """ """ super().__init__(**kwargs) self.grain = None self.grain_unit = None self.value = None self.value_unit = None class Transaction(Resource): # pylint: disable=too-many-instance-attributes """A transaction. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: Resource Id. :vartype id: str :ivar name: Resource name. :vartype name: str :ivar type: Resource type. :vartype type: str :ivar kind: The kind of transaction. Options are all or reservation. Known values are: "all" and "reservation". :vartype kind: str or ~azure.mgmt.billing.models.TransactionTypeKind :ivar date: The date of transaction. :vartype date: ~datetime.datetime :ivar invoice: Invoice on which the transaction was billed or 'pending' if the transaction is not billed. :vartype invoice: str :ivar invoice_id: The ID of the invoice on which the transaction was billed. This field is only applicable for transactions which are billed. :vartype invoice_id: str :ivar order_id: The order ID of the reservation. The field is only applicable for transaction of kind reservation. :vartype order_id: str :ivar order_name: The name of the reservation order. The field is only applicable for transactions of kind reservation. :vartype order_name: str :ivar product_family: The family of the product for which the transaction took place. :vartype product_family: str :ivar product_type_id: The ID of the product type for which the transaction took place. :vartype product_type_id: str :ivar product_type: The type of the product for which the transaction took place. :vartype product_type: str :ivar product_description: The description of the product for which the transaction took place. :vartype product_description: str :ivar transaction_type: The type of transaction. Known values are: "Purchase" and "Usage Charge". :vartype transaction_type: str or ~azure.mgmt.billing.models.ReservationType :ivar transaction_amount: The charge associated with the transaction. :vartype transaction_amount: ~azure.mgmt.billing.models.Amount :ivar quantity: The quantity purchased in the transaction. :vartype quantity: int :ivar invoice_section_id: The ID of the invoice section which will be billed for the transaction. :vartype invoice_section_id: str :ivar invoice_section_display_name: The name of the invoice section which will be billed for the transaction. :vartype invoice_section_display_name: str :ivar billing_profile_id: The ID of the billing profile which will be billed for the transaction. :vartype billing_profile_id: str :ivar billing_profile_display_name: The name of the billing profile which will be billed for the transaction. :vartype billing_profile_display_name: str :ivar customer_id: The ID of the customer for which the transaction took place. The field is applicable only for Microsoft Partner Agreement billing account. :vartype customer_id: str :ivar customer_display_name: The name of the customer for which the transaction took place. The field is applicable only for Microsoft Partner Agreement billing account. :vartype customer_display_name: str :ivar subscription_id: The ID of the subscription that was used for the transaction. The field is only applicable for transaction of kind reservation. :vartype subscription_id: str :ivar subscription_name: The name of the subscription that was used for the transaction. The field is only applicable for transaction of kind reservation. :vartype subscription_name: str :ivar azure_plan: The type of azure plan of the subscription that was used for the transaction. :vartype azure_plan: str :ivar azure_credit_applied: The amount of any Azure credits automatically applied to this transaction. :vartype azure_credit_applied: ~azure.mgmt.billing.models.Amount :ivar billing_currency: The ISO 4217 code for the currency in which this transaction is billed. :vartype billing_currency: str :ivar discount: The percentage discount, if any, applied to this transaction. :vartype discount: float :ivar effective_price: The price of the product after applying any discounts. :vartype effective_price: ~azure.mgmt.billing.models.Amount :ivar exchange_rate: The exchange rate used to convert charged amount to billing currency, if applicable. :vartype exchange_rate: float :ivar market_price: The retail price of the product. :vartype market_price: ~azure.mgmt.billing.models.Amount :ivar pricing_currency: The ISO 4217 code for the currency in which the product is priced. :vartype pricing_currency: str :ivar service_period_start_date: The date of the purchase of the product, or the start date of the month in which usage started. :vartype service_period_start_date: ~datetime.datetime :ivar service_period_end_date: The end date of the product term, or the end date of the month in which usage ended. :vartype service_period_end_date: ~datetime.datetime :ivar sub_total: The pre-tax charged amount for the transaction. :vartype sub_total: ~azure.mgmt.billing.models.Amount :ivar tax: The tax amount applied to the transaction. :vartype tax: ~azure.mgmt.billing.models.Amount :ivar unit_of_measure: The unit of measure used to bill for the product. For example, compute services are billed per hour. :vartype unit_of_measure: str :ivar units: The number of units used for a given product. :vartype units: float :ivar unit_type: The description for the unit of measure for a given product. :vartype unit_type: str """ _validation = { "id": {"readonly": True}, "name": {"readonly": True}, "type": {"readonly": True}, "date": {"readonly": True}, "invoice": {"readonly": True}, "invoice_id": {"readonly": True}, "order_id": {"readonly": True}, "order_name": {"readonly": True}, "product_family": {"readonly": True}, "product_type_id": {"readonly": True}, "product_type": {"readonly": True}, "product_description": {"readonly": True}, "transaction_amount": {"readonly": True}, "quantity": {"readonly": True}, "invoice_section_id": {"readonly": True}, "invoice_section_display_name": {"readonly": True}, "billing_profile_id": {"readonly": True}, "billing_profile_display_name": {"readonly": True}, "customer_id": {"readonly": True}, "customer_display_name": {"readonly": True}, "subscription_id": {"readonly": True}, "subscription_name": {"readonly": True}, "azure_plan": {"readonly": True}, "azure_credit_applied": {"readonly": True}, "billing_currency": {"readonly": True}, "discount": {"readonly": True}, "effective_price": {"readonly": True}, "exchange_rate": {"readonly": True}, "market_price": {"readonly": True}, "pricing_currency": {"readonly": True}, "service_period_start_date": {"readonly": True}, "service_period_end_date": {"readonly": True}, "sub_total": {"readonly": True}, "tax": {"readonly": True}, "unit_of_measure": {"readonly": True}, "units": {"readonly": True}, "unit_type": {"readonly": True}, } _attribute_map = { "id": {"key": "id", "type": "str"}, "name": {"key": "name", "type": "str"}, "type": {"key": "type", "type": "str"}, "kind": {"key": "properties.kind", "type": "str"}, "date": {"key": "properties.date", "type": "iso-8601"}, "invoice": {"key": "properties.invoice", "type": "str"}, "invoice_id": {"key": "properties.invoiceId", "type": "str"}, "order_id": {"key": "properties.orderId", "type": "str"}, "order_name": {"key": "properties.orderName", "type": "str"}, "product_family": {"key": "properties.productFamily", "type": "str"}, "product_type_id": {"key": "properties.productTypeId", "type": "str"}, "product_type": {"key": "properties.productType", "type": "str"}, "product_description": {"key": "properties.productDescription", "type": "str"}, "transaction_type": {"key": "properties.transactionType", "type": "str"}, "transaction_amount": {"key": "properties.transactionAmount", "type": "Amount"}, "quantity": {"key": "properties.quantity", "type": "int"}, "invoice_section_id": {"key": "properties.invoiceSectionId", "type": "str"}, "invoice_section_display_name": {"key": "properties.invoiceSectionDisplayName", "type": "str"}, "billing_profile_id": {"key": "properties.billingProfileId", "type": "str"}, "billing_profile_display_name": {"key": "properties.billingProfileDisplayName", "type": "str"}, "customer_id": {"key": "properties.customerId", "type": "str"}, "customer_display_name": {"key": "properties.customerDisplayName", "type": "str"}, "subscription_id": {"key": "properties.subscriptionId", "type": "str"}, "subscription_name": {"key": "properties.subscriptionName", "type": "str"}, "azure_plan": {"key": "properties.azurePlan", "type": "str"}, "azure_credit_applied": {"key": "properties.azureCreditApplied", "type": "Amount"}, "billing_currency": {"key": "properties.billingCurrency", "type": "str"}, "discount": {"key": "properties.discount", "type": "float"}, "effective_price": {"key": "properties.effectivePrice", "type": "Amount"}, "exchange_rate": {"key": "properties.exchangeRate", "type": "float"}, "market_price": {"key": "properties.marketPrice", "type": "Amount"}, "pricing_currency": {"key": "properties.pricingCurrency", "type": "str"}, "service_period_start_date": {"key": "properties.servicePeriodStartDate", "type": "iso-8601"}, "service_period_end_date": {"key": "properties.servicePeriodEndDate", "type": "iso-8601"}, "sub_total": {"key": "properties.subTotal", "type": "Amount"}, "tax": {"key": "properties.tax", "type": "Amount"}, "unit_of_measure": {"key": "properties.unitOfMeasure", "type": "str"}, "units": {"key": "properties.units", "type": "float"}, "unit_type": {"key": "properties.unitType", "type": "str"}, } def __init__( # pylint: disable=too-many-locals self, *, kind: Optional[Union[str, "_models.TransactionTypeKind"]] = None, transaction_type: Optional[Union[str, "_models.ReservationType"]] = None, **kwargs ): """ :keyword kind: The kind of transaction. Options are all or reservation. Known values are: "all" and "reservation". :paramtype kind: str or ~azure.mgmt.billing.models.TransactionTypeKind :keyword transaction_type: The type of transaction. Known values are: "Purchase" and "Usage Charge". :paramtype transaction_type: str or ~azure.mgmt.billing.models.ReservationType """ super().__init__(**kwargs) self.kind = kind self.date = None self.invoice = None self.invoice_id = None self.order_id = None self.order_name = None self.product_family = None self.product_type_id = None self.product_type = None self.product_description = None self.transaction_type = transaction_type self.transaction_amount = None self.quantity = None self.invoice_section_id = None self.invoice_section_display_name = None self.billing_profile_id = None self.billing_profile_display_name = None self.customer_id = None self.customer_display_name = None self.subscription_id = None self.subscription_name = None self.azure_plan = None self.azure_credit_applied = None self.billing_currency = None self.discount = None self.effective_price = None self.exchange_rate = None self.market_price = None self.pricing_currency = None self.service_period_start_date = None self.service_period_end_date = None self.sub_total = None self.tax = None self.unit_of_measure = None self.units = None self.unit_type = None class TransactionListResult(_serialization.Model): """The list of transactions. Variables are only populated by the server, and will be ignored when sending a request. :ivar value: The list of transactions. :vartype value: list[~azure.mgmt.billing.models.Transaction] :ivar total_count: Total number of records. :vartype total_count: int :ivar next_link: The link (url) to the next page of results. :vartype next_link: str """ _validation = { "value": {"readonly": True}, "total_count": {"readonly": True}, "next_link": {"readonly": True}, } _attribute_map = { "value": {"key": "value", "type": "[Transaction]"}, "total_count": {"key": "totalCount", "type": "int"}, "next_link": {"key": "nextLink", "type": "str"}, } def __init__(self, **kwargs): """ """ super().__init__(**kwargs) self.value = None self.total_count = None self.next_link = None class TransferBillingSubscriptionRequestProperties(_serialization.Model): """Request parameters to transfer billing subscription. All required parameters must be populated in order to send to Azure. :ivar destination_invoice_section_id: The destination invoice section id. Required. :vartype destination_invoice_section_id: str """ _validation = { "destination_invoice_section_id": {"required": True}, } _attribute_map = { "destination_invoice_section_id": {"key": "destinationInvoiceSectionId", "type": "str"}, } def __init__(self, *, destination_invoice_section_id: str, **kwargs): """ :keyword destination_invoice_section_id: The destination invoice section id. Required. :paramtype destination_invoice_section_id: str """ super().__init__(**kwargs) self.destination_invoice_section_id = destination_invoice_section_id class TransferProductRequestProperties(_serialization.Model): """The properties of the product to initiate a transfer. :ivar destination_invoice_section_id: The destination invoice section id. :vartype destination_invoice_section_id: str """ _attribute_map = { "destination_invoice_section_id": {"key": "destinationInvoiceSectionId", "type": "str"}, } def __init__(self, *, destination_invoice_section_id: Optional[str] = None, **kwargs): """ :keyword destination_invoice_section_id: The destination invoice section id. :paramtype destination_invoice_section_id: str """ super().__init__(**kwargs) self.destination_invoice_section_id = destination_invoice_section_id class ValidateAddressResponse(_serialization.Model): """Result of the address validation. :ivar status: status of the address validation. Known values are: "Valid" and "Invalid". :vartype status: str or ~azure.mgmt.billing.models.AddressValidationStatus :ivar suggested_addresses: The list of suggested addresses. :vartype suggested_addresses: list[~azure.mgmt.billing.models.AddressDetails] :ivar validation_message: Validation error message. :vartype validation_message: str """ _attribute_map = { "status": {"key": "status", "type": "str"}, "suggested_addresses": {"key": "suggestedAddresses", "type": "[AddressDetails]"}, "validation_message": {"key": "validationMessage", "type": "str"}, } def __init__( self, *, status: Optional[Union[str, "_models.AddressValidationStatus"]] = None, suggested_addresses: Optional[List["_models.AddressDetails"]] = None, validation_message: Optional[str] = None, **kwargs ): """ :keyword status: status of the address validation. Known values are: "Valid" and "Invalid". :paramtype status: str or ~azure.mgmt.billing.models.AddressValidationStatus :keyword suggested_addresses: The list of suggested addresses. :paramtype suggested_addresses: list[~azure.mgmt.billing.models.AddressDetails] :keyword validation_message: Validation error message. :paramtype validation_message: str """ super().__init__(**kwargs) self.status = status self.suggested_addresses = suggested_addresses self.validation_message = validation_message class ValidateProductTransferEligibilityError(_serialization.Model): """Error details of the product transfer eligibility validation. :ivar code: Error code for the product transfer validation. Known values are: "InvalidSource", "ProductNotActive", "InsufficientPermissionOnSource", "InsufficientPermissionOnDestination", "DestinationBillingProfilePastDue", "ProductTypeNotSupported", "CrossBillingAccountNotAllowed", "NotAvailableForDestinationMarket", and "OneTimePurchaseProductTransferNotAllowed". :vartype code: str or ~azure.mgmt.billing.models.ProductTransferValidationErrorCode :ivar message: The error message. :vartype message: str :ivar details: Detailed error message explaining the error. :vartype details: str """ _attribute_map = { "code": {"key": "code", "type": "str"}, "message": {"key": "message", "type": "str"}, "details": {"key": "details", "type": "str"}, } def __init__( self, *, code: Optional[Union[str, "_models.ProductTransferValidationErrorCode"]] = None, message: Optional[str] = None, details: Optional[str] = None, **kwargs ): """ :keyword code: Error code for the product transfer validation. Known values are: "InvalidSource", "ProductNotActive", "InsufficientPermissionOnSource", "InsufficientPermissionOnDestination", "DestinationBillingProfilePastDue", "ProductTypeNotSupported", "CrossBillingAccountNotAllowed", "NotAvailableForDestinationMarket", and "OneTimePurchaseProductTransferNotAllowed". :paramtype code: str or ~azure.mgmt.billing.models.ProductTransferValidationErrorCode :keyword message: The error message. :paramtype message: str :keyword details: Detailed error message explaining the error. :paramtype details: str """ super().__init__(**kwargs) self.code = code self.message = message self.details = details class ValidateProductTransferEligibilityResult(_serialization.Model): """Result of the product transfer eligibility validation. Variables are only populated by the server, and will be ignored when sending a request. :ivar is_move_eligible: Specifies whether the transfer is eligible or not. :vartype is_move_eligible: bool :ivar error_details: Validation error details. :vartype error_details: ~azure.mgmt.billing.models.ValidateProductTransferEligibilityError """ _validation = { "is_move_eligible": {"readonly": True}, } _attribute_map = { "is_move_eligible": {"key": "isMoveEligible", "type": "bool"}, "error_details": {"key": "errorDetails", "type": "ValidateProductTransferEligibilityError"}, } def __init__(self, *, error_details: Optional["_models.ValidateProductTransferEligibilityError"] = None, **kwargs): """ :keyword error_details: Validation error details. :paramtype error_details: ~azure.mgmt.billing.models.ValidateProductTransferEligibilityError """ super().__init__(**kwargs) self.is_move_eligible = None self.error_details = error_details class ValidateSubscriptionTransferEligibilityError(_serialization.Model): """Error details of the transfer eligibility validation. :ivar code: Error code for the product transfer validation. Known values are: "BillingAccountInactive", "CrossBillingAccountNotAllowed", "DestinationBillingProfileInactive", "DestinationBillingProfileNotFound", "DestinationBillingProfilePastDue", "DestinationInvoiceSectionInactive", "DestinationInvoiceSectionNotFound", "InsufficientPermissionOnDestination", "InsufficientPermissionOnSource", "InvalidDestination", "InvalidSource", "MarketplaceNotEnabledOnDestination", "NotAvailableForDestinationMarket", "ProductInactive", "ProductNotFound", "ProductTypeNotSupported", "SourceBillingProfilePastDue", "SourceInvoiceSectionInactive", "SubscriptionNotActive", and "SubscriptionTypeNotSupported". :vartype code: str or ~azure.mgmt.billing.models.SubscriptionTransferValidationErrorCode :ivar message: The error message. :vartype message: str :ivar details: Detailed error message explaining the error. :vartype details: str """ _attribute_map = { "code": {"key": "code", "type": "str"}, "message": {"key": "message", "type": "str"}, "details": {"key": "details", "type": "str"}, } def __init__( self, *, code: Optional[Union[str, "_models.SubscriptionTransferValidationErrorCode"]] = None, message: Optional[str] = None, details: Optional[str] = None, **kwargs ): """ :keyword code: Error code for the product transfer validation. Known values are: "BillingAccountInactive", "CrossBillingAccountNotAllowed", "DestinationBillingProfileInactive", "DestinationBillingProfileNotFound", "DestinationBillingProfilePastDue", "DestinationInvoiceSectionInactive", "DestinationInvoiceSectionNotFound", "InsufficientPermissionOnDestination", "InsufficientPermissionOnSource", "InvalidDestination", "InvalidSource", "MarketplaceNotEnabledOnDestination", "NotAvailableForDestinationMarket", "ProductInactive", "ProductNotFound", "ProductTypeNotSupported", "SourceBillingProfilePastDue", "SourceInvoiceSectionInactive", "SubscriptionNotActive", and "SubscriptionTypeNotSupported". :paramtype code: str or ~azure.mgmt.billing.models.SubscriptionTransferValidationErrorCode :keyword message: The error message. :paramtype message: str :keyword details: Detailed error message explaining the error. :paramtype details: str """ super().__init__(**kwargs) self.code = code self.message = message self.details = details class ValidateSubscriptionTransferEligibilityResult(_serialization.Model): """Result of the transfer eligibility validation. Variables are only populated by the server, and will be ignored when sending a request. :ivar is_move_eligible: Specifies whether the subscription is eligible to be transferred. :vartype is_move_eligible: bool :ivar error_details: Validation error details. :vartype error_details: ~azure.mgmt.billing.models.ValidateSubscriptionTransferEligibilityError """ _validation = { "is_move_eligible": {"readonly": True}, } _attribute_map = { "is_move_eligible": {"key": "isMoveEligible", "type": "bool"}, "error_details": {"key": "errorDetails", "type": "ValidateSubscriptionTransferEligibilityError"}, } def __init__( self, *, error_details: Optional["_models.ValidateSubscriptionTransferEligibilityError"] = None, **kwargs ): """ :keyword error_details: Validation error details. :paramtype error_details: ~azure.mgmt.billing.models.ValidateSubscriptionTransferEligibilityError """ super().__init__(**kwargs) self.is_move_eligible = None self.error_details = error_details
azure-mgmt-billing
/azure_mgmt_billing-6.1.0b1-py3-none-any.whl/azure/mgmt/billing/models/_models_py3.py
_models_py3.py
import datetime from typing import Dict, List, Optional, TYPE_CHECKING, Union from .. import _serialization if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from .. import models as _models class AddressDetails(_serialization.Model): # pylint: disable=too-many-instance-attributes """Address details. All required parameters must be populated in order to send to Azure. :ivar first_name: First name. :vartype first_name: str :ivar middle_name: Middle name. :vartype middle_name: str :ivar last_name: Last name. :vartype last_name: str :ivar company_name: Company name. :vartype company_name: str :ivar address_line1: Address line 1. Required. :vartype address_line1: str :ivar address_line2: Address line 2. :vartype address_line2: str :ivar address_line3: Address line 3. :vartype address_line3: str :ivar city: Address city. :vartype city: str :ivar district: Address district. :vartype district: str :ivar region: Address region. :vartype region: str :ivar country: Country code uses ISO2, 2-digit format. Required. :vartype country: str :ivar postal_code: Postal code. :vartype postal_code: str :ivar email: Email address. :vartype email: str :ivar phone_number: Phone number. :vartype phone_number: str """ _validation = { "address_line1": {"required": True}, "country": {"required": True}, } _attribute_map = { "first_name": {"key": "firstName", "type": "str"}, "middle_name": {"key": "middleName", "type": "str"}, "last_name": {"key": "lastName", "type": "str"}, "company_name": {"key": "companyName", "type": "str"}, "address_line1": {"key": "addressLine1", "type": "str"}, "address_line2": {"key": "addressLine2", "type": "str"}, "address_line3": {"key": "addressLine3", "type": "str"}, "city": {"key": "city", "type": "str"}, "district": {"key": "district", "type": "str"}, "region": {"key": "region", "type": "str"}, "country": {"key": "country", "type": "str"}, "postal_code": {"key": "postalCode", "type": "str"}, "email": {"key": "email", "type": "str"}, "phone_number": {"key": "phoneNumber", "type": "str"}, } def __init__( self, *, address_line1: str, country: str, first_name: Optional[str] = None, middle_name: Optional[str] = None, last_name: Optional[str] = None, company_name: Optional[str] = None, address_line2: Optional[str] = None, address_line3: Optional[str] = None, city: Optional[str] = None, district: Optional[str] = None, region: Optional[str] = None, postal_code: Optional[str] = None, email: Optional[str] = None, phone_number: Optional[str] = None, **kwargs ): """ :keyword first_name: First name. :paramtype first_name: str :keyword middle_name: Middle name. :paramtype middle_name: str :keyword last_name: Last name. :paramtype last_name: str :keyword company_name: Company name. :paramtype company_name: str :keyword address_line1: Address line 1. Required. :paramtype address_line1: str :keyword address_line2: Address line 2. :paramtype address_line2: str :keyword address_line3: Address line 3. :paramtype address_line3: str :keyword city: Address city. :paramtype city: str :keyword district: Address district. :paramtype district: str :keyword region: Address region. :paramtype region: str :keyword country: Country code uses ISO2, 2-digit format. Required. :paramtype country: str :keyword postal_code: Postal code. :paramtype postal_code: str :keyword email: Email address. :paramtype email: str :keyword phone_number: Phone number. :paramtype phone_number: str """ super().__init__(**kwargs) self.first_name = first_name self.middle_name = middle_name self.last_name = last_name self.company_name = company_name self.address_line1 = address_line1 self.address_line2 = address_line2 self.address_line3 = address_line3 self.city = city self.district = district self.region = region self.country = country self.postal_code = postal_code self.email = email self.phone_number = phone_number class Resource(_serialization.Model): """The Resource model definition. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: Resource Id. :vartype id: str :ivar name: Resource name. :vartype name: str :ivar type: Resource type. :vartype type: str """ _validation = { "id": {"readonly": True}, "name": {"readonly": True}, "type": {"readonly": True}, } _attribute_map = { "id": {"key": "id", "type": "str"}, "name": {"key": "name", "type": "str"}, "type": {"key": "type", "type": "str"}, } def __init__(self, **kwargs): """ """ super().__init__(**kwargs) self.id = None self.name = None self.type = None class Agreement(Resource): # pylint: disable=too-many-instance-attributes """An agreement. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: Resource Id. :vartype id: str :ivar name: Resource name. :vartype name: str :ivar type: Resource type. :vartype type: str :ivar agreement_link: The URL to download the agreement. :vartype agreement_link: str :ivar category: The category of the agreement signed by a customer. Known values are: "MicrosoftCustomerAgreement", "AffiliatePurchaseTerms", and "Other". :vartype category: str or ~azure.mgmt.billing.models.Category :ivar acceptance_mode: The mode of acceptance for an agreement. Known values are: "ClickToAccept", "ESignEmbedded", and "ESignOffline". :vartype acceptance_mode: str or ~azure.mgmt.billing.models.AcceptanceMode :ivar billing_profile_info: The list of billing profiles associated with agreement and present only for specific agreements. :vartype billing_profile_info: ~azure.mgmt.billing.models.BillingProfileInfo :ivar effective_date: The date from which the agreement is effective. :vartype effective_date: ~datetime.datetime :ivar expiration_date: The date when the agreement expires. :vartype expiration_date: ~datetime.datetime :ivar participants: The list of participants that participates in acceptance of an agreement. :vartype participants: list[~azure.mgmt.billing.models.Participants] :ivar status: The current status of the agreement. :vartype status: str """ _validation = { "id": {"readonly": True}, "name": {"readonly": True}, "type": {"readonly": True}, "agreement_link": {"readonly": True}, "category": {"readonly": True}, "acceptance_mode": {"readonly": True}, "billing_profile_info": {"readonly": True}, "effective_date": {"readonly": True}, "expiration_date": {"readonly": True}, "status": {"readonly": True}, } _attribute_map = { "id": {"key": "id", "type": "str"}, "name": {"key": "name", "type": "str"}, "type": {"key": "type", "type": "str"}, "agreement_link": {"key": "properties.agreementLink", "type": "str"}, "category": {"key": "properties.category", "type": "str"}, "acceptance_mode": {"key": "properties.acceptanceMode", "type": "str"}, "billing_profile_info": {"key": "properties.billingProfileInfo", "type": "BillingProfileInfo"}, "effective_date": {"key": "properties.effectiveDate", "type": "iso-8601"}, "expiration_date": {"key": "properties.expirationDate", "type": "iso-8601"}, "participants": {"key": "properties.participants", "type": "[Participants]"}, "status": {"key": "properties.status", "type": "str"}, } def __init__(self, *, participants: Optional[List["_models.Participants"]] = None, **kwargs): """ :keyword participants: The list of participants that participates in acceptance of an agreement. :paramtype participants: list[~azure.mgmt.billing.models.Participants] """ super().__init__(**kwargs) self.agreement_link = None self.category = None self.acceptance_mode = None self.billing_profile_info = None self.effective_date = None self.expiration_date = None self.participants = participants self.status = None class AgreementListResult(_serialization.Model): """Result of listing agreements. Variables are only populated by the server, and will be ignored when sending a request. :ivar value: The list of agreements. :vartype value: list[~azure.mgmt.billing.models.Agreement] :ivar next_link: The link (url) to the next page of results. :vartype next_link: str """ _validation = { "value": {"readonly": True}, "next_link": {"readonly": True}, } _attribute_map = { "value": {"key": "value", "type": "[Agreement]"}, "next_link": {"key": "nextLink", "type": "str"}, } def __init__(self, **kwargs): """ """ super().__init__(**kwargs) self.value = None self.next_link = None class Amount(_serialization.Model): """The amount. Variables are only populated by the server, and will be ignored when sending a request. :ivar currency: The currency for the amount value. :vartype currency: str :ivar value: Amount value. :vartype value: float """ _validation = { "currency": {"readonly": True}, } _attribute_map = { "currency": {"key": "currency", "type": "str"}, "value": {"key": "value", "type": "float"}, } def __init__(self, *, value: Optional[float] = None, **kwargs): """ :keyword value: Amount value. :paramtype value: float """ super().__init__(**kwargs) self.currency = None self.value = value class AvailableBalance(Resource): """The latest Azure credit balance. This is the balance available for pay now. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: Resource Id. :vartype id: str :ivar name: Resource name. :vartype name: str :ivar type: Resource type. :vartype type: str :ivar amount: Balance amount. :vartype amount: ~azure.mgmt.billing.models.Amount """ _validation = { "id": {"readonly": True}, "name": {"readonly": True}, "type": {"readonly": True}, "amount": {"readonly": True}, } _attribute_map = { "id": {"key": "id", "type": "str"}, "name": {"key": "name", "type": "str"}, "type": {"key": "type", "type": "str"}, "amount": {"key": "properties.amount", "type": "Amount"}, } def __init__(self, **kwargs): """ """ super().__init__(**kwargs) self.amount = None class AzurePlan(_serialization.Model): """Details of the Azure plan. Variables are only populated by the server, and will be ignored when sending a request. :ivar sku_id: The sku id. :vartype sku_id: str :ivar sku_description: The sku description. :vartype sku_description: str """ _validation = { "sku_description": {"readonly": True}, } _attribute_map = { "sku_id": {"key": "skuId", "type": "str"}, "sku_description": {"key": "skuDescription", "type": "str"}, } def __init__(self, *, sku_id: Optional[str] = None, **kwargs): """ :keyword sku_id: The sku id. :paramtype sku_id: str """ super().__init__(**kwargs) self.sku_id = sku_id self.sku_description = None class BillingAccount(Resource): # pylint: disable=too-many-instance-attributes """A billing account. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: Resource Id. :vartype id: str :ivar name: Resource name. :vartype name: str :ivar type: Resource type. :vartype type: str :ivar display_name: The billing account name. :vartype display_name: str :ivar sold_to: The address of the individual or organization that is responsible for the billing account. :vartype sold_to: ~azure.mgmt.billing.models.AddressDetails :ivar agreement_type: The type of agreement. Known values are: "MicrosoftCustomerAgreement", "EnterpriseAgreement", "MicrosoftOnlineServicesProgram", and "MicrosoftPartnerAgreement". :vartype agreement_type: str or ~azure.mgmt.billing.models.AgreementType :ivar account_type: The type of customer. Known values are: "Enterprise", "Individual", and "Partner". :vartype account_type: str or ~azure.mgmt.billing.models.AccountType :ivar account_status: The current status of the billing account. Known values are: "Active", "Deleted", "Disabled", "Expired", "Transferred", "Extended", and "Terminated". :vartype account_status: str or ~azure.mgmt.billing.models.AccountStatus :ivar billing_profiles: The billing profiles associated with the billing account. By default this is not populated, unless it's specified in $expand. :vartype billing_profiles: ~azure.mgmt.billing.models.BillingProfilesOnExpand :ivar enrollment_details: The details about the associated legacy enrollment. By default this is not populated, unless it's specified in $expand. :vartype enrollment_details: ~azure.mgmt.billing.models.Enrollment :ivar departments: The departments associated to the enrollment. :vartype departments: list[~azure.mgmt.billing.models.Department] :ivar enrollment_accounts: The accounts associated to the enrollment. :vartype enrollment_accounts: list[~azure.mgmt.billing.models.EnrollmentAccount] :ivar has_read_access: Indicates whether user has read access to the billing account. :vartype has_read_access: bool :ivar notification_email_address: Notification email address, only for legacy accounts. :vartype notification_email_address: str """ _validation = { "id": {"readonly": True}, "name": {"readonly": True}, "type": {"readonly": True}, "agreement_type": {"readonly": True}, "account_type": {"readonly": True}, "account_status": {"readonly": True}, "enrollment_details": {"readonly": True}, "has_read_access": {"readonly": True}, } _attribute_map = { "id": {"key": "id", "type": "str"}, "name": {"key": "name", "type": "str"}, "type": {"key": "type", "type": "str"}, "display_name": {"key": "properties.displayName", "type": "str"}, "sold_to": {"key": "properties.soldTo", "type": "AddressDetails"}, "agreement_type": {"key": "properties.agreementType", "type": "str"}, "account_type": {"key": "properties.accountType", "type": "str"}, "account_status": {"key": "properties.accountStatus", "type": "str"}, "billing_profiles": {"key": "properties.billingProfiles", "type": "BillingProfilesOnExpand"}, "enrollment_details": {"key": "properties.enrollmentDetails", "type": "Enrollment"}, "departments": {"key": "properties.departments", "type": "[Department]"}, "enrollment_accounts": {"key": "properties.enrollmentAccounts", "type": "[EnrollmentAccount]"}, "has_read_access": {"key": "properties.hasReadAccess", "type": "bool"}, "notification_email_address": {"key": "properties.notificationEmailAddress", "type": "str"}, } def __init__( self, *, display_name: Optional[str] = None, sold_to: Optional["_models.AddressDetails"] = None, billing_profiles: Optional["_models.BillingProfilesOnExpand"] = None, departments: Optional[List["_models.Department"]] = None, enrollment_accounts: Optional[List["_models.EnrollmentAccount"]] = None, notification_email_address: Optional[str] = None, **kwargs ): """ :keyword display_name: The billing account name. :paramtype display_name: str :keyword sold_to: The address of the individual or organization that is responsible for the billing account. :paramtype sold_to: ~azure.mgmt.billing.models.AddressDetails :keyword billing_profiles: The billing profiles associated with the billing account. By default this is not populated, unless it's specified in $expand. :paramtype billing_profiles: ~azure.mgmt.billing.models.BillingProfilesOnExpand :keyword departments: The departments associated to the enrollment. :paramtype departments: list[~azure.mgmt.billing.models.Department] :keyword enrollment_accounts: The accounts associated to the enrollment. :paramtype enrollment_accounts: list[~azure.mgmt.billing.models.EnrollmentAccount] :keyword notification_email_address: Notification email address, only for legacy accounts. :paramtype notification_email_address: str """ super().__init__(**kwargs) self.display_name = display_name self.sold_to = sold_to self.agreement_type = None self.account_type = None self.account_status = None self.billing_profiles = billing_profiles self.enrollment_details = None self.departments = departments self.enrollment_accounts = enrollment_accounts self.has_read_access = None self.notification_email_address = notification_email_address class BillingAccountListResult(_serialization.Model): """The list of billing accounts. Variables are only populated by the server, and will be ignored when sending a request. :ivar value: The list of billing accounts. :vartype value: list[~azure.mgmt.billing.models.BillingAccount] :ivar next_link: The link (url) to the next page of results. :vartype next_link: str """ _validation = { "value": {"readonly": True}, "next_link": {"readonly": True}, } _attribute_map = { "value": {"key": "value", "type": "[BillingAccount]"}, "next_link": {"key": "nextLink", "type": "str"}, } def __init__(self, **kwargs): """ """ super().__init__(**kwargs) self.value = None self.next_link = None class BillingAccountUpdateRequest(_serialization.Model): # pylint: disable=too-many-instance-attributes """The request properties of the billing account that can be updated. Variables are only populated by the server, and will be ignored when sending a request. :ivar display_name: The billing account name. :vartype display_name: str :ivar sold_to: The address of the individual or organization that is responsible for the billing account. :vartype sold_to: ~azure.mgmt.billing.models.AddressDetails :ivar agreement_type: The type of agreement. Known values are: "MicrosoftCustomerAgreement", "EnterpriseAgreement", "MicrosoftOnlineServicesProgram", and "MicrosoftPartnerAgreement". :vartype agreement_type: str or ~azure.mgmt.billing.models.AgreementType :ivar account_type: The type of customer. Known values are: "Enterprise", "Individual", and "Partner". :vartype account_type: str or ~azure.mgmt.billing.models.AccountType :ivar account_status: The current status of the billing account. Known values are: "Active", "Deleted", "Disabled", "Expired", "Transferred", "Extended", and "Terminated". :vartype account_status: str or ~azure.mgmt.billing.models.AccountStatus :ivar billing_profiles: The billing profiles associated with the billing account. By default this is not populated, unless it's specified in $expand. :vartype billing_profiles: ~azure.mgmt.billing.models.BillingProfilesOnExpand :ivar enrollment_details: The details about the associated legacy enrollment. By default this is not populated, unless it's specified in $expand. :vartype enrollment_details: ~azure.mgmt.billing.models.Enrollment :ivar departments: The departments associated to the enrollment. :vartype departments: list[~azure.mgmt.billing.models.Department] :ivar enrollment_accounts: The accounts associated to the enrollment. :vartype enrollment_accounts: list[~azure.mgmt.billing.models.EnrollmentAccount] :ivar has_read_access: Indicates whether user has read access to the billing account. :vartype has_read_access: bool :ivar notification_email_address: Notification email address, only for legacy accounts. :vartype notification_email_address: str """ _validation = { "agreement_type": {"readonly": True}, "account_type": {"readonly": True}, "account_status": {"readonly": True}, "enrollment_details": {"readonly": True}, "has_read_access": {"readonly": True}, } _attribute_map = { "display_name": {"key": "properties.displayName", "type": "str"}, "sold_to": {"key": "properties.soldTo", "type": "AddressDetails"}, "agreement_type": {"key": "properties.agreementType", "type": "str"}, "account_type": {"key": "properties.accountType", "type": "str"}, "account_status": {"key": "properties.accountStatus", "type": "str"}, "billing_profiles": {"key": "properties.billingProfiles", "type": "BillingProfilesOnExpand"}, "enrollment_details": {"key": "properties.enrollmentDetails", "type": "Enrollment"}, "departments": {"key": "properties.departments", "type": "[Department]"}, "enrollment_accounts": {"key": "properties.enrollmentAccounts", "type": "[EnrollmentAccount]"}, "has_read_access": {"key": "properties.hasReadAccess", "type": "bool"}, "notification_email_address": {"key": "properties.notificationEmailAddress", "type": "str"}, } def __init__( self, *, display_name: Optional[str] = None, sold_to: Optional["_models.AddressDetails"] = None, billing_profiles: Optional["_models.BillingProfilesOnExpand"] = None, departments: Optional[List["_models.Department"]] = None, enrollment_accounts: Optional[List["_models.EnrollmentAccount"]] = None, notification_email_address: Optional[str] = None, **kwargs ): """ :keyword display_name: The billing account name. :paramtype display_name: str :keyword sold_to: The address of the individual or organization that is responsible for the billing account. :paramtype sold_to: ~azure.mgmt.billing.models.AddressDetails :keyword billing_profiles: The billing profiles associated with the billing account. By default this is not populated, unless it's specified in $expand. :paramtype billing_profiles: ~azure.mgmt.billing.models.BillingProfilesOnExpand :keyword departments: The departments associated to the enrollment. :paramtype departments: list[~azure.mgmt.billing.models.Department] :keyword enrollment_accounts: The accounts associated to the enrollment. :paramtype enrollment_accounts: list[~azure.mgmt.billing.models.EnrollmentAccount] :keyword notification_email_address: Notification email address, only for legacy accounts. :paramtype notification_email_address: str """ super().__init__(**kwargs) self.display_name = display_name self.sold_to = sold_to self.agreement_type = None self.account_type = None self.account_status = None self.billing_profiles = billing_profiles self.enrollment_details = None self.departments = departments self.enrollment_accounts = enrollment_accounts self.has_read_access = None self.notification_email_address = notification_email_address class BillingPeriod(Resource): """A billing period resource. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: Resource Id. :vartype id: str :ivar name: Resource name. :vartype name: str :ivar type: Resource type. :vartype type: str :ivar billing_period_start_date: The start of the date range covered by the billing period. :vartype billing_period_start_date: ~datetime.date :ivar billing_period_end_date: The end of the date range covered by the billing period. :vartype billing_period_end_date: ~datetime.date :ivar invoice_ids: Array of invoice ids that associated with. :vartype invoice_ids: list[str] """ _validation = { "id": {"readonly": True}, "name": {"readonly": True}, "type": {"readonly": True}, "billing_period_start_date": {"readonly": True}, "billing_period_end_date": {"readonly": True}, "invoice_ids": {"readonly": True}, } _attribute_map = { "id": {"key": "id", "type": "str"}, "name": {"key": "name", "type": "str"}, "type": {"key": "type", "type": "str"}, "billing_period_start_date": {"key": "properties.billingPeriodStartDate", "type": "date"}, "billing_period_end_date": {"key": "properties.billingPeriodEndDate", "type": "date"}, "invoice_ids": {"key": "properties.invoiceIds", "type": "[str]"}, } def __init__(self, **kwargs): """ """ super().__init__(**kwargs) self.billing_period_start_date = None self.billing_period_end_date = None self.invoice_ids = None class BillingPeriodsListResult(_serialization.Model): """Result of listing billing periods. It contains a list of available billing periods in reverse chronological order. Variables are only populated by the server, and will be ignored when sending a request. :ivar value: The list of billing periods. :vartype value: list[~azure.mgmt.billing.models.BillingPeriod] :ivar next_link: The link (url) to the next page of results. :vartype next_link: str """ _validation = { "value": {"readonly": True}, "next_link": {"readonly": True}, } _attribute_map = { "value": {"key": "value", "type": "[BillingPeriod]"}, "next_link": {"key": "nextLink", "type": "str"}, } def __init__(self, **kwargs): """ """ super().__init__(**kwargs) self.value = None self.next_link = None class BillingPermissionsListResult(_serialization.Model): """Result of list billingPermissions a caller has on a billing account. Variables are only populated by the server, and will be ignored when sending a request. :ivar value: The list of billingPermissions a caller has on a billing account. :vartype value: list[~azure.mgmt.billing.models.BillingPermissionsProperties] :ivar next_link: The link (url) to the next page of results. :vartype next_link: str """ _validation = { "value": {"readonly": True}, "next_link": {"readonly": True}, } _attribute_map = { "value": {"key": "value", "type": "[BillingPermissionsProperties]"}, "next_link": {"key": "nextLink", "type": "str"}, } def __init__(self, **kwargs): """ """ super().__init__(**kwargs) self.value = None self.next_link = None class BillingPermissionsProperties(_serialization.Model): """The set of allowed action and not allowed actions a caller has on a billing account. Variables are only populated by the server, and will be ignored when sending a request. :ivar actions: The set of actions that the caller is allowed to perform. :vartype actions: list[str] :ivar not_actions: The set of actions that the caller is not allowed to perform. :vartype not_actions: list[str] """ _validation = { "actions": {"readonly": True}, "not_actions": {"readonly": True}, } _attribute_map = { "actions": {"key": "actions", "type": "[str]"}, "not_actions": {"key": "notActions", "type": "[str]"}, } def __init__(self, **kwargs): """ """ super().__init__(**kwargs) self.actions = None self.not_actions = None class BillingProfile(Resource): # pylint: disable=too-many-instance-attributes """A billing profile. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: Resource Id. :vartype id: str :ivar name: Resource name. :vartype name: str :ivar type: Resource type. :vartype type: str :ivar display_name: The name of the billing profile. :vartype display_name: str :ivar po_number: The purchase order name that will appear on the invoices generated for the billing profile. :vartype po_number: str :ivar billing_relationship_type: Identifies which services and purchases are paid by a billing profile. Known values are: "Direct", "IndirectCustomer", "IndirectPartner", and "CSPPartner". :vartype billing_relationship_type: str or ~azure.mgmt.billing.models.BillingRelationshipType :ivar bill_to: Billing address. :vartype bill_to: ~azure.mgmt.billing.models.AddressDetails :ivar indirect_relationship_info: Identifies the billing profile that is linked to another billing profile in indirect purchase motion. :vartype indirect_relationship_info: ~azure.mgmt.billing.models.IndirectRelationshipInfo :ivar invoice_email_opt_in: Flag controlling whether the invoices for the billing profile are sent through email. :vartype invoice_email_opt_in: bool :ivar invoice_day: The day of the month when the invoice for the billing profile is generated. :vartype invoice_day: int :ivar currency: The currency in which the charges for the billing profile are billed. :vartype currency: str :ivar enabled_azure_plans: Information about the enabled azure plans. :vartype enabled_azure_plans: list[~azure.mgmt.billing.models.AzurePlan] :ivar invoice_sections: The invoice sections associated to the billing profile. By default this is not populated, unless it's specified in $expand. :vartype invoice_sections: ~azure.mgmt.billing.models.InvoiceSectionsOnExpand :ivar has_read_access: Indicates whether user has read access to the billing profile. :vartype has_read_access: bool :ivar system_id: The system generated unique identifier for a billing profile. :vartype system_id: str :ivar status: The status of the billing profile. Known values are: "Active", "Disabled", and "Warned". :vartype status: str or ~azure.mgmt.billing.models.BillingProfileStatus :ivar status_reason_code: Reason for the specified billing profile status. Known values are: "PastDue", "SpendingLimitReached", and "SpendingLimitExpired". :vartype status_reason_code: str or ~azure.mgmt.billing.models.StatusReasonCode :ivar spending_limit: The billing profile spending limit. Known values are: "Off" and "On". :vartype spending_limit: str or ~azure.mgmt.billing.models.SpendingLimit :ivar target_clouds: Identifies the cloud environments that are associated with a billing profile. This is a system managed optional field and gets updated as the billing profile gets associated with accounts in various clouds. :vartype target_clouds: list[str or ~azure.mgmt.billing.models.TargetCloud] :ivar tags: Tags of billing profiles. :vartype tags: dict[str, str] """ _validation = { "id": {"readonly": True}, "name": {"readonly": True}, "type": {"readonly": True}, "billing_relationship_type": {"readonly": True}, "indirect_relationship_info": {"readonly": True}, "invoice_day": {"readonly": True}, "currency": {"readonly": True}, "has_read_access": {"readonly": True}, "system_id": {"readonly": True}, "status": {"readonly": True}, "status_reason_code": {"readonly": True}, "spending_limit": {"readonly": True}, "target_clouds": {"readonly": True}, } _attribute_map = { "id": {"key": "id", "type": "str"}, "name": {"key": "name", "type": "str"}, "type": {"key": "type", "type": "str"}, "display_name": {"key": "properties.displayName", "type": "str"}, "po_number": {"key": "properties.poNumber", "type": "str"}, "billing_relationship_type": {"key": "properties.billingRelationshipType", "type": "str"}, "bill_to": {"key": "properties.billTo", "type": "AddressDetails"}, "indirect_relationship_info": { "key": "properties.indirectRelationshipInfo", "type": "IndirectRelationshipInfo", }, "invoice_email_opt_in": {"key": "properties.invoiceEmailOptIn", "type": "bool"}, "invoice_day": {"key": "properties.invoiceDay", "type": "int"}, "currency": {"key": "properties.currency", "type": "str"}, "enabled_azure_plans": {"key": "properties.enabledAzurePlans", "type": "[AzurePlan]"}, "invoice_sections": {"key": "properties.invoiceSections", "type": "InvoiceSectionsOnExpand"}, "has_read_access": {"key": "properties.hasReadAccess", "type": "bool"}, "system_id": {"key": "properties.systemId", "type": "str"}, "status": {"key": "properties.status", "type": "str"}, "status_reason_code": {"key": "properties.statusReasonCode", "type": "str"}, "spending_limit": {"key": "properties.spendingLimit", "type": "str"}, "target_clouds": {"key": "properties.targetClouds", "type": "[str]"}, "tags": {"key": "properties.tags", "type": "{str}"}, } def __init__( self, *, display_name: Optional[str] = None, po_number: Optional[str] = None, bill_to: Optional["_models.AddressDetails"] = None, invoice_email_opt_in: Optional[bool] = None, enabled_azure_plans: Optional[List["_models.AzurePlan"]] = None, invoice_sections: Optional["_models.InvoiceSectionsOnExpand"] = None, tags: Optional[Dict[str, str]] = None, **kwargs ): """ :keyword display_name: The name of the billing profile. :paramtype display_name: str :keyword po_number: The purchase order name that will appear on the invoices generated for the billing profile. :paramtype po_number: str :keyword bill_to: Billing address. :paramtype bill_to: ~azure.mgmt.billing.models.AddressDetails :keyword invoice_email_opt_in: Flag controlling whether the invoices for the billing profile are sent through email. :paramtype invoice_email_opt_in: bool :keyword enabled_azure_plans: Information about the enabled azure plans. :paramtype enabled_azure_plans: list[~azure.mgmt.billing.models.AzurePlan] :keyword invoice_sections: The invoice sections associated to the billing profile. By default this is not populated, unless it's specified in $expand. :paramtype invoice_sections: ~azure.mgmt.billing.models.InvoiceSectionsOnExpand :keyword tags: Tags of billing profiles. :paramtype tags: dict[str, str] """ super().__init__(**kwargs) self.display_name = display_name self.po_number = po_number self.billing_relationship_type = None self.bill_to = bill_to self.indirect_relationship_info = None self.invoice_email_opt_in = invoice_email_opt_in self.invoice_day = None self.currency = None self.enabled_azure_plans = enabled_azure_plans self.invoice_sections = invoice_sections self.has_read_access = None self.system_id = None self.status = None self.status_reason_code = None self.spending_limit = None self.target_clouds = None self.tags = tags class BillingProfileCreationRequest(_serialization.Model): """The request parameters for creating a new billing profile. :ivar display_name: The name of the billing profile. :vartype display_name: str :ivar po_number: The purchase order name that will appear on the invoices generated for the billing profile. :vartype po_number: str :ivar bill_to: The address of the individual or organization that is responsible for the billing profile. :vartype bill_to: ~azure.mgmt.billing.models.AddressDetails :ivar invoice_email_opt_in: Flag controlling whether the invoices for the billing profile are sent through email. :vartype invoice_email_opt_in: bool :ivar enabled_azure_plans: Enabled azure plans for the billing profile. :vartype enabled_azure_plans: list[~azure.mgmt.billing.models.AzurePlan] """ _attribute_map = { "display_name": {"key": "displayName", "type": "str"}, "po_number": {"key": "poNumber", "type": "str"}, "bill_to": {"key": "billTo", "type": "AddressDetails"}, "invoice_email_opt_in": {"key": "invoiceEmailOptIn", "type": "bool"}, "enabled_azure_plans": {"key": "enabledAzurePlans", "type": "[AzurePlan]"}, } def __init__( self, *, display_name: Optional[str] = None, po_number: Optional[str] = None, bill_to: Optional["_models.AddressDetails"] = None, invoice_email_opt_in: Optional[bool] = None, enabled_azure_plans: Optional[List["_models.AzurePlan"]] = None, **kwargs ): """ :keyword display_name: The name of the billing profile. :paramtype display_name: str :keyword po_number: The purchase order name that will appear on the invoices generated for the billing profile. :paramtype po_number: str :keyword bill_to: The address of the individual or organization that is responsible for the billing profile. :paramtype bill_to: ~azure.mgmt.billing.models.AddressDetails :keyword invoice_email_opt_in: Flag controlling whether the invoices for the billing profile are sent through email. :paramtype invoice_email_opt_in: bool :keyword enabled_azure_plans: Enabled azure plans for the billing profile. :paramtype enabled_azure_plans: list[~azure.mgmt.billing.models.AzurePlan] """ super().__init__(**kwargs) self.display_name = display_name self.po_number = po_number self.bill_to = bill_to self.invoice_email_opt_in = invoice_email_opt_in self.enabled_azure_plans = enabled_azure_plans class BillingProfileInfo(_serialization.Model): """Details about billing profile associated with agreement and available only for specific agreements. :ivar billing_profile_id: The unique identifier for the billing profile. :vartype billing_profile_id: str :ivar billing_profile_display_name: The name of the billing profile. :vartype billing_profile_display_name: str :ivar indirect_relationship_organization_name: Billing account name. This property is available for a specific type of agreement. :vartype indirect_relationship_organization_name: str """ _attribute_map = { "billing_profile_id": {"key": "billingProfileId", "type": "str"}, "billing_profile_display_name": {"key": "billingProfileDisplayName", "type": "str"}, "indirect_relationship_organization_name": {"key": "indirectRelationshipOrganizationName", "type": "str"}, } def __init__( self, *, billing_profile_id: Optional[str] = None, billing_profile_display_name: Optional[str] = None, indirect_relationship_organization_name: Optional[str] = None, **kwargs ): """ :keyword billing_profile_id: The unique identifier for the billing profile. :paramtype billing_profile_id: str :keyword billing_profile_display_name: The name of the billing profile. :paramtype billing_profile_display_name: str :keyword indirect_relationship_organization_name: Billing account name. This property is available for a specific type of agreement. :paramtype indirect_relationship_organization_name: str """ super().__init__(**kwargs) self.billing_profile_id = billing_profile_id self.billing_profile_display_name = billing_profile_display_name self.indirect_relationship_organization_name = indirect_relationship_organization_name class BillingProfileListResult(_serialization.Model): """The list of billing profiles. Variables are only populated by the server, and will be ignored when sending a request. :ivar value: The list of billing profiles. :vartype value: list[~azure.mgmt.billing.models.BillingProfile] :ivar total_count: Total number of records. :vartype total_count: int :ivar next_link: The link (url) to the next page of results. :vartype next_link: str """ _validation = { "value": {"readonly": True}, "total_count": {"readonly": True}, "next_link": {"readonly": True}, } _attribute_map = { "value": {"key": "value", "type": "[BillingProfile]"}, "total_count": {"key": "totalCount", "type": "int"}, "next_link": {"key": "nextLink", "type": "str"}, } def __init__(self, **kwargs): """ """ super().__init__(**kwargs) self.value = None self.total_count = None self.next_link = None class BillingProfilesOnExpand(_serialization.Model): """The billing profiles associated with the billing account. By default this is not populated, unless it's specified in $expand. Variables are only populated by the server, and will be ignored when sending a request. :ivar has_more_results: Indicates whether there are more billing profiles than the ones listed in this collection. The collection lists a maximum of 50 billing profiles. To get all billing profiles, use the list billing profiles API. :vartype has_more_results: bool :ivar value: The billing profiles associated with the billing account. :vartype value: list[~azure.mgmt.billing.models.BillingProfile] """ _validation = { "has_more_results": {"readonly": True}, } _attribute_map = { "has_more_results": {"key": "hasMoreResults", "type": "bool"}, "value": {"key": "value", "type": "[BillingProfile]"}, } def __init__(self, *, value: Optional[List["_models.BillingProfile"]] = None, **kwargs): """ :keyword value: The billing profiles associated with the billing account. :paramtype value: list[~azure.mgmt.billing.models.BillingProfile] """ super().__init__(**kwargs) self.has_more_results = None self.value = value class BillingProperty(Resource): # pylint: disable=too-many-instance-attributes """A billing property. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: Resource Id. :vartype id: str :ivar name: Resource name. :vartype name: str :ivar type: Resource type. :vartype type: str :ivar account_admin_notification_email_address: The email address on which the account admin gets all Azure notifications. :vartype account_admin_notification_email_address: str :ivar billing_tenant_id: The Azure AD tenant ID of the billing account for the subscription. :vartype billing_tenant_id: str :ivar billing_account_id: The ID of the billing account to which the subscription is billed. :vartype billing_account_id: str :ivar billing_account_display_name: The name of the billing account to which the subscription is billed. :vartype billing_account_display_name: str :ivar billing_profile_id: The ID of the billing profile to which the subscription is billed. :vartype billing_profile_id: str :ivar billing_profile_display_name: The name of the billing profile to which the subscription is billed. :vartype billing_profile_display_name: str :ivar billing_profile_status: The status of the billing profile. Known values are: "Active", "Disabled", and "Warned". :vartype billing_profile_status: str or ~azure.mgmt.billing.models.BillingProfileStatus :ivar billing_profile_status_reason_code: Reason for the specified billing profile status. Known values are: "PastDue", "SpendingLimitReached", and "SpendingLimitExpired". :vartype billing_profile_status_reason_code: str or ~azure.mgmt.billing.models.BillingProfileStatusReasonCode :ivar billing_profile_spending_limit: The billing profile spending limit. Known values are: "Off" and "On". :vartype billing_profile_spending_limit: str or ~azure.mgmt.billing.models.BillingProfileSpendingLimit :ivar cost_center: The cost center applied to the subscription. :vartype cost_center: str :ivar invoice_section_id: The ID of the invoice section to which the subscription is billed. :vartype invoice_section_id: str :ivar invoice_section_display_name: The name of the invoice section to which the subscription is billed. :vartype invoice_section_display_name: str :ivar is_account_admin: Indicates whether user is the account admin. :vartype is_account_admin: bool :ivar product_id: The product ID of the Azure plan. :vartype product_id: str :ivar product_name: The product name of the Azure plan. :vartype product_name: str :ivar sku_id: The sku ID of the Azure plan for the subscription. :vartype sku_id: str :ivar sku_description: The sku description of the Azure plan for the subscription. :vartype sku_description: str """ _validation = { "id": {"readonly": True}, "name": {"readonly": True}, "type": {"readonly": True}, "account_admin_notification_email_address": {"readonly": True}, "billing_tenant_id": {"readonly": True}, "billing_account_id": {"readonly": True}, "billing_account_display_name": {"readonly": True}, "billing_profile_id": {"readonly": True}, "billing_profile_display_name": {"readonly": True}, "billing_profile_status": {"readonly": True}, "billing_profile_status_reason_code": {"readonly": True}, "billing_profile_spending_limit": {"readonly": True}, "invoice_section_id": {"readonly": True}, "invoice_section_display_name": {"readonly": True}, "is_account_admin": {"readonly": True}, "product_id": {"readonly": True}, "product_name": {"readonly": True}, "sku_id": {"readonly": True}, "sku_description": {"readonly": True}, } _attribute_map = { "id": {"key": "id", "type": "str"}, "name": {"key": "name", "type": "str"}, "type": {"key": "type", "type": "str"}, "account_admin_notification_email_address": { "key": "properties.accountAdminNotificationEmailAddress", "type": "str", }, "billing_tenant_id": {"key": "properties.billingTenantId", "type": "str"}, "billing_account_id": {"key": "properties.billingAccountId", "type": "str"}, "billing_account_display_name": {"key": "properties.billingAccountDisplayName", "type": "str"}, "billing_profile_id": {"key": "properties.billingProfileId", "type": "str"}, "billing_profile_display_name": {"key": "properties.billingProfileDisplayName", "type": "str"}, "billing_profile_status": {"key": "properties.billingProfileStatus", "type": "str"}, "billing_profile_status_reason_code": {"key": "properties.billingProfileStatusReasonCode", "type": "str"}, "billing_profile_spending_limit": {"key": "properties.billingProfileSpendingLimit", "type": "str"}, "cost_center": {"key": "properties.costCenter", "type": "str"}, "invoice_section_id": {"key": "properties.invoiceSectionId", "type": "str"}, "invoice_section_display_name": {"key": "properties.invoiceSectionDisplayName", "type": "str"}, "is_account_admin": {"key": "properties.isAccountAdmin", "type": "bool"}, "product_id": {"key": "properties.productId", "type": "str"}, "product_name": {"key": "properties.productName", "type": "str"}, "sku_id": {"key": "properties.skuId", "type": "str"}, "sku_description": {"key": "properties.skuDescription", "type": "str"}, } def __init__(self, *, cost_center: Optional[str] = None, **kwargs): """ :keyword cost_center: The cost center applied to the subscription. :paramtype cost_center: str """ super().__init__(**kwargs) self.account_admin_notification_email_address = None self.billing_tenant_id = None self.billing_account_id = None self.billing_account_display_name = None self.billing_profile_id = None self.billing_profile_display_name = None self.billing_profile_status = None self.billing_profile_status_reason_code = None self.billing_profile_spending_limit = None self.cost_center = cost_center self.invoice_section_id = None self.invoice_section_display_name = None self.is_account_admin = None self.product_id = None self.product_name = None self.sku_id = None self.sku_description = None class BillingRoleAssignment(Resource): # pylint: disable=too-many-instance-attributes """The role assignment. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: Resource Id. :vartype id: str :ivar name: Resource name. :vartype name: str :ivar type: Resource type. :vartype type: str :ivar created_on: The date the role assignment was created. :vartype created_on: str :ivar created_by_principal_tenant_id: The tenant Id of the user who created the role assignment. :vartype created_by_principal_tenant_id: str :ivar created_by_principal_id: The principal Id of the user who created the role assignment. :vartype created_by_principal_id: str :ivar created_by_user_email_address: The email address of the user who created the role assignment. :vartype created_by_user_email_address: str :ivar principal_id: The principal id of the user to whom the role was assigned. :vartype principal_id: str :ivar principal_tenant_id: The principal tenant id of the user to whom the role was assigned. :vartype principal_tenant_id: str :ivar role_definition_id: The ID of the role definition. :vartype role_definition_id: str :ivar scope: The scope at which the role was assigned. :vartype scope: str :ivar user_authentication_type: The authentication type. :vartype user_authentication_type: str :ivar user_email_address: The email address of the user. :vartype user_email_address: str """ _validation = { "id": {"readonly": True}, "name": {"readonly": True}, "type": {"readonly": True}, "created_on": {"readonly": True}, "created_by_principal_tenant_id": {"readonly": True}, "created_by_principal_id": {"readonly": True}, "created_by_user_email_address": {"readonly": True}, "scope": {"readonly": True}, } _attribute_map = { "id": {"key": "id", "type": "str"}, "name": {"key": "name", "type": "str"}, "type": {"key": "type", "type": "str"}, "created_on": {"key": "properties.createdOn", "type": "str"}, "created_by_principal_tenant_id": {"key": "properties.createdByPrincipalTenantId", "type": "str"}, "created_by_principal_id": {"key": "properties.createdByPrincipalId", "type": "str"}, "created_by_user_email_address": {"key": "properties.createdByUserEmailAddress", "type": "str"}, "principal_id": {"key": "properties.principalId", "type": "str"}, "principal_tenant_id": {"key": "properties.principalTenantId", "type": "str"}, "role_definition_id": {"key": "properties.roleDefinitionId", "type": "str"}, "scope": {"key": "properties.scope", "type": "str"}, "user_authentication_type": {"key": "properties.userAuthenticationType", "type": "str"}, "user_email_address": {"key": "properties.userEmailAddress", "type": "str"}, } def __init__( self, *, principal_id: Optional[str] = None, principal_tenant_id: Optional[str] = None, role_definition_id: Optional[str] = None, user_authentication_type: Optional[str] = None, user_email_address: Optional[str] = None, **kwargs ): """ :keyword principal_id: The principal id of the user to whom the role was assigned. :paramtype principal_id: str :keyword principal_tenant_id: The principal tenant id of the user to whom the role was assigned. :paramtype principal_tenant_id: str :keyword role_definition_id: The ID of the role definition. :paramtype role_definition_id: str :keyword user_authentication_type: The authentication type. :paramtype user_authentication_type: str :keyword user_email_address: The email address of the user. :paramtype user_email_address: str """ super().__init__(**kwargs) self.created_on = None self.created_by_principal_tenant_id = None self.created_by_principal_id = None self.created_by_user_email_address = None self.principal_id = principal_id self.principal_tenant_id = principal_tenant_id self.role_definition_id = role_definition_id self.scope = None self.user_authentication_type = user_authentication_type self.user_email_address = user_email_address class BillingRoleAssignmentListResult(_serialization.Model): """The list of role assignments. Variables are only populated by the server, and will be ignored when sending a request. :ivar value: The list of role assignments. :vartype value: list[~azure.mgmt.billing.models.BillingRoleAssignment] :ivar next_link: The link (url) to the next page of results. :vartype next_link: str """ _validation = { "value": {"readonly": True}, "next_link": {"readonly": True}, } _attribute_map = { "value": {"key": "value", "type": "[BillingRoleAssignment]"}, "next_link": {"key": "nextLink", "type": "str"}, } def __init__(self, **kwargs): """ """ super().__init__(**kwargs) self.value = None self.next_link = None class BillingRoleDefinition(Resource): """The properties of a role definition. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: Resource Id. :vartype id: str :ivar name: Resource name. :vartype name: str :ivar type: Resource type. :vartype type: str :ivar description: The role description. :vartype description: str :ivar permissions: The billingPermissions the role has. :vartype permissions: list[~azure.mgmt.billing.models.BillingPermissionsProperties] :ivar role_name: The name of the role. :vartype role_name: str """ _validation = { "id": {"readonly": True}, "name": {"readonly": True}, "type": {"readonly": True}, "description": {"readonly": True}, "role_name": {"readonly": True}, } _attribute_map = { "id": {"key": "id", "type": "str"}, "name": {"key": "name", "type": "str"}, "type": {"key": "type", "type": "str"}, "description": {"key": "properties.description", "type": "str"}, "permissions": {"key": "properties.permissions", "type": "[BillingPermissionsProperties]"}, "role_name": {"key": "properties.roleName", "type": "str"}, } def __init__(self, *, permissions: Optional[List["_models.BillingPermissionsProperties"]] = None, **kwargs): """ :keyword permissions: The billingPermissions the role has. :paramtype permissions: list[~azure.mgmt.billing.models.BillingPermissionsProperties] """ super().__init__(**kwargs) self.description = None self.permissions = permissions self.role_name = None class BillingRoleDefinitionListResult(_serialization.Model): """The list of role definitions. Variables are only populated by the server, and will be ignored when sending a request. :ivar value: The role definitions. :vartype value: list[~azure.mgmt.billing.models.BillingRoleDefinition] :ivar next_link: The link (url) to the next page of results. :vartype next_link: str """ _validation = { "value": {"readonly": True}, "next_link": {"readonly": True}, } _attribute_map = { "value": {"key": "value", "type": "[BillingRoleDefinition]"}, "next_link": {"key": "nextLink", "type": "str"}, } def __init__(self, **kwargs): """ """ super().__init__(**kwargs) self.value = None self.next_link = None class BillingSubscription(Resource): # pylint: disable=too-many-instance-attributes """A billing subscription. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: Resource Id. :vartype id: str :ivar name: Resource name. :vartype name: str :ivar type: Resource type. :vartype type: str :ivar display_name: The name of the subscription. :vartype display_name: str :ivar subscription_id: The ID of the subscription. :vartype subscription_id: str :ivar subscription_billing_status: The current billing status of the subscription. Known values are: "Active", "Inactive", "Abandoned", "Deleted", and "Warning". :vartype subscription_billing_status: str or ~azure.mgmt.billing.models.BillingSubscriptionStatusType :ivar last_month_charges: The last month charges. :vartype last_month_charges: ~azure.mgmt.billing.models.Amount :ivar month_to_date_charges: The current month to date charges. :vartype month_to_date_charges: ~azure.mgmt.billing.models.Amount :ivar billing_profile_id: The ID of the billing profile to which the subscription is billed. :vartype billing_profile_id: str :ivar billing_profile_display_name: The name of the billing profile to which the subscription is billed. :vartype billing_profile_display_name: str :ivar cost_center: The cost center applied to the subscription. :vartype cost_center: str :ivar customer_id: The ID of the customer for whom the subscription was created. The field is applicable only for Microsoft Partner Agreement billing account. :vartype customer_id: str :ivar customer_display_name: The name of the customer for whom the subscription was created. The field is applicable only for Microsoft Partner Agreement billing account. :vartype customer_display_name: str :ivar invoice_section_id: The ID of the invoice section to which the subscription is billed. :vartype invoice_section_id: str :ivar invoice_section_display_name: The name of the invoice section to which the subscription is billed. :vartype invoice_section_display_name: str :ivar reseller: Reseller for this subscription. :vartype reseller: ~azure.mgmt.billing.models.Reseller :ivar sku_id: The sku ID of the Azure plan for the subscription. :vartype sku_id: str :ivar sku_description: The sku description of the Azure plan for the subscription. :vartype sku_description: str :ivar suspension_reasons: The suspension reason for a subscription. Applies only to subscriptions in Microsoft Online Services Program billing accounts. :vartype suspension_reasons: list[str] """ _validation = { "id": {"readonly": True}, "name": {"readonly": True}, "type": {"readonly": True}, "display_name": {"readonly": True}, "subscription_id": {"readonly": True}, "last_month_charges": {"readonly": True}, "month_to_date_charges": {"readonly": True}, "billing_profile_id": {"readonly": True}, "billing_profile_display_name": {"readonly": True}, "customer_id": {"readonly": True}, "customer_display_name": {"readonly": True}, "invoice_section_id": {"readonly": True}, "invoice_section_display_name": {"readonly": True}, "reseller": {"readonly": True}, "sku_description": {"readonly": True}, "suspension_reasons": {"readonly": True}, } _attribute_map = { "id": {"key": "id", "type": "str"}, "name": {"key": "name", "type": "str"}, "type": {"key": "type", "type": "str"}, "display_name": {"key": "properties.displayName", "type": "str"}, "subscription_id": {"key": "properties.subscriptionId", "type": "str"}, "subscription_billing_status": {"key": "properties.subscriptionBillingStatus", "type": "str"}, "last_month_charges": {"key": "properties.lastMonthCharges", "type": "Amount"}, "month_to_date_charges": {"key": "properties.monthToDateCharges", "type": "Amount"}, "billing_profile_id": {"key": "properties.billingProfileId", "type": "str"}, "billing_profile_display_name": {"key": "properties.billingProfileDisplayName", "type": "str"}, "cost_center": {"key": "properties.costCenter", "type": "str"}, "customer_id": {"key": "properties.customerId", "type": "str"}, "customer_display_name": {"key": "properties.customerDisplayName", "type": "str"}, "invoice_section_id": {"key": "properties.invoiceSectionId", "type": "str"}, "invoice_section_display_name": {"key": "properties.invoiceSectionDisplayName", "type": "str"}, "reseller": {"key": "properties.reseller", "type": "Reseller"}, "sku_id": {"key": "properties.skuId", "type": "str"}, "sku_description": {"key": "properties.skuDescription", "type": "str"}, "suspension_reasons": {"key": "properties.suspensionReasons", "type": "[str]"}, } def __init__( self, *, subscription_billing_status: Optional[Union[str, "_models.BillingSubscriptionStatusType"]] = None, cost_center: Optional[str] = None, sku_id: Optional[str] = None, **kwargs ): """ :keyword subscription_billing_status: The current billing status of the subscription. Known values are: "Active", "Inactive", "Abandoned", "Deleted", and "Warning". :paramtype subscription_billing_status: str or ~azure.mgmt.billing.models.BillingSubscriptionStatusType :keyword cost_center: The cost center applied to the subscription. :paramtype cost_center: str :keyword sku_id: The sku ID of the Azure plan for the subscription. :paramtype sku_id: str """ super().__init__(**kwargs) self.display_name = None self.subscription_id = None self.subscription_billing_status = subscription_billing_status self.last_month_charges = None self.month_to_date_charges = None self.billing_profile_id = None self.billing_profile_display_name = None self.cost_center = cost_center self.customer_id = None self.customer_display_name = None self.invoice_section_id = None self.invoice_section_display_name = None self.reseller = None self.sku_id = sku_id self.sku_description = None self.suspension_reasons = None class BillingSubscriptionsListResult(_serialization.Model): """The list of billing subscriptions. Variables are only populated by the server, and will be ignored when sending a request. :ivar value: The list of billing subscriptions. :vartype value: list[~azure.mgmt.billing.models.BillingSubscription] :ivar total_count: Total number of records. :vartype total_count: int :ivar next_link: The link (url) to the next page of results. :vartype next_link: str """ _validation = { "value": {"readonly": True}, "total_count": {"readonly": True}, "next_link": {"readonly": True}, } _attribute_map = { "value": {"key": "value", "type": "[BillingSubscription]"}, "total_count": {"key": "totalCount", "type": "int"}, "next_link": {"key": "nextLink", "type": "str"}, } def __init__(self, **kwargs): """ """ super().__init__(**kwargs) self.value = None self.total_count = None self.next_link = None class Customer(Resource): """A partner's customer. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: Resource Id. :vartype id: str :ivar name: Resource name. :vartype name: str :ivar type: Resource type. :vartype type: str :ivar billing_profile_id: The ID of the billing profile for the invoice section. :vartype billing_profile_id: str :ivar billing_profile_display_name: The name of the billing profile for the invoice section. :vartype billing_profile_display_name: str :ivar display_name: The name of the customer. :vartype display_name: str :ivar enabled_azure_plans: Azure plans enabled for the customer. :vartype enabled_azure_plans: list[~azure.mgmt.billing.models.AzurePlan] :ivar resellers: The list of resellers for which an Azure plan is enabled for the customer. :vartype resellers: list[~azure.mgmt.billing.models.Reseller] """ _validation = { "id": {"readonly": True}, "name": {"readonly": True}, "type": {"readonly": True}, "billing_profile_id": {"readonly": True}, "billing_profile_display_name": {"readonly": True}, } _attribute_map = { "id": {"key": "id", "type": "str"}, "name": {"key": "name", "type": "str"}, "type": {"key": "type", "type": "str"}, "billing_profile_id": {"key": "properties.billingProfileId", "type": "str"}, "billing_profile_display_name": {"key": "properties.billingProfileDisplayName", "type": "str"}, "display_name": {"key": "properties.displayName", "type": "str"}, "enabled_azure_plans": {"key": "properties.enabledAzurePlans", "type": "[AzurePlan]"}, "resellers": {"key": "properties.resellers", "type": "[Reseller]"}, } def __init__( self, *, display_name: Optional[str] = None, enabled_azure_plans: Optional[List["_models.AzurePlan"]] = None, resellers: Optional[List["_models.Reseller"]] = None, **kwargs ): """ :keyword display_name: The name of the customer. :paramtype display_name: str :keyword enabled_azure_plans: Azure plans enabled for the customer. :paramtype enabled_azure_plans: list[~azure.mgmt.billing.models.AzurePlan] :keyword resellers: The list of resellers for which an Azure plan is enabled for the customer. :paramtype resellers: list[~azure.mgmt.billing.models.Reseller] """ super().__init__(**kwargs) self.billing_profile_id = None self.billing_profile_display_name = None self.display_name = display_name self.enabled_azure_plans = enabled_azure_plans self.resellers = resellers class CustomerListResult(_serialization.Model): """The list of customers. Variables are only populated by the server, and will be ignored when sending a request. :ivar value: The list of customers. :vartype value: list[~azure.mgmt.billing.models.Customer] :ivar total_count: Total number of records. :vartype total_count: int :ivar next_link: The link (url) to the next page of results. :vartype next_link: str """ _validation = { "value": {"readonly": True}, "total_count": {"readonly": True}, "next_link": {"readonly": True}, } _attribute_map = { "value": {"key": "value", "type": "[Customer]"}, "total_count": {"key": "totalCount", "type": "int"}, "next_link": {"key": "nextLink", "type": "str"}, } def __init__(self, **kwargs): """ """ super().__init__(**kwargs) self.value = None self.total_count = None self.next_link = None class CustomerPolicy(Resource): """The customer's Policy. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: Resource Id. :vartype id: str :ivar name: Resource name. :vartype name: str :ivar type: Resource type. :vartype type: str :ivar view_charges: The policy that controls whether the users in customer's organization can view charges at pay-as-you-go prices. Known values are: "Allowed" and "NotAllowed". :vartype view_charges: str or ~azure.mgmt.billing.models.ViewCharges """ _validation = { "id": {"readonly": True}, "name": {"readonly": True}, "type": {"readonly": True}, } _attribute_map = { "id": {"key": "id", "type": "str"}, "name": {"key": "name", "type": "str"}, "type": {"key": "type", "type": "str"}, "view_charges": {"key": "properties.viewCharges", "type": "str"}, } def __init__(self, *, view_charges: Optional[Union[str, "_models.ViewCharges"]] = None, **kwargs): """ :keyword view_charges: The policy that controls whether the users in customer's organization can view charges at pay-as-you-go prices. Known values are: "Allowed" and "NotAllowed". :paramtype view_charges: str or ~azure.mgmt.billing.models.ViewCharges """ super().__init__(**kwargs) self.view_charges = view_charges class Department(Resource): """A department. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: Resource Id. :vartype id: str :ivar name: Resource name. :vartype name: str :ivar type: Resource type. :vartype type: str :ivar department_name: The name of the department. :vartype department_name: str :ivar cost_center: The cost center associated with the department. :vartype cost_center: str :ivar status: The status of the department. :vartype status: str :ivar enrollment_accounts: Associated enrollment accounts. By default this is not populated, unless it's specified in $expand. :vartype enrollment_accounts: list[~azure.mgmt.billing.models.EnrollmentAccount] """ _validation = { "id": {"readonly": True}, "name": {"readonly": True}, "type": {"readonly": True}, } _attribute_map = { "id": {"key": "id", "type": "str"}, "name": {"key": "name", "type": "str"}, "type": {"key": "type", "type": "str"}, "department_name": {"key": "properties.departmentName", "type": "str"}, "cost_center": {"key": "properties.costCenter", "type": "str"}, "status": {"key": "properties.status", "type": "str"}, "enrollment_accounts": {"key": "properties.enrollmentAccounts", "type": "[EnrollmentAccount]"}, } def __init__( self, *, department_name: Optional[str] = None, cost_center: Optional[str] = None, status: Optional[str] = None, enrollment_accounts: Optional[List["_models.EnrollmentAccount"]] = None, **kwargs ): """ :keyword department_name: The name of the department. :paramtype department_name: str :keyword cost_center: The cost center associated with the department. :paramtype cost_center: str :keyword status: The status of the department. :paramtype status: str :keyword enrollment_accounts: Associated enrollment accounts. By default this is not populated, unless it's specified in $expand. :paramtype enrollment_accounts: list[~azure.mgmt.billing.models.EnrollmentAccount] """ super().__init__(**kwargs) self.department_name = department_name self.cost_center = cost_center self.status = status self.enrollment_accounts = enrollment_accounts class Document(_serialization.Model): """The properties of a document. Variables are only populated by the server, and will be ignored when sending a request. :ivar kind: The type of the document. Known values are: "Invoice", "VoidNote", "TaxReceipt", and "CreditNote". :vartype kind: str or ~azure.mgmt.billing.models.DocumentType :ivar url: Document URL. :vartype url: str :ivar source: The source of the document. ENF for Brazil and DRS for rest of the world. Known values are: "DRS" and "ENF". :vartype source: str or ~azure.mgmt.billing.models.DocumentSource """ _validation = { "kind": {"readonly": True}, "url": {"readonly": True}, "source": {"readonly": True}, } _attribute_map = { "kind": {"key": "kind", "type": "str"}, "url": {"key": "url", "type": "str"}, "source": {"key": "source", "type": "str"}, } def __init__(self, **kwargs): """ """ super().__init__(**kwargs) self.kind = None self.url = None self.source = None class DownloadUrl(_serialization.Model): """A secure URL that can be used to download a an entity until the URL expires. Variables are only populated by the server, and will be ignored when sending a request. :ivar expiry_time: The time in UTC when the download URL will expire. :vartype expiry_time: ~datetime.datetime :ivar url: The URL to the PDF file. :vartype url: str """ _validation = { "expiry_time": {"readonly": True}, "url": {"readonly": True}, } _attribute_map = { "expiry_time": {"key": "expiryTime", "type": "iso-8601"}, "url": {"key": "url", "type": "str"}, } def __init__(self, **kwargs): """ """ super().__init__(**kwargs) self.expiry_time = None self.url = None class Enrollment(_serialization.Model): """The properties of an enrollment. Variables are only populated by the server, and will be ignored when sending a request. :ivar start_date: The start date of the enrollment. :vartype start_date: ~datetime.datetime :ivar end_date: The end date of the enrollment. :vartype end_date: ~datetime.datetime :ivar currency: The billing currency for the enrollment. :vartype currency: str :ivar channel: The channel type of the enrollment. :vartype channel: str :ivar policies: The policies for Enterprise Agreement enrollments. :vartype policies: ~azure.mgmt.billing.models.EnrollmentPolicies :ivar language: The language for the enrollment. :vartype language: str :ivar country_code: The country code of the enrollment. :vartype country_code: str :ivar status: The current status of the enrollment. :vartype status: str :ivar billing_cycle: The billing cycle for the enrollment. :vartype billing_cycle: str """ _validation = { "currency": {"readonly": True}, "channel": {"readonly": True}, "policies": {"readonly": True}, "language": {"readonly": True}, "country_code": {"readonly": True}, "status": {"readonly": True}, "billing_cycle": {"readonly": True}, } _attribute_map = { "start_date": {"key": "startDate", "type": "iso-8601"}, "end_date": {"key": "endDate", "type": "iso-8601"}, "currency": {"key": "currency", "type": "str"}, "channel": {"key": "channel", "type": "str"}, "policies": {"key": "policies", "type": "EnrollmentPolicies"}, "language": {"key": "language", "type": "str"}, "country_code": {"key": "countryCode", "type": "str"}, "status": {"key": "status", "type": "str"}, "billing_cycle": {"key": "billingCycle", "type": "str"}, } def __init__( self, *, start_date: Optional[datetime.datetime] = None, end_date: Optional[datetime.datetime] = None, **kwargs ): """ :keyword start_date: The start date of the enrollment. :paramtype start_date: ~datetime.datetime :keyword end_date: The end date of the enrollment. :paramtype end_date: ~datetime.datetime """ super().__init__(**kwargs) self.start_date = start_date self.end_date = end_date self.currency = None self.channel = None self.policies = None self.language = None self.country_code = None self.status = None self.billing_cycle = None class EnrollmentAccount(Resource): # pylint: disable=too-many-instance-attributes """An enrollment account. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: Resource Id. :vartype id: str :ivar name: Resource name. :vartype name: str :ivar type: Resource type. :vartype type: str :ivar account_name: The name of the enrollment account. :vartype account_name: str :ivar cost_center: The cost center associated with the enrollment account. :vartype cost_center: str :ivar account_owner: The owner of the enrollment account. :vartype account_owner: str :ivar account_owner_email: The enrollment account owner email address. :vartype account_owner_email: str :ivar status: The status of the enrollment account. :vartype status: str :ivar start_date: The start date of the enrollment account. :vartype start_date: ~datetime.datetime :ivar end_date: The end date of the enrollment account. :vartype end_date: ~datetime.datetime :ivar department: Associated department. By default this is not populated, unless it's specified in $expand. :vartype department: ~azure.mgmt.billing.models.Department """ _validation = { "id": {"readonly": True}, "name": {"readonly": True}, "type": {"readonly": True}, } _attribute_map = { "id": {"key": "id", "type": "str"}, "name": {"key": "name", "type": "str"}, "type": {"key": "type", "type": "str"}, "account_name": {"key": "properties.accountName", "type": "str"}, "cost_center": {"key": "properties.costCenter", "type": "str"}, "account_owner": {"key": "properties.accountOwner", "type": "str"}, "account_owner_email": {"key": "properties.accountOwnerEmail", "type": "str"}, "status": {"key": "properties.status", "type": "str"}, "start_date": {"key": "properties.startDate", "type": "iso-8601"}, "end_date": {"key": "properties.endDate", "type": "iso-8601"}, "department": {"key": "properties.department", "type": "Department"}, } def __init__( self, *, account_name: Optional[str] = None, cost_center: Optional[str] = None, account_owner: Optional[str] = None, account_owner_email: Optional[str] = None, status: Optional[str] = None, start_date: Optional[datetime.datetime] = None, end_date: Optional[datetime.datetime] = None, department: Optional["_models.Department"] = None, **kwargs ): """ :keyword account_name: The name of the enrollment account. :paramtype account_name: str :keyword cost_center: The cost center associated with the enrollment account. :paramtype cost_center: str :keyword account_owner: The owner of the enrollment account. :paramtype account_owner: str :keyword account_owner_email: The enrollment account owner email address. :paramtype account_owner_email: str :keyword status: The status of the enrollment account. :paramtype status: str :keyword start_date: The start date of the enrollment account. :paramtype start_date: ~datetime.datetime :keyword end_date: The end date of the enrollment account. :paramtype end_date: ~datetime.datetime :keyword department: Associated department. By default this is not populated, unless it's specified in $expand. :paramtype department: ~azure.mgmt.billing.models.Department """ super().__init__(**kwargs) self.account_name = account_name self.cost_center = cost_center self.account_owner = account_owner self.account_owner_email = account_owner_email self.status = status self.start_date = start_date self.end_date = end_date self.department = department class EnrollmentAccountContext(_serialization.Model): """The enrollment account context. :ivar cost_center: The cost center associated with the enrollment account. :vartype cost_center: str :ivar start_date: The start date of the enrollment account. :vartype start_date: ~datetime.datetime :ivar end_date: The end date of the enrollment account. :vartype end_date: ~datetime.datetime :ivar enrollment_account_name: The ID of the enrollment account. :vartype enrollment_account_name: str """ _attribute_map = { "cost_center": {"key": "costCenter", "type": "str"}, "start_date": {"key": "startDate", "type": "iso-8601"}, "end_date": {"key": "endDate", "type": "iso-8601"}, "enrollment_account_name": {"key": "enrollmentAccountName", "type": "str"}, } def __init__( self, *, cost_center: Optional[str] = None, start_date: Optional[datetime.datetime] = None, end_date: Optional[datetime.datetime] = None, enrollment_account_name: Optional[str] = None, **kwargs ): """ :keyword cost_center: The cost center associated with the enrollment account. :paramtype cost_center: str :keyword start_date: The start date of the enrollment account. :paramtype start_date: ~datetime.datetime :keyword end_date: The end date of the enrollment account. :paramtype end_date: ~datetime.datetime :keyword enrollment_account_name: The ID of the enrollment account. :paramtype enrollment_account_name: str """ super().__init__(**kwargs) self.cost_center = cost_center self.start_date = start_date self.end_date = end_date self.enrollment_account_name = enrollment_account_name class EnrollmentAccountListResult(_serialization.Model): """Result of listing enrollment accounts. Variables are only populated by the server, and will be ignored when sending a request. :ivar value: The list of enrollment accounts. :vartype value: list[~azure.mgmt.billing.models.EnrollmentAccountSummary] :ivar next_link: The link (url) to the next page of results. :vartype next_link: str """ _validation = { "value": {"readonly": True}, "next_link": {"readonly": True}, } _attribute_map = { "value": {"key": "value", "type": "[EnrollmentAccountSummary]"}, "next_link": {"key": "nextLink", "type": "str"}, } def __init__(self, **kwargs): """ """ super().__init__(**kwargs) self.value = None self.next_link = None class EnrollmentAccountSummary(Resource): """An enrollment account resource. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: Resource Id. :vartype id: str :ivar name: Resource name. :vartype name: str :ivar type: Resource type. :vartype type: str :ivar principal_name: The account owner's principal name. :vartype principal_name: str """ _validation = { "id": {"readonly": True}, "name": {"readonly": True}, "type": {"readonly": True}, "principal_name": {"readonly": True}, } _attribute_map = { "id": {"key": "id", "type": "str"}, "name": {"key": "name", "type": "str"}, "type": {"key": "type", "type": "str"}, "principal_name": {"key": "properties.principalName", "type": "str"}, } def __init__(self, **kwargs): """ """ super().__init__(**kwargs) self.principal_name = None class EnrollmentPolicies(_serialization.Model): """The policies for Enterprise Agreement enrollments. Variables are only populated by the server, and will be ignored when sending a request. :ivar account_owner_view_charges: The policy that controls whether Account Owners can view charges. :vartype account_owner_view_charges: bool :ivar department_admin_view_charges: The policy that controls whether Department Administrators can view charges. :vartype department_admin_view_charges: bool :ivar marketplace_enabled: The policy that controls whether Azure marketplace purchases are allowed in the enrollment. :vartype marketplace_enabled: bool :ivar reserved_instances_enabled: The policy that controls whether Azure reservation purchases are allowed in the enrollment. :vartype reserved_instances_enabled: bool """ _validation = { "account_owner_view_charges": {"readonly": True}, "department_admin_view_charges": {"readonly": True}, "marketplace_enabled": {"readonly": True}, "reserved_instances_enabled": {"readonly": True}, } _attribute_map = { "account_owner_view_charges": {"key": "accountOwnerViewCharges", "type": "bool"}, "department_admin_view_charges": {"key": "departmentAdminViewCharges", "type": "bool"}, "marketplace_enabled": {"key": "marketplaceEnabled", "type": "bool"}, "reserved_instances_enabled": {"key": "reservedInstancesEnabled", "type": "bool"}, } def __init__(self, **kwargs): """ """ super().__init__(**kwargs) self.account_owner_view_charges = None self.department_admin_view_charges = None self.marketplace_enabled = None self.reserved_instances_enabled = None class ErrorDetails(_serialization.Model): """The details of the error. Variables are only populated by the server, and will be ignored when sending a request. :ivar code: Error code. :vartype code: str :ivar message: Error message indicating why the operation failed. :vartype message: str :ivar target: The target of the particular error. :vartype target: str :ivar details: The sub details of the error. :vartype details: list[~azure.mgmt.billing.models.ErrorSubDetailsItem] """ _validation = { "code": {"readonly": True}, "message": {"readonly": True}, "target": {"readonly": True}, "details": {"readonly": True}, } _attribute_map = { "code": {"key": "code", "type": "str"}, "message": {"key": "message", "type": "str"}, "target": {"key": "target", "type": "str"}, "details": {"key": "details", "type": "[ErrorSubDetailsItem]"}, } def __init__(self, **kwargs): """ """ super().__init__(**kwargs) self.code = None self.message = None self.target = None self.details = None class ErrorResponse(_serialization.Model): """Error response indicates that the service is not able to process the incoming request. The reason is provided in the error message. :ivar error: The details of the error. :vartype error: ~azure.mgmt.billing.models.ErrorDetails """ _attribute_map = { "error": {"key": "error", "type": "ErrorDetails"}, } def __init__(self, *, error: Optional["_models.ErrorDetails"] = None, **kwargs): """ :keyword error: The details of the error. :paramtype error: ~azure.mgmt.billing.models.ErrorDetails """ super().__init__(**kwargs) self.error = error class ErrorSubDetailsItem(_serialization.Model): """ErrorSubDetailsItem. Variables are only populated by the server, and will be ignored when sending a request. :ivar code: Error code. :vartype code: str :ivar message: Error message indicating why the operation failed. :vartype message: str :ivar target: The target of the particular error. :vartype target: str """ _validation = { "code": {"readonly": True}, "message": {"readonly": True}, "target": {"readonly": True}, } _attribute_map = { "code": {"key": "code", "type": "str"}, "message": {"key": "message", "type": "str"}, "target": {"key": "target", "type": "str"}, } def __init__(self, **kwargs): """ """ super().__init__(**kwargs) self.code = None self.message = None self.target = None class IndirectRelationshipInfo(_serialization.Model): """The billing profile details of the partner of the customer for an indirect motion. :ivar billing_account_name: The billing account name of the partner or the customer for an indirect motion. :vartype billing_account_name: str :ivar billing_profile_name: The billing profile name of the partner or the customer for an indirect motion. :vartype billing_profile_name: str :ivar display_name: The display name of the partner or customer for an indirect motion. :vartype display_name: str """ _attribute_map = { "billing_account_name": {"key": "billingAccountName", "type": "str"}, "billing_profile_name": {"key": "billingProfileName", "type": "str"}, "display_name": {"key": "displayName", "type": "str"}, } def __init__( self, *, billing_account_name: Optional[str] = None, billing_profile_name: Optional[str] = None, display_name: Optional[str] = None, **kwargs ): """ :keyword billing_account_name: The billing account name of the partner or the customer for an indirect motion. :paramtype billing_account_name: str :keyword billing_profile_name: The billing profile name of the partner or the customer for an indirect motion. :paramtype billing_profile_name: str :keyword display_name: The display name of the partner or customer for an indirect motion. :paramtype display_name: str """ super().__init__(**kwargs) self.billing_account_name = billing_account_name self.billing_profile_name = billing_profile_name self.display_name = display_name class Instruction(Resource): """An instruction. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: Resource Id. :vartype id: str :ivar name: Resource name. :vartype name: str :ivar type: Resource type. :vartype type: str :ivar amount: The amount budgeted for this billing instruction. :vartype amount: float :ivar start_date: The date this billing instruction goes into effect. :vartype start_date: ~datetime.datetime :ivar end_date: The date this billing instruction is no longer in effect. :vartype end_date: ~datetime.datetime :ivar creation_date: The date this billing instruction was created. :vartype creation_date: ~datetime.datetime """ _validation = { "id": {"readonly": True}, "name": {"readonly": True}, "type": {"readonly": True}, } _attribute_map = { "id": {"key": "id", "type": "str"}, "name": {"key": "name", "type": "str"}, "type": {"key": "type", "type": "str"}, "amount": {"key": "properties.amount", "type": "float"}, "start_date": {"key": "properties.startDate", "type": "iso-8601"}, "end_date": {"key": "properties.endDate", "type": "iso-8601"}, "creation_date": {"key": "properties.creationDate", "type": "iso-8601"}, } def __init__( self, *, amount: Optional[float] = None, start_date: Optional[datetime.datetime] = None, end_date: Optional[datetime.datetime] = None, creation_date: Optional[datetime.datetime] = None, **kwargs ): """ :keyword amount: The amount budgeted for this billing instruction. :paramtype amount: float :keyword start_date: The date this billing instruction goes into effect. :paramtype start_date: ~datetime.datetime :keyword end_date: The date this billing instruction is no longer in effect. :paramtype end_date: ~datetime.datetime :keyword creation_date: The date this billing instruction was created. :paramtype creation_date: ~datetime.datetime """ super().__init__(**kwargs) self.amount = amount self.start_date = start_date self.end_date = end_date self.creation_date = creation_date class InstructionListResult(_serialization.Model): """The list of billing instructions used during invoice generation. Variables are only populated by the server, and will be ignored when sending a request. :ivar value: The list of billing instructions used during invoice generation. :vartype value: list[~azure.mgmt.billing.models.Instruction] :ivar next_link: The link (url) to the next page of results. :vartype next_link: str """ _validation = { "value": {"readonly": True}, "next_link": {"readonly": True}, } _attribute_map = { "value": {"key": "value", "type": "[Instruction]"}, "next_link": {"key": "nextLink", "type": "str"}, } def __init__(self, **kwargs): """ """ super().__init__(**kwargs) self.value = None self.next_link = None class Invoice(Resource): # pylint: disable=too-many-instance-attributes """An invoice. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: Resource Id. :vartype id: str :ivar name: Resource name. :vartype name: str :ivar type: Resource type. :vartype type: str :ivar due_date: The due date for the invoice. :vartype due_date: ~datetime.datetime :ivar invoice_date: The date when the invoice was generated. :vartype invoice_date: ~datetime.datetime :ivar status: The current status of the invoice. Known values are: "Due", "OverDue", "Paid", and "Void". :vartype status: str or ~azure.mgmt.billing.models.InvoiceStatus :ivar amount_due: The amount due as of now. :vartype amount_due: ~azure.mgmt.billing.models.Amount :ivar azure_prepayment_applied: The amount of Azure prepayment applied to the charges. This field is applicable to billing accounts with agreement type Microsoft Customer Agreement. :vartype azure_prepayment_applied: ~azure.mgmt.billing.models.Amount :ivar billed_amount: The total charges for the invoice billing period. :vartype billed_amount: ~azure.mgmt.billing.models.Amount :ivar credit_amount: The total refund for returns and cancellations during the invoice billing period. This field is applicable to billing accounts with agreement type Microsoft Customer Agreement. :vartype credit_amount: ~azure.mgmt.billing.models.Amount :ivar free_azure_credit_applied: The amount of free Azure credits applied to the charges. This field is applicable to billing accounts with agreement type Microsoft Customer Agreement. :vartype free_azure_credit_applied: ~azure.mgmt.billing.models.Amount :ivar sub_total: The pre-tax amount due. This field is applicable to billing accounts with agreement type Microsoft Customer Agreement. :vartype sub_total: ~azure.mgmt.billing.models.Amount :ivar tax_amount: The amount of tax charged for the billing period. This field is applicable to billing accounts with agreement type Microsoft Customer Agreement. :vartype tax_amount: ~azure.mgmt.billing.models.Amount :ivar total_amount: The amount due when the invoice was generated. This field is applicable to billing accounts with agreement type Microsoft Customer Agreement. :vartype total_amount: ~azure.mgmt.billing.models.Amount :ivar invoice_period_start_date: The start date of the billing period for which the invoice is generated. :vartype invoice_period_start_date: ~datetime.datetime :ivar invoice_period_end_date: The end date of the billing period for which the invoice is generated. :vartype invoice_period_end_date: ~datetime.datetime :ivar invoice_type: Invoice type. Known values are: "AzureService", "AzureMarketplace", and "AzureSupport". :vartype invoice_type: str or ~azure.mgmt.billing.models.InvoiceType :ivar is_monthly_invoice: Specifies if the invoice is generated as part of monthly invoicing cycle or not. This field is applicable to billing accounts with agreement type Microsoft Customer Agreement. :vartype is_monthly_invoice: bool :ivar billing_profile_id: The ID of the billing profile for which the invoice is generated. :vartype billing_profile_id: str :ivar billing_profile_display_name: The name of the billing profile for which the invoice is generated. :vartype billing_profile_display_name: str :ivar purchase_order_number: An optional purchase order number for the invoice. :vartype purchase_order_number: str :ivar documents: List of documents available to download such as invoice and tax receipt. :vartype documents: list[~azure.mgmt.billing.models.Document] :ivar payments: List of payments. :vartype payments: list[~azure.mgmt.billing.models.PaymentProperties] :ivar rebill_details: Rebill details for an invoice. :vartype rebill_details: dict[str, ~azure.mgmt.billing.models.RebillDetails] :ivar document_type: The type of the document. Known values are: "Invoice" and "CreditNote". :vartype document_type: str or ~azure.mgmt.billing.models.InvoiceDocumentType :ivar billed_document_id: The Id of the active invoice which is originally billed after this invoice was voided. This field is applicable to the void invoices only. :vartype billed_document_id: str :ivar credit_for_document_id: The Id of the invoice which got voided and this credit note was issued as a result. This field is applicable to the credit notes only. :vartype credit_for_document_id: str :ivar subscription_id: The ID of the subscription for which the invoice is generated. :vartype subscription_id: str """ _validation = { "id": {"readonly": True}, "name": {"readonly": True}, "type": {"readonly": True}, "due_date": {"readonly": True}, "invoice_date": {"readonly": True}, "status": {"readonly": True}, "amount_due": {"readonly": True}, "azure_prepayment_applied": {"readonly": True}, "billed_amount": {"readonly": True}, "credit_amount": {"readonly": True}, "free_azure_credit_applied": {"readonly": True}, "sub_total": {"readonly": True}, "tax_amount": {"readonly": True}, "total_amount": {"readonly": True}, "invoice_period_start_date": {"readonly": True}, "invoice_period_end_date": {"readonly": True}, "invoice_type": {"readonly": True}, "is_monthly_invoice": {"readonly": True}, "billing_profile_id": {"readonly": True}, "billing_profile_display_name": {"readonly": True}, "purchase_order_number": {"readonly": True}, "documents": {"readonly": True}, "payments": {"readonly": True}, "rebill_details": {"readonly": True}, "document_type": {"readonly": True}, "billed_document_id": {"readonly": True}, "credit_for_document_id": {"readonly": True}, "subscription_id": {"readonly": True}, } _attribute_map = { "id": {"key": "id", "type": "str"}, "name": {"key": "name", "type": "str"}, "type": {"key": "type", "type": "str"}, "due_date": {"key": "properties.dueDate", "type": "iso-8601"}, "invoice_date": {"key": "properties.invoiceDate", "type": "iso-8601"}, "status": {"key": "properties.status", "type": "str"}, "amount_due": {"key": "properties.amountDue", "type": "Amount"}, "azure_prepayment_applied": {"key": "properties.azurePrepaymentApplied", "type": "Amount"}, "billed_amount": {"key": "properties.billedAmount", "type": "Amount"}, "credit_amount": {"key": "properties.creditAmount", "type": "Amount"}, "free_azure_credit_applied": {"key": "properties.freeAzureCreditApplied", "type": "Amount"}, "sub_total": {"key": "properties.subTotal", "type": "Amount"}, "tax_amount": {"key": "properties.taxAmount", "type": "Amount"}, "total_amount": {"key": "properties.totalAmount", "type": "Amount"}, "invoice_period_start_date": {"key": "properties.invoicePeriodStartDate", "type": "iso-8601"}, "invoice_period_end_date": {"key": "properties.invoicePeriodEndDate", "type": "iso-8601"}, "invoice_type": {"key": "properties.invoiceType", "type": "str"}, "is_monthly_invoice": {"key": "properties.isMonthlyInvoice", "type": "bool"}, "billing_profile_id": {"key": "properties.billingProfileId", "type": "str"}, "billing_profile_display_name": {"key": "properties.billingProfileDisplayName", "type": "str"}, "purchase_order_number": {"key": "properties.purchaseOrderNumber", "type": "str"}, "documents": {"key": "properties.documents", "type": "[Document]"}, "payments": {"key": "properties.payments", "type": "[PaymentProperties]"}, "rebill_details": {"key": "properties.rebillDetails", "type": "{RebillDetails}"}, "document_type": {"key": "properties.documentType", "type": "str"}, "billed_document_id": {"key": "properties.billedDocumentId", "type": "str"}, "credit_for_document_id": {"key": "properties.creditForDocumentId", "type": "str"}, "subscription_id": {"key": "properties.subscriptionId", "type": "str"}, } def __init__(self, **kwargs): # pylint: disable=too-many-locals """ """ super().__init__(**kwargs) self.due_date = None self.invoice_date = None self.status = None self.amount_due = None self.azure_prepayment_applied = None self.billed_amount = None self.credit_amount = None self.free_azure_credit_applied = None self.sub_total = None self.tax_amount = None self.total_amount = None self.invoice_period_start_date = None self.invoice_period_end_date = None self.invoice_type = None self.is_monthly_invoice = None self.billing_profile_id = None self.billing_profile_display_name = None self.purchase_order_number = None self.documents = None self.payments = None self.rebill_details = None self.document_type = None self.billed_document_id = None self.credit_for_document_id = None self.subscription_id = None class InvoiceListResult(_serialization.Model): """The list of invoices. Variables are only populated by the server, and will be ignored when sending a request. :ivar value: The list of invoices. :vartype value: list[~azure.mgmt.billing.models.Invoice] :ivar next_link: The link (url) to the next page of results. :vartype next_link: str :ivar total_count: Total number of records. :vartype total_count: int """ _validation = { "value": {"readonly": True}, "next_link": {"readonly": True}, "total_count": {"readonly": True}, } _attribute_map = { "value": {"key": "value", "type": "[Invoice]"}, "next_link": {"key": "nextLink", "type": "str"}, "total_count": {"key": "totalCount", "type": "int"}, } def __init__(self, **kwargs): """ """ super().__init__(**kwargs) self.value = None self.next_link = None self.total_count = None class InvoiceSection(Resource): """An invoice section. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: Resource Id. :vartype id: str :ivar name: Resource name. :vartype name: str :ivar type: Resource type. :vartype type: str :ivar display_name: The name of the invoice section. :vartype display_name: str :ivar labels: Dictionary of metadata associated with the invoice section. :vartype labels: dict[str, str] :ivar state: Identifies the state of an invoice section. Known values are: "Active" and "Restricted". :vartype state: str or ~azure.mgmt.billing.models.InvoiceSectionState :ivar system_id: The system generated unique identifier for an invoice section. :vartype system_id: str :ivar tags: Dictionary of metadata associated with the invoice section. Maximum key/value length supported of 256 characters. Keys/value should not empty value nor null. Keys can not contain < > % & ? /. :vartype tags: dict[str, str] :ivar target_cloud: Identifies the cloud environments that are associated with an invoice section. This is a system managed optional field and gets updated as the invoice section gets associated with accounts in various clouds. Known values are: "USGov", "USNat", and "USSec". :vartype target_cloud: str or ~azure.mgmt.billing.models.TargetCloud """ _validation = { "id": {"readonly": True}, "name": {"readonly": True}, "type": {"readonly": True}, "state": {"readonly": True}, "system_id": {"readonly": True}, "target_cloud": {"readonly": True}, } _attribute_map = { "id": {"key": "id", "type": "str"}, "name": {"key": "name", "type": "str"}, "type": {"key": "type", "type": "str"}, "display_name": {"key": "properties.displayName", "type": "str"}, "labels": {"key": "properties.labels", "type": "{str}"}, "state": {"key": "properties.state", "type": "str"}, "system_id": {"key": "properties.systemId", "type": "str"}, "tags": {"key": "properties.tags", "type": "{str}"}, "target_cloud": {"key": "properties.targetCloud", "type": "str"}, } def __init__( self, *, display_name: Optional[str] = None, labels: Optional[Dict[str, str]] = None, tags: Optional[Dict[str, str]] = None, **kwargs ): """ :keyword display_name: The name of the invoice section. :paramtype display_name: str :keyword labels: Dictionary of metadata associated with the invoice section. :paramtype labels: dict[str, str] :keyword tags: Dictionary of metadata associated with the invoice section. Maximum key/value length supported of 256 characters. Keys/value should not empty value nor null. Keys can not contain < > % & ? /. :paramtype tags: dict[str, str] """ super().__init__(**kwargs) self.display_name = display_name self.labels = labels self.state = None self.system_id = None self.tags = tags self.target_cloud = None class InvoiceSectionCreationRequest(_serialization.Model): """The properties of the invoice section. :ivar display_name: The name of the invoice section. :vartype display_name: str """ _attribute_map = { "display_name": {"key": "displayName", "type": "str"}, } def __init__(self, *, display_name: Optional[str] = None, **kwargs): """ :keyword display_name: The name of the invoice section. :paramtype display_name: str """ super().__init__(**kwargs) self.display_name = display_name class InvoiceSectionListResult(_serialization.Model): """The list of invoice sections. Variables are only populated by the server, and will be ignored when sending a request. :ivar value: The list of invoice sections. :vartype value: list[~azure.mgmt.billing.models.InvoiceSection] :ivar total_count: Total number of records. :vartype total_count: int :ivar next_link: The link (url) to the next page of results. :vartype next_link: str """ _validation = { "value": {"readonly": True}, "total_count": {"readonly": True}, "next_link": {"readonly": True}, } _attribute_map = { "value": {"key": "value", "type": "[InvoiceSection]"}, "total_count": {"key": "totalCount", "type": "int"}, "next_link": {"key": "nextLink", "type": "str"}, } def __init__(self, **kwargs): """ """ super().__init__(**kwargs) self.value = None self.total_count = None self.next_link = None class InvoiceSectionListWithCreateSubPermissionResult(_serialization.Model): """The list of invoice section properties with create subscription permission. Variables are only populated by the server, and will be ignored when sending a request. :ivar value: The list of invoice section properties with create subscription permission. :vartype value: list[~azure.mgmt.billing.models.InvoiceSectionWithCreateSubPermission] :ivar next_link: The link (url) to the next page of results. :vartype next_link: str """ _validation = { "next_link": {"readonly": True}, } _attribute_map = { "value": {"key": "value", "type": "[InvoiceSectionWithCreateSubPermission]"}, "next_link": {"key": "nextLink", "type": "str"}, } def __init__(self, *, value: Optional[List["_models.InvoiceSectionWithCreateSubPermission"]] = None, **kwargs): """ :keyword value: The list of invoice section properties with create subscription permission. :paramtype value: list[~azure.mgmt.billing.models.InvoiceSectionWithCreateSubPermission] """ super().__init__(**kwargs) self.value = value self.next_link = None class InvoiceSectionsOnExpand(_serialization.Model): """The invoice sections associated to the billing profile. By default this is not populated, unless it's specified in $expand. Variables are only populated by the server, and will be ignored when sending a request. :ivar has_more_results: Indicates whether there are more invoice sections than the ones listed in this collection. The collection lists a maximum of 50 invoice sections. To get all invoice sections, use the list invoice sections API. :vartype has_more_results: bool :ivar value: The invoice sections associated to the billing profile. :vartype value: list[~azure.mgmt.billing.models.InvoiceSection] """ _validation = { "has_more_results": {"readonly": True}, } _attribute_map = { "has_more_results": {"key": "hasMoreResults", "type": "bool"}, "value": {"key": "value", "type": "[InvoiceSection]"}, } def __init__(self, *, value: Optional[List["_models.InvoiceSection"]] = None, **kwargs): """ :keyword value: The invoice sections associated to the billing profile. :paramtype value: list[~azure.mgmt.billing.models.InvoiceSection] """ super().__init__(**kwargs) self.has_more_results = None self.value = value class InvoiceSectionWithCreateSubPermission(_serialization.Model): """Invoice section properties with create subscription permission. Variables are only populated by the server, and will be ignored when sending a request. :ivar invoice_section_id: The ID of the invoice section. :vartype invoice_section_id: str :ivar invoice_section_display_name: The name of the invoice section. :vartype invoice_section_display_name: str :ivar invoice_section_system_id: The system generated unique identifier for an invoice section. :vartype invoice_section_system_id: str :ivar billing_profile_id: The ID of the billing profile for the invoice section. :vartype billing_profile_id: str :ivar billing_profile_display_name: The name of the billing profile for the invoice section. :vartype billing_profile_display_name: str :ivar billing_profile_status: The status of the billing profile. Known values are: "Active", "Disabled", and "Warned". :vartype billing_profile_status: str or ~azure.mgmt.billing.models.BillingProfileStatus :ivar billing_profile_status_reason_code: Reason for the specified billing profile status. Known values are: "PastDue", "SpendingLimitReached", and "SpendingLimitExpired". :vartype billing_profile_status_reason_code: str or ~azure.mgmt.billing.models.StatusReasonCodeForBillingProfile :ivar billing_profile_spending_limit: The billing profile spending limit. Known values are: "Off" and "On". :vartype billing_profile_spending_limit: str or ~azure.mgmt.billing.models.SpendingLimitForBillingProfile :ivar billing_profile_system_id: The system generated unique identifier for a billing profile. :vartype billing_profile_system_id: str :ivar enabled_azure_plans: Enabled azure plans for the associated billing profile. :vartype enabled_azure_plans: list[~azure.mgmt.billing.models.AzurePlan] """ _validation = { "invoice_section_id": {"readonly": True}, "invoice_section_display_name": {"readonly": True}, "invoice_section_system_id": {"readonly": True}, "billing_profile_id": {"readonly": True}, "billing_profile_display_name": {"readonly": True}, "billing_profile_status": {"readonly": True}, "billing_profile_status_reason_code": {"readonly": True}, "billing_profile_spending_limit": {"readonly": True}, "billing_profile_system_id": {"readonly": True}, } _attribute_map = { "invoice_section_id": {"key": "invoiceSectionId", "type": "str"}, "invoice_section_display_name": {"key": "invoiceSectionDisplayName", "type": "str"}, "invoice_section_system_id": {"key": "invoiceSectionSystemId", "type": "str"}, "billing_profile_id": {"key": "billingProfileId", "type": "str"}, "billing_profile_display_name": {"key": "billingProfileDisplayName", "type": "str"}, "billing_profile_status": {"key": "billingProfileStatus", "type": "str"}, "billing_profile_status_reason_code": {"key": "billingProfileStatusReasonCode", "type": "str"}, "billing_profile_spending_limit": {"key": "billingProfileSpendingLimit", "type": "str"}, "billing_profile_system_id": {"key": "billingProfileSystemId", "type": "str"}, "enabled_azure_plans": {"key": "enabledAzurePlans", "type": "[AzurePlan]"}, } def __init__(self, *, enabled_azure_plans: Optional[List["_models.AzurePlan"]] = None, **kwargs): """ :keyword enabled_azure_plans: Enabled azure plans for the associated billing profile. :paramtype enabled_azure_plans: list[~azure.mgmt.billing.models.AzurePlan] """ super().__init__(**kwargs) self.invoice_section_id = None self.invoice_section_display_name = None self.invoice_section_system_id = None self.billing_profile_id = None self.billing_profile_display_name = None self.billing_profile_status = None self.billing_profile_status_reason_code = None self.billing_profile_spending_limit = None self.billing_profile_system_id = None self.enabled_azure_plans = enabled_azure_plans class Operation(_serialization.Model): """A Billing REST API operation. Variables are only populated by the server, and will be ignored when sending a request. :ivar name: Operation name: {provider}/{resource}/{operation}. :vartype name: str :ivar is_data_action: Identifies if the operation is a data operation. :vartype is_data_action: bool :ivar display: The object that represents the operation. :vartype display: ~azure.mgmt.billing.models.OperationDisplay """ _validation = { "name": {"readonly": True}, "is_data_action": {"readonly": True}, } _attribute_map = { "name": {"key": "name", "type": "str"}, "is_data_action": {"key": "isDataAction", "type": "bool"}, "display": {"key": "display", "type": "OperationDisplay"}, } def __init__(self, *, display: Optional["_models.OperationDisplay"] = None, **kwargs): """ :keyword display: The object that represents the operation. :paramtype display: ~azure.mgmt.billing.models.OperationDisplay """ super().__init__(**kwargs) self.name = None self.is_data_action = None self.display = display class OperationDisplay(_serialization.Model): """The object that represents the operation. Variables are only populated by the server, and will be ignored when sending a request. :ivar provider: Service provider: Microsoft.Billing. :vartype provider: str :ivar resource: Resource on which the operation is performed such as invoice and billing subscription. :vartype resource: str :ivar operation: Operation type such as read, write and delete. :vartype operation: str :ivar description: Description of operation. :vartype description: str """ _validation = { "provider": {"readonly": True}, "resource": {"readonly": True}, "operation": {"readonly": True}, "description": {"readonly": True}, } _attribute_map = { "provider": {"key": "provider", "type": "str"}, "resource": {"key": "resource", "type": "str"}, "operation": {"key": "operation", "type": "str"}, "description": {"key": "description", "type": "str"}, } def __init__(self, **kwargs): """ """ super().__init__(**kwargs) self.provider = None self.resource = None self.operation = None self.description = None class OperationListResult(_serialization.Model): """The list of billing operations and a URL link to get the next set of results. Variables are only populated by the server, and will be ignored when sending a request. :ivar value: The list of billing operations supported by the Microsoft.Billing resource provider. :vartype value: list[~azure.mgmt.billing.models.Operation] :ivar next_link: URL to get the next set of operation list results if there are any. :vartype next_link: str """ _validation = { "value": {"readonly": True}, "next_link": {"readonly": True}, } _attribute_map = { "value": {"key": "value", "type": "[Operation]"}, "next_link": {"key": "nextLink", "type": "str"}, } def __init__(self, **kwargs): """ """ super().__init__(**kwargs) self.value = None self.next_link = None class OperationsErrorDetails(_serialization.Model): """The details of the error. Variables are only populated by the server, and will be ignored when sending a request. :ivar code: Error code. :vartype code: str :ivar message: Error message indicating why the operation failed. :vartype message: str :ivar target: The target of the particular error. :vartype target: str """ _validation = { "code": {"readonly": True}, "message": {"readonly": True}, "target": {"readonly": True}, } _attribute_map = { "code": {"key": "code", "type": "str"}, "message": {"key": "message", "type": "str"}, "target": {"key": "target", "type": "str"}, } def __init__(self, **kwargs): """ """ super().__init__(**kwargs) self.code = None self.message = None self.target = None class OperationsErrorResponse(_serialization.Model): """Error response indicates that the service is not able to process the incoming request. The reason is provided in the error message. :ivar error: The details of the error. :vartype error: ~azure.mgmt.billing.models.OperationsErrorDetails """ _attribute_map = { "error": {"key": "error", "type": "OperationsErrorDetails"}, } def __init__(self, *, error: Optional["_models.OperationsErrorDetails"] = None, **kwargs): """ :keyword error: The details of the error. :paramtype error: ~azure.mgmt.billing.models.OperationsErrorDetails """ super().__init__(**kwargs) self.error = error class Participants(_serialization.Model): """The details about a participant. Variables are only populated by the server, and will be ignored when sending a request. :ivar status: The acceptance status of the participant. :vartype status: str :ivar status_date: The date when the status got changed. :vartype status_date: ~datetime.datetime :ivar email: The email address of the participant. :vartype email: str """ _validation = { "status": {"readonly": True}, "status_date": {"readonly": True}, "email": {"readonly": True}, } _attribute_map = { "status": {"key": "status", "type": "str"}, "status_date": {"key": "statusDate", "type": "iso-8601"}, "email": {"key": "email", "type": "str"}, } def __init__(self, **kwargs): """ """ super().__init__(**kwargs) self.status = None self.status_date = None self.email = None class PaymentProperties(_serialization.Model): """The properties of a payment. Variables are only populated by the server, and will be ignored when sending a request. :ivar payment_type: The type of payment. :vartype payment_type: str :ivar amount: The paid amount. :vartype amount: ~azure.mgmt.billing.models.Amount :ivar date: The date when the payment was made. :vartype date: ~datetime.datetime :ivar payment_method_family: The family of payment method. Known values are: "Credits", "CheckWire", "CreditCard", and "None". :vartype payment_method_family: str or ~azure.mgmt.billing.models.PaymentMethodFamily :ivar payment_method_type: The type of payment method. :vartype payment_method_type: str """ _validation = { "payment_type": {"readonly": True}, "amount": {"readonly": True}, "date": {"readonly": True}, "payment_method_type": {"readonly": True}, } _attribute_map = { "payment_type": {"key": "paymentType", "type": "str"}, "amount": {"key": "amount", "type": "Amount"}, "date": {"key": "date", "type": "iso-8601"}, "payment_method_family": {"key": "paymentMethodFamily", "type": "str"}, "payment_method_type": {"key": "paymentMethodType", "type": "str"}, } def __init__(self, *, payment_method_family: Optional[Union[str, "_models.PaymentMethodFamily"]] = None, **kwargs): """ :keyword payment_method_family: The family of payment method. Known values are: "Credits", "CheckWire", "CreditCard", and "None". :paramtype payment_method_family: str or ~azure.mgmt.billing.models.PaymentMethodFamily """ super().__init__(**kwargs) self.payment_type = None self.amount = None self.date = None self.payment_method_family = payment_method_family self.payment_method_type = None class Policy(Resource): """A policy. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: Resource Id. :vartype id: str :ivar name: Resource name. :vartype name: str :ivar type: Resource type. :vartype type: str :ivar marketplace_purchases: The policy that controls whether Azure marketplace purchases are allowed for a billing profile. Known values are: "AllAllowed", "OnlyFreeAllowed", and "NotAllowed". :vartype marketplace_purchases: str or ~azure.mgmt.billing.models.MarketplacePurchasesPolicy :ivar reservation_purchases: The policy that controls whether Azure reservation purchases are allowed for a billing profile. Known values are: "Allowed" and "NotAllowed". :vartype reservation_purchases: str or ~azure.mgmt.billing.models.ReservationPurchasesPolicy :ivar view_charges: The policy that controls whether users with Azure RBAC access to a subscription can view its charges. Known values are: "Allowed" and "NotAllowed". :vartype view_charges: str or ~azure.mgmt.billing.models.ViewChargesPolicy """ _validation = { "id": {"readonly": True}, "name": {"readonly": True}, "type": {"readonly": True}, } _attribute_map = { "id": {"key": "id", "type": "str"}, "name": {"key": "name", "type": "str"}, "type": {"key": "type", "type": "str"}, "marketplace_purchases": {"key": "properties.marketplacePurchases", "type": "str"}, "reservation_purchases": {"key": "properties.reservationPurchases", "type": "str"}, "view_charges": {"key": "properties.viewCharges", "type": "str"}, } def __init__( self, *, marketplace_purchases: Optional[Union[str, "_models.MarketplacePurchasesPolicy"]] = None, reservation_purchases: Optional[Union[str, "_models.ReservationPurchasesPolicy"]] = None, view_charges: Optional[Union[str, "_models.ViewChargesPolicy"]] = None, **kwargs ): """ :keyword marketplace_purchases: The policy that controls whether Azure marketplace purchases are allowed for a billing profile. Known values are: "AllAllowed", "OnlyFreeAllowed", and "NotAllowed". :paramtype marketplace_purchases: str or ~azure.mgmt.billing.models.MarketplacePurchasesPolicy :keyword reservation_purchases: The policy that controls whether Azure reservation purchases are allowed for a billing profile. Known values are: "Allowed" and "NotAllowed". :paramtype reservation_purchases: str or ~azure.mgmt.billing.models.ReservationPurchasesPolicy :keyword view_charges: The policy that controls whether users with Azure RBAC access to a subscription can view its charges. Known values are: "Allowed" and "NotAllowed". :paramtype view_charges: str or ~azure.mgmt.billing.models.ViewChargesPolicy """ super().__init__(**kwargs) self.marketplace_purchases = marketplace_purchases self.reservation_purchases = reservation_purchases self.view_charges = view_charges class Product(Resource): # pylint: disable=too-many-instance-attributes """A product. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: Resource Id. :vartype id: str :ivar name: Resource name. :vartype name: str :ivar type: Resource type. :vartype type: str :ivar auto_renew: Indicates whether auto renewal is turned on or off for a product. Known values are: "Off" and "On". :vartype auto_renew: str or ~azure.mgmt.billing.models.AutoRenew :ivar display_name: The display name of the product. :vartype display_name: str :ivar purchase_date: The date when the product was purchased. :vartype purchase_date: ~datetime.datetime :ivar product_type_id: The ID of the type of product. :vartype product_type_id: str :ivar product_type: The description of the type of product. :vartype product_type: str :ivar status: The current status of the product. Known values are: "Active", "Inactive", "PastDue", "Expiring", "Expired", "Disabled", "Cancelled", and "AutoRenew". :vartype status: str or ~azure.mgmt.billing.models.ProductStatusType :ivar end_date: The date when the product will be renewed or canceled. :vartype end_date: ~datetime.datetime :ivar billing_frequency: The frequency at which the product will be billed. Known values are: "OneTime", "Monthly", and "UsageBased". :vartype billing_frequency: str or ~azure.mgmt.billing.models.BillingFrequency :ivar last_charge: The last month charges. :vartype last_charge: ~azure.mgmt.billing.models.Amount :ivar last_charge_date: The date of the last charge. :vartype last_charge_date: ~datetime.datetime :ivar quantity: The quantity purchased for the product. :vartype quantity: float :ivar sku_id: The sku ID of the product. :vartype sku_id: str :ivar sku_description: The sku description of the product. :vartype sku_description: str :ivar tenant_id: The id of the tenant in which the product is used. :vartype tenant_id: str :ivar availability_id: The availability of the product. :vartype availability_id: str :ivar invoice_section_id: The ID of the invoice section to which the product is billed. :vartype invoice_section_id: str :ivar invoice_section_display_name: The name of the invoice section to which the product is billed. :vartype invoice_section_display_name: str :ivar billing_profile_id: The ID of the billing profile to which the product is billed. :vartype billing_profile_id: str :ivar billing_profile_display_name: The name of the billing profile to which the product is billed. :vartype billing_profile_display_name: str :ivar customer_id: The ID of the customer for whom the product was purchased. The field is applicable only for Microsoft Partner Agreement billing account. :vartype customer_id: str :ivar customer_display_name: The name of the customer for whom the product was purchased. The field is applicable only for Microsoft Partner Agreement billing account. :vartype customer_display_name: str :ivar reseller: Reseller for this product. :vartype reseller: ~azure.mgmt.billing.models.Reseller """ _validation = { "id": {"readonly": True}, "name": {"readonly": True}, "type": {"readonly": True}, "display_name": {"readonly": True}, "purchase_date": {"readonly": True}, "product_type_id": {"readonly": True}, "product_type": {"readonly": True}, "end_date": {"readonly": True}, "last_charge": {"readonly": True}, "last_charge_date": {"readonly": True}, "quantity": {"readonly": True}, "sku_id": {"readonly": True}, "sku_description": {"readonly": True}, "tenant_id": {"readonly": True}, "availability_id": {"readonly": True}, "invoice_section_id": {"readonly": True}, "invoice_section_display_name": {"readonly": True}, "billing_profile_id": {"readonly": True}, "billing_profile_display_name": {"readonly": True}, "customer_id": {"readonly": True}, "customer_display_name": {"readonly": True}, "reseller": {"readonly": True}, } _attribute_map = { "id": {"key": "id", "type": "str"}, "name": {"key": "name", "type": "str"}, "type": {"key": "type", "type": "str"}, "auto_renew": {"key": "properties.autoRenew", "type": "str"}, "display_name": {"key": "properties.displayName", "type": "str"}, "purchase_date": {"key": "properties.purchaseDate", "type": "iso-8601"}, "product_type_id": {"key": "properties.productTypeId", "type": "str"}, "product_type": {"key": "properties.productType", "type": "str"}, "status": {"key": "properties.status", "type": "str"}, "end_date": {"key": "properties.endDate", "type": "iso-8601"}, "billing_frequency": {"key": "properties.billingFrequency", "type": "str"}, "last_charge": {"key": "properties.lastCharge", "type": "Amount"}, "last_charge_date": {"key": "properties.lastChargeDate", "type": "iso-8601"}, "quantity": {"key": "properties.quantity", "type": "float"}, "sku_id": {"key": "properties.skuId", "type": "str"}, "sku_description": {"key": "properties.skuDescription", "type": "str"}, "tenant_id": {"key": "properties.tenantId", "type": "str"}, "availability_id": {"key": "properties.availabilityId", "type": "str"}, "invoice_section_id": {"key": "properties.invoiceSectionId", "type": "str"}, "invoice_section_display_name": {"key": "properties.invoiceSectionDisplayName", "type": "str"}, "billing_profile_id": {"key": "properties.billingProfileId", "type": "str"}, "billing_profile_display_name": {"key": "properties.billingProfileDisplayName", "type": "str"}, "customer_id": {"key": "properties.customerId", "type": "str"}, "customer_display_name": {"key": "properties.customerDisplayName", "type": "str"}, "reseller": {"key": "properties.reseller", "type": "Reseller"}, } def __init__( # pylint: disable=too-many-locals self, *, auto_renew: Optional[Union[str, "_models.AutoRenew"]] = None, status: Optional[Union[str, "_models.ProductStatusType"]] = None, billing_frequency: Optional[Union[str, "_models.BillingFrequency"]] = None, **kwargs ): """ :keyword auto_renew: Indicates whether auto renewal is turned on or off for a product. Known values are: "Off" and "On". :paramtype auto_renew: str or ~azure.mgmt.billing.models.AutoRenew :keyword status: The current status of the product. Known values are: "Active", "Inactive", "PastDue", "Expiring", "Expired", "Disabled", "Cancelled", and "AutoRenew". :paramtype status: str or ~azure.mgmt.billing.models.ProductStatusType :keyword billing_frequency: The frequency at which the product will be billed. Known values are: "OneTime", "Monthly", and "UsageBased". :paramtype billing_frequency: str or ~azure.mgmt.billing.models.BillingFrequency """ super().__init__(**kwargs) self.auto_renew = auto_renew self.display_name = None self.purchase_date = None self.product_type_id = None self.product_type = None self.status = status self.end_date = None self.billing_frequency = billing_frequency self.last_charge = None self.last_charge_date = None self.quantity = None self.sku_id = None self.sku_description = None self.tenant_id = None self.availability_id = None self.invoice_section_id = None self.invoice_section_display_name = None self.billing_profile_id = None self.billing_profile_display_name = None self.customer_id = None self.customer_display_name = None self.reseller = None class ProductsListResult(_serialization.Model): """The list of products. It contains a list of available product summaries in reverse chronological order by purchase date. Variables are only populated by the server, and will be ignored when sending a request. :ivar value: The list of products. :vartype value: list[~azure.mgmt.billing.models.Product] :ivar total_count: Total number of records. :vartype total_count: int :ivar next_link: The link (url) to the next page of results. :vartype next_link: str """ _validation = { "value": {"readonly": True}, "total_count": {"readonly": True}, "next_link": {"readonly": True}, } _attribute_map = { "value": {"key": "value", "type": "[Product]"}, "total_count": {"key": "totalCount", "type": "int"}, "next_link": {"key": "nextLink", "type": "str"}, } def __init__(self, **kwargs): """ """ super().__init__(**kwargs) self.value = None self.total_count = None self.next_link = None class RebillDetails(_serialization.Model): """The rebill details of an invoice. Variables are only populated by the server, and will be ignored when sending a request. :ivar credit_note_document_id: The ID of credit note. :vartype credit_note_document_id: str :ivar invoice_document_id: The ID of invoice. :vartype invoice_document_id: str :ivar rebill_details: Rebill details for an invoice. :vartype rebill_details: dict[str, ~azure.mgmt.billing.models.RebillDetails] """ _validation = { "credit_note_document_id": {"readonly": True}, "invoice_document_id": {"readonly": True}, "rebill_details": {"readonly": True}, } _attribute_map = { "credit_note_document_id": {"key": "creditNoteDocumentId", "type": "str"}, "invoice_document_id": {"key": "invoiceDocumentId", "type": "str"}, "rebill_details": {"key": "rebillDetails", "type": "{RebillDetails}"}, } def __init__(self, **kwargs): """ """ super().__init__(**kwargs) self.credit_note_document_id = None self.invoice_document_id = None self.rebill_details = None class Reseller(_serialization.Model): """Details of the reseller. Variables are only populated by the server, and will be ignored when sending a request. :ivar reseller_id: The MPN ID of the reseller. :vartype reseller_id: str :ivar description: The name of the reseller. :vartype description: str """ _validation = { "reseller_id": {"readonly": True}, "description": {"readonly": True}, } _attribute_map = { "reseller_id": {"key": "resellerId", "type": "str"}, "description": {"key": "description", "type": "str"}, } def __init__(self, **kwargs): """ """ super().__init__(**kwargs) self.reseller_id = None self.description = None class Reservation(_serialization.Model): # pylint: disable=too-many-instance-attributes """The definition of the reservation. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: The id of the reservation. :vartype id: str :ivar name: The name of the reservation. :vartype name: str :ivar type: The type of the reservation. :vartype type: str :ivar location: The location of the reservation. :vartype location: str :ivar sku: The sku information associated to this reservation. :vartype sku: ~azure.mgmt.billing.models.ReservationSkuProperty :ivar applied_scopes: The array of applied scopes of a reservation. Will be null if the reservation is in Shared scope. :vartype applied_scopes: list[str] :ivar applied_scope_type: The applied scope type of the reservation. :vartype applied_scope_type: str :ivar reserved_resource_type: The reserved source type of the reservation, e.g. virtual machine. :vartype reserved_resource_type: str :ivar quantity: The number of the reservation. :vartype quantity: float :ivar provisioning_state: The provisioning state of the reservation, e.g. Succeeded. :vartype provisioning_state: str :ivar expiry_date: The expiry date of the reservation. :vartype expiry_date: str :ivar provisioning_sub_state: The provisioning state of the reservation, e.g. Succeeded. :vartype provisioning_sub_state: str :ivar display_name: The display name of the reservation. :vartype display_name: str :ivar display_provisioning_state: The provisioning state of the reservation for display, e.g. Succeeded. :vartype display_provisioning_state: str :ivar user_friendly_renew_state: The renew state of the reservation for display, e.g. On. :vartype user_friendly_renew_state: str :ivar user_friendly_applied_scope_type: The applied scope type of the reservation for display, e.g. Shared. :vartype user_friendly_applied_scope_type: str :ivar effective_date_time: The effective date time of the reservation. :vartype effective_date_time: str :ivar sku_description: The sku description of the reservation. :vartype sku_description: str :ivar term: The term of the reservation, e.g. P1Y. :vartype term: str :ivar renew: The renew state of the reservation. :vartype renew: bool :ivar renew_source: The renew source of the reservation. :vartype renew_source: str :ivar utilization: Reservation utilization. :vartype utilization: ~azure.mgmt.billing.models.ReservationPropertyUtilization """ _validation = { "id": {"readonly": True}, "name": {"readonly": True}, "type": {"readonly": True}, "location": {"readonly": True}, "applied_scope_type": {"readonly": True}, "reserved_resource_type": {"readonly": True}, "quantity": {"readonly": True}, "provisioning_state": {"readonly": True}, "expiry_date": {"readonly": True}, "provisioning_sub_state": {"readonly": True}, "display_name": {"readonly": True}, "display_provisioning_state": {"readonly": True}, "user_friendly_renew_state": {"readonly": True}, "user_friendly_applied_scope_type": {"readonly": True}, "effective_date_time": {"readonly": True}, "sku_description": {"readonly": True}, "term": {"readonly": True}, "renew": {"readonly": True}, "renew_source": {"readonly": True}, "utilization": {"readonly": True}, } _attribute_map = { "id": {"key": "id", "type": "str"}, "name": {"key": "name", "type": "str"}, "type": {"key": "type", "type": "str"}, "location": {"key": "location", "type": "str"}, "sku": {"key": "sku", "type": "ReservationSkuProperty"}, "applied_scopes": {"key": "properties.appliedScopes", "type": "[str]"}, "applied_scope_type": {"key": "properties.appliedScopeType", "type": "str"}, "reserved_resource_type": {"key": "properties.reservedResourceType", "type": "str"}, "quantity": {"key": "properties.quantity", "type": "float"}, "provisioning_state": {"key": "properties.provisioningState", "type": "str"}, "expiry_date": {"key": "properties.expiryDate", "type": "str"}, "provisioning_sub_state": {"key": "properties.provisioningSubState", "type": "str"}, "display_name": {"key": "properties.displayName", "type": "str"}, "display_provisioning_state": {"key": "properties.displayProvisioningState", "type": "str"}, "user_friendly_renew_state": {"key": "properties.userFriendlyRenewState", "type": "str"}, "user_friendly_applied_scope_type": {"key": "properties.userFriendlyAppliedScopeType", "type": "str"}, "effective_date_time": {"key": "properties.effectiveDateTime", "type": "str"}, "sku_description": {"key": "properties.skuDescription", "type": "str"}, "term": {"key": "properties.term", "type": "str"}, "renew": {"key": "properties.renew", "type": "bool"}, "renew_source": {"key": "properties.renewSource", "type": "str"}, "utilization": {"key": "properties.utilization", "type": "ReservationPropertyUtilization"}, } def __init__( self, *, sku: Optional["_models.ReservationSkuProperty"] = None, applied_scopes: Optional[List[str]] = None, **kwargs ): """ :keyword sku: The sku information associated to this reservation. :paramtype sku: ~azure.mgmt.billing.models.ReservationSkuProperty :keyword applied_scopes: The array of applied scopes of a reservation. Will be null if the reservation is in Shared scope. :paramtype applied_scopes: list[str] """ super().__init__(**kwargs) self.id = None self.name = None self.type = None self.location = None self.sku = sku self.applied_scopes = applied_scopes self.applied_scope_type = None self.reserved_resource_type = None self.quantity = None self.provisioning_state = None self.expiry_date = None self.provisioning_sub_state = None self.display_name = None self.display_provisioning_state = None self.user_friendly_renew_state = None self.user_friendly_applied_scope_type = None self.effective_date_time = None self.sku_description = None self.term = None self.renew = None self.renew_source = None self.utilization = None class ReservationPropertyUtilization(_serialization.Model): """Reservation utilization. Variables are only populated by the server, and will be ignored when sending a request. :ivar trend: The number of days trend for a reservation. :vartype trend: str :ivar aggregates: The array of aggregates of a reservation's utilization. :vartype aggregates: list[~azure.mgmt.billing.models.ReservationUtilizationAggregates] """ _validation = { "trend": {"readonly": True}, } _attribute_map = { "trend": {"key": "trend", "type": "str"}, "aggregates": {"key": "aggregates", "type": "[ReservationUtilizationAggregates]"}, } def __init__(self, *, aggregates: Optional[List["_models.ReservationUtilizationAggregates"]] = None, **kwargs): """ :keyword aggregates: The array of aggregates of a reservation's utilization. :paramtype aggregates: list[~azure.mgmt.billing.models.ReservationUtilizationAggregates] """ super().__init__(**kwargs) self.trend = None self.aggregates = aggregates class ReservationSkuProperty(_serialization.Model): """The property of reservation sku object. Variables are only populated by the server, and will be ignored when sending a request. :ivar name: The name of the reservation sku. :vartype name: str """ _validation = { "name": {"readonly": True}, } _attribute_map = { "name": {"key": "name", "type": "str"}, } def __init__(self, **kwargs): """ """ super().__init__(**kwargs) self.name = None class ReservationsListResult(_serialization.Model): """The list of reservations and summary of roll out count of reservations in each state. Variables are only populated by the server, and will be ignored when sending a request. :ivar value: The list of reservations. :vartype value: list[~azure.mgmt.billing.models.Reservation] :ivar next_link: The link (url) to the next page of results. :vartype next_link: str :ivar summary: The roll out count summary of the reservations. :vartype summary: ~azure.mgmt.billing.models.ReservationSummary """ _validation = { "value": {"readonly": True}, "next_link": {"readonly": True}, } _attribute_map = { "value": {"key": "value", "type": "[Reservation]"}, "next_link": {"key": "nextLink", "type": "str"}, "summary": {"key": "summary", "type": "ReservationSummary"}, } def __init__(self, *, summary: Optional["_models.ReservationSummary"] = None, **kwargs): """ :keyword summary: The roll out count summary of the reservations. :paramtype summary: ~azure.mgmt.billing.models.ReservationSummary """ super().__init__(**kwargs) self.value = None self.next_link = None self.summary = summary class ReservationSummary(_serialization.Model): """The roll up count summary of reservations in each state. Variables are only populated by the server, and will be ignored when sending a request. :ivar succeeded_count: The number of reservation in Succeeded state. :vartype succeeded_count: float :ivar failed_count: The number of reservation in Failed state. :vartype failed_count: float :ivar expiring_count: The number of reservation in Expiring state. :vartype expiring_count: float :ivar expired_count: The number of reservation in Expired state. :vartype expired_count: float :ivar pending_count: The number of reservation in Pending state. :vartype pending_count: float :ivar cancelled_count: The number of reservation in Cancelled state. :vartype cancelled_count: float """ _validation = { "succeeded_count": {"readonly": True}, "failed_count": {"readonly": True}, "expiring_count": {"readonly": True}, "expired_count": {"readonly": True}, "pending_count": {"readonly": True}, "cancelled_count": {"readonly": True}, } _attribute_map = { "succeeded_count": {"key": "succeededCount", "type": "float"}, "failed_count": {"key": "failedCount", "type": "float"}, "expiring_count": {"key": "expiringCount", "type": "float"}, "expired_count": {"key": "expiredCount", "type": "float"}, "pending_count": {"key": "pendingCount", "type": "float"}, "cancelled_count": {"key": "cancelledCount", "type": "float"}, } def __init__(self, **kwargs): """ """ super().__init__(**kwargs) self.succeeded_count = None self.failed_count = None self.expiring_count = None self.expired_count = None self.pending_count = None self.cancelled_count = None class ReservationUtilizationAggregates(_serialization.Model): """The aggregate values of reservation utilization. Variables are only populated by the server, and will be ignored when sending a request. :ivar grain: The grain of the aggregate. :vartype grain: float :ivar grain_unit: The grain unit of the aggregate. :vartype grain_unit: str :ivar value: The aggregate value. :vartype value: float :ivar value_unit: The aggregate value unit. :vartype value_unit: str """ _validation = { "grain": {"readonly": True}, "grain_unit": {"readonly": True}, "value": {"readonly": True}, "value_unit": {"readonly": True}, } _attribute_map = { "grain": {"key": "grain", "type": "float"}, "grain_unit": {"key": "grainUnit", "type": "str"}, "value": {"key": "value", "type": "float"}, "value_unit": {"key": "valueUnit", "type": "str"}, } def __init__(self, **kwargs): """ """ super().__init__(**kwargs) self.grain = None self.grain_unit = None self.value = None self.value_unit = None class Transaction(Resource): # pylint: disable=too-many-instance-attributes """A transaction. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: Resource Id. :vartype id: str :ivar name: Resource name. :vartype name: str :ivar type: Resource type. :vartype type: str :ivar kind: The kind of transaction. Options are all or reservation. Known values are: "all" and "reservation". :vartype kind: str or ~azure.mgmt.billing.models.TransactionTypeKind :ivar date: The date of transaction. :vartype date: ~datetime.datetime :ivar invoice: Invoice on which the transaction was billed or 'pending' if the transaction is not billed. :vartype invoice: str :ivar invoice_id: The ID of the invoice on which the transaction was billed. This field is only applicable for transactions which are billed. :vartype invoice_id: str :ivar order_id: The order ID of the reservation. The field is only applicable for transaction of kind reservation. :vartype order_id: str :ivar order_name: The name of the reservation order. The field is only applicable for transactions of kind reservation. :vartype order_name: str :ivar product_family: The family of the product for which the transaction took place. :vartype product_family: str :ivar product_type_id: The ID of the product type for which the transaction took place. :vartype product_type_id: str :ivar product_type: The type of the product for which the transaction took place. :vartype product_type: str :ivar product_description: The description of the product for which the transaction took place. :vartype product_description: str :ivar transaction_type: The type of transaction. Known values are: "Purchase" and "Usage Charge". :vartype transaction_type: str or ~azure.mgmt.billing.models.ReservationType :ivar transaction_amount: The charge associated with the transaction. :vartype transaction_amount: ~azure.mgmt.billing.models.Amount :ivar quantity: The quantity purchased in the transaction. :vartype quantity: int :ivar invoice_section_id: The ID of the invoice section which will be billed for the transaction. :vartype invoice_section_id: str :ivar invoice_section_display_name: The name of the invoice section which will be billed for the transaction. :vartype invoice_section_display_name: str :ivar billing_profile_id: The ID of the billing profile which will be billed for the transaction. :vartype billing_profile_id: str :ivar billing_profile_display_name: The name of the billing profile which will be billed for the transaction. :vartype billing_profile_display_name: str :ivar customer_id: The ID of the customer for which the transaction took place. The field is applicable only for Microsoft Partner Agreement billing account. :vartype customer_id: str :ivar customer_display_name: The name of the customer for which the transaction took place. The field is applicable only for Microsoft Partner Agreement billing account. :vartype customer_display_name: str :ivar subscription_id: The ID of the subscription that was used for the transaction. The field is only applicable for transaction of kind reservation. :vartype subscription_id: str :ivar subscription_name: The name of the subscription that was used for the transaction. The field is only applicable for transaction of kind reservation. :vartype subscription_name: str :ivar azure_plan: The type of azure plan of the subscription that was used for the transaction. :vartype azure_plan: str :ivar azure_credit_applied: The amount of any Azure credits automatically applied to this transaction. :vartype azure_credit_applied: ~azure.mgmt.billing.models.Amount :ivar billing_currency: The ISO 4217 code for the currency in which this transaction is billed. :vartype billing_currency: str :ivar discount: The percentage discount, if any, applied to this transaction. :vartype discount: float :ivar effective_price: The price of the product after applying any discounts. :vartype effective_price: ~azure.mgmt.billing.models.Amount :ivar exchange_rate: The exchange rate used to convert charged amount to billing currency, if applicable. :vartype exchange_rate: float :ivar market_price: The retail price of the product. :vartype market_price: ~azure.mgmt.billing.models.Amount :ivar pricing_currency: The ISO 4217 code for the currency in which the product is priced. :vartype pricing_currency: str :ivar service_period_start_date: The date of the purchase of the product, or the start date of the month in which usage started. :vartype service_period_start_date: ~datetime.datetime :ivar service_period_end_date: The end date of the product term, or the end date of the month in which usage ended. :vartype service_period_end_date: ~datetime.datetime :ivar sub_total: The pre-tax charged amount for the transaction. :vartype sub_total: ~azure.mgmt.billing.models.Amount :ivar tax: The tax amount applied to the transaction. :vartype tax: ~azure.mgmt.billing.models.Amount :ivar unit_of_measure: The unit of measure used to bill for the product. For example, compute services are billed per hour. :vartype unit_of_measure: str :ivar units: The number of units used for a given product. :vartype units: float :ivar unit_type: The description for the unit of measure for a given product. :vartype unit_type: str """ _validation = { "id": {"readonly": True}, "name": {"readonly": True}, "type": {"readonly": True}, "date": {"readonly": True}, "invoice": {"readonly": True}, "invoice_id": {"readonly": True}, "order_id": {"readonly": True}, "order_name": {"readonly": True}, "product_family": {"readonly": True}, "product_type_id": {"readonly": True}, "product_type": {"readonly": True}, "product_description": {"readonly": True}, "transaction_amount": {"readonly": True}, "quantity": {"readonly": True}, "invoice_section_id": {"readonly": True}, "invoice_section_display_name": {"readonly": True}, "billing_profile_id": {"readonly": True}, "billing_profile_display_name": {"readonly": True}, "customer_id": {"readonly": True}, "customer_display_name": {"readonly": True}, "subscription_id": {"readonly": True}, "subscription_name": {"readonly": True}, "azure_plan": {"readonly": True}, "azure_credit_applied": {"readonly": True}, "billing_currency": {"readonly": True}, "discount": {"readonly": True}, "effective_price": {"readonly": True}, "exchange_rate": {"readonly": True}, "market_price": {"readonly": True}, "pricing_currency": {"readonly": True}, "service_period_start_date": {"readonly": True}, "service_period_end_date": {"readonly": True}, "sub_total": {"readonly": True}, "tax": {"readonly": True}, "unit_of_measure": {"readonly": True}, "units": {"readonly": True}, "unit_type": {"readonly": True}, } _attribute_map = { "id": {"key": "id", "type": "str"}, "name": {"key": "name", "type": "str"}, "type": {"key": "type", "type": "str"}, "kind": {"key": "properties.kind", "type": "str"}, "date": {"key": "properties.date", "type": "iso-8601"}, "invoice": {"key": "properties.invoice", "type": "str"}, "invoice_id": {"key": "properties.invoiceId", "type": "str"}, "order_id": {"key": "properties.orderId", "type": "str"}, "order_name": {"key": "properties.orderName", "type": "str"}, "product_family": {"key": "properties.productFamily", "type": "str"}, "product_type_id": {"key": "properties.productTypeId", "type": "str"}, "product_type": {"key": "properties.productType", "type": "str"}, "product_description": {"key": "properties.productDescription", "type": "str"}, "transaction_type": {"key": "properties.transactionType", "type": "str"}, "transaction_amount": {"key": "properties.transactionAmount", "type": "Amount"}, "quantity": {"key": "properties.quantity", "type": "int"}, "invoice_section_id": {"key": "properties.invoiceSectionId", "type": "str"}, "invoice_section_display_name": {"key": "properties.invoiceSectionDisplayName", "type": "str"}, "billing_profile_id": {"key": "properties.billingProfileId", "type": "str"}, "billing_profile_display_name": {"key": "properties.billingProfileDisplayName", "type": "str"}, "customer_id": {"key": "properties.customerId", "type": "str"}, "customer_display_name": {"key": "properties.customerDisplayName", "type": "str"}, "subscription_id": {"key": "properties.subscriptionId", "type": "str"}, "subscription_name": {"key": "properties.subscriptionName", "type": "str"}, "azure_plan": {"key": "properties.azurePlan", "type": "str"}, "azure_credit_applied": {"key": "properties.azureCreditApplied", "type": "Amount"}, "billing_currency": {"key": "properties.billingCurrency", "type": "str"}, "discount": {"key": "properties.discount", "type": "float"}, "effective_price": {"key": "properties.effectivePrice", "type": "Amount"}, "exchange_rate": {"key": "properties.exchangeRate", "type": "float"}, "market_price": {"key": "properties.marketPrice", "type": "Amount"}, "pricing_currency": {"key": "properties.pricingCurrency", "type": "str"}, "service_period_start_date": {"key": "properties.servicePeriodStartDate", "type": "iso-8601"}, "service_period_end_date": {"key": "properties.servicePeriodEndDate", "type": "iso-8601"}, "sub_total": {"key": "properties.subTotal", "type": "Amount"}, "tax": {"key": "properties.tax", "type": "Amount"}, "unit_of_measure": {"key": "properties.unitOfMeasure", "type": "str"}, "units": {"key": "properties.units", "type": "float"}, "unit_type": {"key": "properties.unitType", "type": "str"}, } def __init__( # pylint: disable=too-many-locals self, *, kind: Optional[Union[str, "_models.TransactionTypeKind"]] = None, transaction_type: Optional[Union[str, "_models.ReservationType"]] = None, **kwargs ): """ :keyword kind: The kind of transaction. Options are all or reservation. Known values are: "all" and "reservation". :paramtype kind: str or ~azure.mgmt.billing.models.TransactionTypeKind :keyword transaction_type: The type of transaction. Known values are: "Purchase" and "Usage Charge". :paramtype transaction_type: str or ~azure.mgmt.billing.models.ReservationType """ super().__init__(**kwargs) self.kind = kind self.date = None self.invoice = None self.invoice_id = None self.order_id = None self.order_name = None self.product_family = None self.product_type_id = None self.product_type = None self.product_description = None self.transaction_type = transaction_type self.transaction_amount = None self.quantity = None self.invoice_section_id = None self.invoice_section_display_name = None self.billing_profile_id = None self.billing_profile_display_name = None self.customer_id = None self.customer_display_name = None self.subscription_id = None self.subscription_name = None self.azure_plan = None self.azure_credit_applied = None self.billing_currency = None self.discount = None self.effective_price = None self.exchange_rate = None self.market_price = None self.pricing_currency = None self.service_period_start_date = None self.service_period_end_date = None self.sub_total = None self.tax = None self.unit_of_measure = None self.units = None self.unit_type = None class TransactionListResult(_serialization.Model): """The list of transactions. Variables are only populated by the server, and will be ignored when sending a request. :ivar value: The list of transactions. :vartype value: list[~azure.mgmt.billing.models.Transaction] :ivar total_count: Total number of records. :vartype total_count: int :ivar next_link: The link (url) to the next page of results. :vartype next_link: str """ _validation = { "value": {"readonly": True}, "total_count": {"readonly": True}, "next_link": {"readonly": True}, } _attribute_map = { "value": {"key": "value", "type": "[Transaction]"}, "total_count": {"key": "totalCount", "type": "int"}, "next_link": {"key": "nextLink", "type": "str"}, } def __init__(self, **kwargs): """ """ super().__init__(**kwargs) self.value = None self.total_count = None self.next_link = None class TransferBillingSubscriptionRequestProperties(_serialization.Model): """Request parameters to transfer billing subscription. All required parameters must be populated in order to send to Azure. :ivar destination_invoice_section_id: The destination invoice section id. Required. :vartype destination_invoice_section_id: str """ _validation = { "destination_invoice_section_id": {"required": True}, } _attribute_map = { "destination_invoice_section_id": {"key": "destinationInvoiceSectionId", "type": "str"}, } def __init__(self, *, destination_invoice_section_id: str, **kwargs): """ :keyword destination_invoice_section_id: The destination invoice section id. Required. :paramtype destination_invoice_section_id: str """ super().__init__(**kwargs) self.destination_invoice_section_id = destination_invoice_section_id class TransferProductRequestProperties(_serialization.Model): """The properties of the product to initiate a transfer. :ivar destination_invoice_section_id: The destination invoice section id. :vartype destination_invoice_section_id: str """ _attribute_map = { "destination_invoice_section_id": {"key": "destinationInvoiceSectionId", "type": "str"}, } def __init__(self, *, destination_invoice_section_id: Optional[str] = None, **kwargs): """ :keyword destination_invoice_section_id: The destination invoice section id. :paramtype destination_invoice_section_id: str """ super().__init__(**kwargs) self.destination_invoice_section_id = destination_invoice_section_id class ValidateAddressResponse(_serialization.Model): """Result of the address validation. :ivar status: status of the address validation. Known values are: "Valid" and "Invalid". :vartype status: str or ~azure.mgmt.billing.models.AddressValidationStatus :ivar suggested_addresses: The list of suggested addresses. :vartype suggested_addresses: list[~azure.mgmt.billing.models.AddressDetails] :ivar validation_message: Validation error message. :vartype validation_message: str """ _attribute_map = { "status": {"key": "status", "type": "str"}, "suggested_addresses": {"key": "suggestedAddresses", "type": "[AddressDetails]"}, "validation_message": {"key": "validationMessage", "type": "str"}, } def __init__( self, *, status: Optional[Union[str, "_models.AddressValidationStatus"]] = None, suggested_addresses: Optional[List["_models.AddressDetails"]] = None, validation_message: Optional[str] = None, **kwargs ): """ :keyword status: status of the address validation. Known values are: "Valid" and "Invalid". :paramtype status: str or ~azure.mgmt.billing.models.AddressValidationStatus :keyword suggested_addresses: The list of suggested addresses. :paramtype suggested_addresses: list[~azure.mgmt.billing.models.AddressDetails] :keyword validation_message: Validation error message. :paramtype validation_message: str """ super().__init__(**kwargs) self.status = status self.suggested_addresses = suggested_addresses self.validation_message = validation_message class ValidateProductTransferEligibilityError(_serialization.Model): """Error details of the product transfer eligibility validation. :ivar code: Error code for the product transfer validation. Known values are: "InvalidSource", "ProductNotActive", "InsufficientPermissionOnSource", "InsufficientPermissionOnDestination", "DestinationBillingProfilePastDue", "ProductTypeNotSupported", "CrossBillingAccountNotAllowed", "NotAvailableForDestinationMarket", and "OneTimePurchaseProductTransferNotAllowed". :vartype code: str or ~azure.mgmt.billing.models.ProductTransferValidationErrorCode :ivar message: The error message. :vartype message: str :ivar details: Detailed error message explaining the error. :vartype details: str """ _attribute_map = { "code": {"key": "code", "type": "str"}, "message": {"key": "message", "type": "str"}, "details": {"key": "details", "type": "str"}, } def __init__( self, *, code: Optional[Union[str, "_models.ProductTransferValidationErrorCode"]] = None, message: Optional[str] = None, details: Optional[str] = None, **kwargs ): """ :keyword code: Error code for the product transfer validation. Known values are: "InvalidSource", "ProductNotActive", "InsufficientPermissionOnSource", "InsufficientPermissionOnDestination", "DestinationBillingProfilePastDue", "ProductTypeNotSupported", "CrossBillingAccountNotAllowed", "NotAvailableForDestinationMarket", and "OneTimePurchaseProductTransferNotAllowed". :paramtype code: str or ~azure.mgmt.billing.models.ProductTransferValidationErrorCode :keyword message: The error message. :paramtype message: str :keyword details: Detailed error message explaining the error. :paramtype details: str """ super().__init__(**kwargs) self.code = code self.message = message self.details = details class ValidateProductTransferEligibilityResult(_serialization.Model): """Result of the product transfer eligibility validation. Variables are only populated by the server, and will be ignored when sending a request. :ivar is_move_eligible: Specifies whether the transfer is eligible or not. :vartype is_move_eligible: bool :ivar error_details: Validation error details. :vartype error_details: ~azure.mgmt.billing.models.ValidateProductTransferEligibilityError """ _validation = { "is_move_eligible": {"readonly": True}, } _attribute_map = { "is_move_eligible": {"key": "isMoveEligible", "type": "bool"}, "error_details": {"key": "errorDetails", "type": "ValidateProductTransferEligibilityError"}, } def __init__(self, *, error_details: Optional["_models.ValidateProductTransferEligibilityError"] = None, **kwargs): """ :keyword error_details: Validation error details. :paramtype error_details: ~azure.mgmt.billing.models.ValidateProductTransferEligibilityError """ super().__init__(**kwargs) self.is_move_eligible = None self.error_details = error_details class ValidateSubscriptionTransferEligibilityError(_serialization.Model): """Error details of the transfer eligibility validation. :ivar code: Error code for the product transfer validation. Known values are: "BillingAccountInactive", "CrossBillingAccountNotAllowed", "DestinationBillingProfileInactive", "DestinationBillingProfileNotFound", "DestinationBillingProfilePastDue", "DestinationInvoiceSectionInactive", "DestinationInvoiceSectionNotFound", "InsufficientPermissionOnDestination", "InsufficientPermissionOnSource", "InvalidDestination", "InvalidSource", "MarketplaceNotEnabledOnDestination", "NotAvailableForDestinationMarket", "ProductInactive", "ProductNotFound", "ProductTypeNotSupported", "SourceBillingProfilePastDue", "SourceInvoiceSectionInactive", "SubscriptionNotActive", and "SubscriptionTypeNotSupported". :vartype code: str or ~azure.mgmt.billing.models.SubscriptionTransferValidationErrorCode :ivar message: The error message. :vartype message: str :ivar details: Detailed error message explaining the error. :vartype details: str """ _attribute_map = { "code": {"key": "code", "type": "str"}, "message": {"key": "message", "type": "str"}, "details": {"key": "details", "type": "str"}, } def __init__( self, *, code: Optional[Union[str, "_models.SubscriptionTransferValidationErrorCode"]] = None, message: Optional[str] = None, details: Optional[str] = None, **kwargs ): """ :keyword code: Error code for the product transfer validation. Known values are: "BillingAccountInactive", "CrossBillingAccountNotAllowed", "DestinationBillingProfileInactive", "DestinationBillingProfileNotFound", "DestinationBillingProfilePastDue", "DestinationInvoiceSectionInactive", "DestinationInvoiceSectionNotFound", "InsufficientPermissionOnDestination", "InsufficientPermissionOnSource", "InvalidDestination", "InvalidSource", "MarketplaceNotEnabledOnDestination", "NotAvailableForDestinationMarket", "ProductInactive", "ProductNotFound", "ProductTypeNotSupported", "SourceBillingProfilePastDue", "SourceInvoiceSectionInactive", "SubscriptionNotActive", and "SubscriptionTypeNotSupported". :paramtype code: str or ~azure.mgmt.billing.models.SubscriptionTransferValidationErrorCode :keyword message: The error message. :paramtype message: str :keyword details: Detailed error message explaining the error. :paramtype details: str """ super().__init__(**kwargs) self.code = code self.message = message self.details = details class ValidateSubscriptionTransferEligibilityResult(_serialization.Model): """Result of the transfer eligibility validation. Variables are only populated by the server, and will be ignored when sending a request. :ivar is_move_eligible: Specifies whether the subscription is eligible to be transferred. :vartype is_move_eligible: bool :ivar error_details: Validation error details. :vartype error_details: ~azure.mgmt.billing.models.ValidateSubscriptionTransferEligibilityError """ _validation = { "is_move_eligible": {"readonly": True}, } _attribute_map = { "is_move_eligible": {"key": "isMoveEligible", "type": "bool"}, "error_details": {"key": "errorDetails", "type": "ValidateSubscriptionTransferEligibilityError"}, } def __init__( self, *, error_details: Optional["_models.ValidateSubscriptionTransferEligibilityError"] = None, **kwargs ): """ :keyword error_details: Validation error details. :paramtype error_details: ~azure.mgmt.billing.models.ValidateSubscriptionTransferEligibilityError """ super().__init__(**kwargs) self.is_move_eligible = None self.error_details = error_details
0.851845
0.282156