diff --git a/sdk/batch/azure-mgmt-batch/_meta.json b/sdk/batch/azure-mgmt-batch/_meta.json index e58dbb95f578..1081cdd7c08b 100644 --- a/sdk/batch/azure-mgmt-batch/_meta.json +++ b/sdk/batch/azure-mgmt-batch/_meta.json @@ -1,11 +1,11 @@ { - "autorest": "3.7.2", + "commit": "999f2d3706c86ce460c2817f52f684110f2a8b30", + "repository_url": "https://github.com/Azure/azure-rest-api-specs", + "autorest": "3.9.2", "use": [ - "@autorest/python@5.13.0", - "@autorest/modelerfour@4.19.3" + "@autorest/python@6.2.1", + "@autorest/modelerfour@4.24.3" ], - "commit": "5ee062ac3cc2df298ff47bdfc7792d257fd85bb8", - "repository_url": "https://github.com/Azure/azure-rest-api-specs", - "autorest_command": "autorest specification/batch/resource-manager/readme.md --multiapi --python --python-sdks-folder=/home/vsts/work/1/azure-sdk-for-python/sdk --python3-only --use=@autorest/python@5.13.0 --use=@autorest/modelerfour@4.19.3 --version=3.7.2", + "autorest_command": "autorest specification/batch/resource-manager/readme.md --generate-sample=True --include-x-ms-examples-original-file=True --python --python-sdks-folder=/mnt/vss/_work/1/s/azure-sdk-for-python/sdk --use=@autorest/python@6.2.1 --use=@autorest/modelerfour@4.24.3 --version=3.9.2 --version-tolerant=False", "readme": "specification/batch/resource-manager/readme.md" } \ No newline at end of file diff --git a/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/__init__.py b/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/__init__.py index 21eada7ba672..8bc8749db5e0 100644 --- a/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/__init__.py +++ b/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/__init__.py @@ -10,9 +10,17 @@ from ._version import VERSION __version__ = VERSION -__all__ = ['BatchManagementClient'] -# `._patch.py` is used for handwritten extensions to the generated code -# Example: https://github.com/Azure/azure-sdk-for-python/blob/main/doc/dev/customize_code/how-to-patch-sdk-code.md -from ._patch import patch_sdk -patch_sdk() +try: + from ._patch import __all__ as _patch_all + from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import +except ImportError: + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "BatchManagementClient", +] +__all__.extend([p for p in _patch_all if p not in __all__]) + +_patch_sdk() diff --git a/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/_batch_management_client.py b/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/_batch_management_client.py index ce3f8284efbf..3a50c8e8c354 100644 --- a/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/_batch_management_client.py +++ b/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/_batch_management_client.py @@ -9,20 +9,30 @@ from copy import deepcopy from typing import Any, TYPE_CHECKING -from msrest import Deserializer, Serializer - from azure.core.rest import HttpRequest, HttpResponse from azure.mgmt.core import ARMPipelineClient from . import models from ._configuration import BatchManagementClientConfiguration -from .operations import ApplicationOperations, ApplicationPackageOperations, BatchAccountOperations, CertificateOperations, LocationOperations, Operations, PoolOperations, PrivateEndpointConnectionOperations, PrivateLinkResourceOperations +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=too-many-instance-attributes + +class BatchManagementClient: # pylint: disable=client-accepts-api-version-keyword,too-many-instance-attributes """Batch Client. :ivar batch_account: BatchAccountOperations operations @@ -44,14 +54,14 @@ class BatchManagementClient: # pylint: disable=too-many-instance-attributes 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. + :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). + 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 "2022-06-01". Note that overriding this + :keyword api_version: Api Version. Default value is "2022-10-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 @@ -65,7 +75,9 @@ def __init__( base_url: str = "https://management.azure.com", **kwargs: Any ) -> None: - self._config = BatchManagementClientConfiguration(credential=credential, subscription_id=subscription_id, **kwargs) + self._config = BatchManagementClientConfiguration( + 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)} @@ -73,21 +85,22 @@ def __init__( 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_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.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: + 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 @@ -96,7 +109,7 @@ def _send_request( >>> response = client._send_request(request) - For more information on this code flow, see https://aka.ms/azsdk/python/protocol/quickstart + 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 diff --git a/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/_configuration.py b/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/_configuration.py index f67b4b421e9e..3ec69b883c57 100644 --- a/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/_configuration.py +++ b/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/_configuration.py @@ -6,6 +6,7 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +import sys from typing import Any, TYPE_CHECKING from azure.core.configuration import Configuration @@ -14,6 +15,11 @@ from ._version import VERSION +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 azure.core.credentials import TokenCredential @@ -25,24 +31,19 @@ class BatchManagementClientConfiguration(Configuration): # pylint: disable=too- 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. + :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). + 00000000-0000-0000-0000-000000000000). Required. :type subscription_id: str - :keyword api_version: Api Version. Default value is "2022-06-01". Note that overriding this + :keyword api_version: Api Version. Default value is "2022-10-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: + def __init__(self, credential: "TokenCredential", subscription_id: str, **kwargs: Any) -> None: super(BatchManagementClientConfiguration, self).__init__(**kwargs) - api_version = kwargs.pop('api_version', "2022-06-01") # type: str + api_version = kwargs.pop("api_version", "2022-10-01") # type: Literal["2022-10-01"] if credential is None: raise ValueError("Parameter 'credential' must not be None.") @@ -52,23 +53,24 @@ def __init__( 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.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 # type: Any + 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') + 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) + self.authentication_policy = ARMChallengeAuthenticationPolicy( + self.credential, *self.credential_scopes, **kwargs + ) diff --git a/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/_metadata.json b/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/_metadata.json deleted file mode 100644 index 53ef74f54103..000000000000 --- a/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/_metadata.json +++ /dev/null @@ -1,110 +0,0 @@ -{ - "chosen_version": "2022-06-01", - "total_api_version_list": ["2022-06-01"], - "client": { - "name": "BatchManagementClient", - "filename": "_batch_management_client", - "description": "Batch Client.", - "host_value": "\"https://management.azure.com\"", - "parameterized_host_template": null, - "azure_arm": true, - "has_lro_operations": true, - "client_side_validation": false, - "sync_imports": "{\"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}, \"regular\": {\"azurecore\": {\"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"], \"azure.mgmt.core\": [\"ARMPipelineClient\"]}, \"local\": {\"._configuration\": [\"BatchManagementClientConfiguration\"]}, \"thirdparty\": {\"msrest\": [\"Deserializer\", \"Serializer\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}}", - "async_imports": "{\"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"], \"azure.core.credentials\": [\"TokenCredential\"]}}, \"regular\": {\"azurecore\": {\"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"], \"azure.mgmt.core\": [\"AsyncARMPipelineClient\"]}, \"local\": {\"._configuration\": [\"BatchManagementClientConfiguration\"]}, \"thirdparty\": {\"msrest\": [\"Deserializer\", \"Serializer\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}}" - }, - "global_parameters": { - "sync": { - "credential": { - "signature": "credential, # type: \"TokenCredential\"", - "description": "Credential needed for the client to connect to Azure.", - "docstring_type": "~azure.core.credentials.TokenCredential", - "required": true - }, - "subscription_id": { - "signature": "subscription_id, # type: str", - "description": "The Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000).", - "docstring_type": "str", - "required": true - } - }, - "async": { - "credential": { - "signature": "credential: \"AsyncTokenCredential\",", - "description": "Credential needed for the client to connect to Azure.", - "docstring_type": "~azure.core.credentials_async.AsyncTokenCredential", - "required": true - }, - "subscription_id": { - "signature": "subscription_id: str,", - "description": "The Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000).", - "docstring_type": "str", - "required": true - } - }, - "constant": { - }, - "call": "credential, subscription_id", - "service_client_specific": { - "sync": { - "api_version": { - "signature": "api_version=None, # type: Optional[str]", - "description": "API version to use if no profile is provided, or if missing in profile.", - "docstring_type": "str", - "required": false - }, - "base_url": { - "signature": "base_url=\"https://management.azure.com\", # type: str", - "description": "Service URL", - "docstring_type": "str", - "required": false - }, - "profile": { - "signature": "profile=KnownProfiles.default, # type: KnownProfiles", - "description": "A profile definition, from KnownProfiles to dict.", - "docstring_type": "azure.profiles.KnownProfiles", - "required": false - } - }, - "async": { - "api_version": { - "signature": "api_version: Optional[str] = None,", - "description": "API version to use if no profile is provided, or if missing in profile.", - "docstring_type": "str", - "required": false - }, - "base_url": { - "signature": "base_url: str = \"https://management.azure.com\",", - "description": "Service URL", - "docstring_type": "str", - "required": false - }, - "profile": { - "signature": "profile: KnownProfiles = KnownProfiles.default,", - "description": "A profile definition, from KnownProfiles to dict.", - "docstring_type": "azure.profiles.KnownProfiles", - "required": false - } - } - } - }, - "config": { - "credential": true, - "credential_scopes": ["https://management.azure.com/.default"], - "credential_call_sync": "ARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs)", - "credential_call_async": "AsyncARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs)", - "sync_imports": "{\"regular\": {\"azurecore\": {\"azure.core.configuration\": [\"Configuration\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMChallengeAuthenticationPolicy\", \"ARMHttpLoggingPolicy\"]}, \"local\": {\"._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", - "async_imports": "{\"regular\": {\"azurecore\": {\"azure.core.configuration\": [\"Configuration\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMHttpLoggingPolicy\", \"AsyncARMChallengeAuthenticationPolicy\"]}, \"local\": {\".._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" - }, - "operation_groups": { - "batch_account": "BatchAccountOperations", - "application_package": "ApplicationPackageOperations", - "application": "ApplicationOperations", - "location": "LocationOperations", - "operations": "Operations", - "certificate": "CertificateOperations", - "private_link_resource": "PrivateLinkResourceOperations", - "private_endpoint_connection": "PrivateEndpointConnectionOperations", - "pool": "PoolOperations" - } -} \ No newline at end of file diff --git a/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/_patch.py b/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/_patch.py index 74e48ecd07cf..f99e77fef986 100644 --- a/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/_patch.py +++ b/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/_patch.py @@ -28,4 +28,4 @@ # This file is used for handwritten extensions to the generated code. Example: # https://github.com/Azure/azure-sdk-for-python/blob/main/doc/dev/customize_code/how-to-patch-sdk-code.md def patch_sdk(): - pass \ No newline at end of file + pass diff --git a/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/_serialization.py b/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/_serialization.py new file mode 100644 index 000000000000..7c1dedb5133d --- /dev/null +++ b/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/_serialization.py @@ -0,0 +1,1970 @@ +# -------------------------------------------------------------------------- +# +# Copyright (c) Microsoft Corporation. All rights reserved. +# +# The MIT License (MIT) +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the ""Software""), to +# deal in the Software without restriction, including without limitation the +# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +# sell copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +# IN THE SOFTWARE. +# +# -------------------------------------------------------------------------- + +# pylint: skip-file + +from base64 import b64decode, b64encode +import calendar +import datetime +import decimal +import email +from enum import Enum +import json +import logging +import re +import sys +import codecs + +try: + from urllib import quote # type: ignore +except ImportError: + from urllib.parse import quote # type: ignore +import xml.etree.ElementTree as ET + +import isodate + +from typing import Dict, Any, cast, TYPE_CHECKING + +from azure.core.exceptions import DeserializationError, SerializationError, raise_with_traceback + +_BOM = codecs.BOM_UTF8.decode(encoding="utf-8") + +if TYPE_CHECKING: + from typing import Optional, Union, AnyStr, IO, Mapping + + +class RawDeserializer: + + # Accept "text" because we're open minded people... + JSON_REGEXP = re.compile(r"^(application|text)/([a-z+.]+\+)?json$") + + # Name used in context + CONTEXT_NAME = "deserialized_data" + + @classmethod + def deserialize_from_text(cls, data, content_type=None): + # type: (Optional[Union[AnyStr, IO]], Optional[str]) -> Any + """Decode data according to content-type. + + Accept a stream of data as well, but will be load at once in memory for now. + + If no content-type, will return the string version (not bytes, not stream) + + :param data: Input, could be bytes or stream (will be decoded with UTF8) or text + :type data: str or bytes or IO + :param str content_type: The content type. + """ + if hasattr(data, "read"): + # Assume a stream + data = cast(IO, data).read() + + if isinstance(data, bytes): + data_as_str = data.decode(encoding="utf-8-sig") + else: + # Explain to mypy the correct type. + data_as_str = cast(str, data) + + # Remove Byte Order Mark if present in string + data_as_str = data_as_str.lstrip(_BOM) + + if content_type is None: + return data + + if cls.JSON_REGEXP.match(content_type): + try: + return json.loads(data_as_str) + except ValueError as err: + raise DeserializationError("JSON is invalid: {}".format(err), err) + elif "xml" in (content_type or []): + try: + + try: + if isinstance(data, unicode): # type: ignore + # If I'm Python 2.7 and unicode XML will scream if I try a "fromstring" on unicode string + data_as_str = data_as_str.encode(encoding="utf-8") # type: ignore + except NameError: + pass + + return ET.fromstring(data_as_str) # nosec + except ET.ParseError: + # It might be because the server has an issue, and returned JSON with + # content-type XML.... + # So let's try a JSON load, and if it's still broken + # let's flow the initial exception + def _json_attemp(data): + try: + return True, json.loads(data) + except ValueError: + return False, None # Don't care about this one + + success, json_result = _json_attemp(data) + if success: + return json_result + # If i'm here, it's not JSON, it's not XML, let's scream + # and raise the last context in this block (the XML exception) + # The function hack is because Py2.7 messes up with exception + # context otherwise. + _LOGGER.critical("Wasn't XML not JSON, failing") + raise_with_traceback(DeserializationError, "XML is invalid") + raise DeserializationError("Cannot deserialize content-type: {}".format(content_type)) + + @classmethod + def deserialize_from_http_generics(cls, body_bytes, headers): + # type: (Optional[Union[AnyStr, IO]], Mapping) -> Any + """Deserialize from HTTP response. + + Use bytes and headers to NOT use any requests/aiohttp or whatever + specific implementation. + Headers will tested for "content-type" + """ + # Try to use content-type from headers if available + content_type = None + if "content-type" in headers: + content_type = headers["content-type"].split(";")[0].strip().lower() + # Ouch, this server did not declare what it sent... + # Let's guess it's JSON... + # Also, since Autorest was considering that an empty body was a valid JSON, + # need that test as well.... + else: + content_type = "application/json" + + if body_bytes: + return cls.deserialize_from_text(body_bytes, content_type) + return None + + +try: + basestring # type: ignore + unicode_str = unicode # type: ignore +except NameError: + basestring = str # type: ignore + unicode_str = str # type: ignore + +_LOGGER = logging.getLogger(__name__) + +try: + _long_type = long # type: ignore +except NameError: + _long_type = int + + +class UTC(datetime.tzinfo): + """Time Zone info for handling UTC""" + + def utcoffset(self, dt): + """UTF offset for UTC is 0.""" + return datetime.timedelta(0) + + def tzname(self, dt): + """Timestamp representation.""" + return "Z" + + def dst(self, dt): + """No daylight saving for UTC.""" + return datetime.timedelta(hours=1) + + +try: + from datetime import timezone as _FixedOffset +except ImportError: # Python 2.7 + + class _FixedOffset(datetime.tzinfo): # type: ignore + """Fixed offset in minutes east from UTC. + Copy/pasted from Python doc + :param datetime.timedelta offset: offset in timedelta format + """ + + def __init__(self, offset): + self.__offset = offset + + def utcoffset(self, dt): + return self.__offset + + def tzname(self, dt): + return str(self.__offset.total_seconds() / 3600) + + def __repr__(self): + return "".format(self.tzname(None)) + + def dst(self, dt): + return datetime.timedelta(0) + + def __getinitargs__(self): + return (self.__offset,) + + +try: + from datetime import timezone + + TZ_UTC = timezone.utc # type: ignore +except ImportError: + TZ_UTC = UTC() # type: ignore + +_FLATTEN = re.compile(r"(? y, + "minimum": lambda x, y: x < y, + "maximum": lambda x, y: x > y, + "minimum_ex": lambda x, y: x <= y, + "maximum_ex": lambda x, y: x >= y, + "min_items": lambda x, y: len(x) < y, + "max_items": lambda x, y: len(x) > y, + "pattern": lambda x, y: not re.match(y, x, re.UNICODE), + "unique": lambda x, y: len(x) != len(set(x)), + "multiple": lambda x, y: x % y != 0, + } + + def __init__(self, classes=None): + self.serialize_type = { + "iso-8601": Serializer.serialize_iso, + "rfc-1123": Serializer.serialize_rfc, + "unix-time": Serializer.serialize_unix, + "duration": Serializer.serialize_duration, + "date": Serializer.serialize_date, + "time": Serializer.serialize_time, + "decimal": Serializer.serialize_decimal, + "long": Serializer.serialize_long, + "bytearray": Serializer.serialize_bytearray, + "base64": Serializer.serialize_base64, + "object": self.serialize_object, + "[]": self.serialize_iter, + "{}": self.serialize_dict, + } + self.dependencies = dict(classes) if classes else {} + self.key_transformer = full_restapi_key_transformer + self.client_side_validation = True + + def _serialize(self, target_obj, data_type=None, **kwargs): + """Serialize data into a string according to type. + + :param target_obj: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: str, dict + :raises: SerializationError if serialization fails. + """ + key_transformer = kwargs.get("key_transformer", self.key_transformer) + keep_readonly = kwargs.get("keep_readonly", False) + if target_obj is None: + return None + + attr_name = None + class_name = target_obj.__class__.__name__ + + if data_type: + return self.serialize_data(target_obj, data_type, **kwargs) + + if not hasattr(target_obj, "_attribute_map"): + data_type = type(target_obj).__name__ + if data_type in self.basic_types.values(): + return self.serialize_data(target_obj, data_type, **kwargs) + + # Force "is_xml" kwargs if we detect a XML model + try: + is_xml_model_serialization = kwargs["is_xml"] + except KeyError: + is_xml_model_serialization = kwargs.setdefault("is_xml", target_obj.is_xml_model()) + + serialized = {} + if is_xml_model_serialization: + serialized = target_obj._create_xml_node() + try: + attributes = target_obj._attribute_map + for attr, attr_desc in attributes.items(): + attr_name = attr + if not keep_readonly and target_obj._validation.get(attr_name, {}).get("readonly", False): + continue + + if attr_name == "additional_properties" and attr_desc["key"] == "": + if target_obj.additional_properties is not None: + serialized.update(target_obj.additional_properties) + continue + try: + + orig_attr = getattr(target_obj, attr) + if is_xml_model_serialization: + pass # Don't provide "transformer" for XML for now. Keep "orig_attr" + else: # JSON + keys, orig_attr = key_transformer(attr, attr_desc.copy(), orig_attr) + keys = keys if isinstance(keys, list) else [keys] + + kwargs["serialization_ctxt"] = attr_desc + new_attr = self.serialize_data(orig_attr, attr_desc["type"], **kwargs) + + if is_xml_model_serialization: + xml_desc = attr_desc.get("xml", {}) + xml_name = xml_desc.get("name", attr_desc["key"]) + xml_prefix = xml_desc.get("prefix", None) + xml_ns = xml_desc.get("ns", None) + if xml_desc.get("attr", False): + if xml_ns: + ET.register_namespace(xml_prefix, xml_ns) + xml_name = "{}{}".format(xml_ns, xml_name) + serialized.set(xml_name, new_attr) + continue + if xml_desc.get("text", False): + serialized.text = new_attr + continue + if isinstance(new_attr, list): + serialized.extend(new_attr) + elif isinstance(new_attr, ET.Element): + # If the down XML has no XML/Name, we MUST replace the tag with the local tag. But keeping the namespaces. + if "name" not in getattr(orig_attr, "_xml_map", {}): + splitted_tag = new_attr.tag.split("}") + if len(splitted_tag) == 2: # Namespace + new_attr.tag = "}".join([splitted_tag[0], xml_name]) + else: + new_attr.tag = xml_name + serialized.append(new_attr) + else: # That's a basic type + # Integrate namespace if necessary + local_node = _create_xml_node(xml_name, xml_prefix, xml_ns) + local_node.text = unicode_str(new_attr) + serialized.append(local_node) + else: # JSON + for k in reversed(keys): + unflattened = {k: new_attr} + new_attr = unflattened + + _new_attr = new_attr + _serialized = serialized + for k in keys: + if k not in _serialized: + _serialized.update(_new_attr) + _new_attr = _new_attr[k] + _serialized = _serialized[k] + except ValueError: + continue + + except (AttributeError, KeyError, TypeError) as err: + msg = "Attribute {} in object {} cannot be serialized.\n{}".format(attr_name, class_name, str(target_obj)) + raise_with_traceback(SerializationError, msg, err) + else: + return serialized + + def body(self, data, data_type, **kwargs): + """Serialize data intended for a request body. + + :param data: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: dict + :raises: SerializationError if serialization fails. + :raises: ValueError if data is None + """ + + # Just in case this is a dict + internal_data_type = data_type.strip("[]{}") + internal_data_type = self.dependencies.get(internal_data_type, None) + try: + is_xml_model_serialization = kwargs["is_xml"] + except KeyError: + if internal_data_type and issubclass(internal_data_type, Model): + is_xml_model_serialization = kwargs.setdefault("is_xml", internal_data_type.is_xml_model()) + else: + is_xml_model_serialization = False + if internal_data_type and not isinstance(internal_data_type, Enum): + try: + deserializer = Deserializer(self.dependencies) + # Since it's on serialization, it's almost sure that format is not JSON REST + # We're not able to deal with additional properties for now. + deserializer.additional_properties_detection = False + if is_xml_model_serialization: + deserializer.key_extractors = [ + attribute_key_case_insensitive_extractor, + ] + else: + deserializer.key_extractors = [ + rest_key_case_insensitive_extractor, + attribute_key_case_insensitive_extractor, + last_rest_key_case_insensitive_extractor, + ] + data = deserializer._deserialize(data_type, data) + except DeserializationError as err: + raise_with_traceback(SerializationError, "Unable to build a model: " + str(err), err) + + return self._serialize(data, data_type, **kwargs) + + def url(self, name, data, data_type, **kwargs): + """Serialize data intended for a URL path. + + :param data: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: str + :raises: TypeError if serialization fails. + :raises: ValueError if data is None + """ + try: + output = self.serialize_data(data, data_type, **kwargs) + if data_type == "bool": + output = json.dumps(output) + + if kwargs.get("skip_quote") is True: + output = str(output) + else: + output = quote(str(output), safe="") + except SerializationError: + raise TypeError("{} must be type {}.".format(name, data_type)) + else: + return output + + def query(self, name, data, data_type, **kwargs): + """Serialize data intended for a URL query. + + :param data: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: str + :raises: TypeError if serialization fails. + :raises: ValueError if data is None + """ + try: + # Treat the list aside, since we don't want to encode the div separator + if data_type.startswith("["): + internal_data_type = data_type[1:-1] + data = [self.serialize_data(d, internal_data_type, **kwargs) if d is not None else "" for d in data] + if not kwargs.get("skip_quote", False): + data = [quote(str(d), safe="") for d in data] + return str(self.serialize_iter(data, internal_data_type, **kwargs)) + + # Not a list, regular serialization + output = self.serialize_data(data, data_type, **kwargs) + if data_type == "bool": + output = json.dumps(output) + if kwargs.get("skip_quote") is True: + output = str(output) + else: + output = quote(str(output), safe="") + except SerializationError: + raise TypeError("{} must be type {}.".format(name, data_type)) + else: + return str(output) + + def header(self, name, data, data_type, **kwargs): + """Serialize data intended for a request header. + + :param data: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: str + :raises: TypeError if serialization fails. + :raises: ValueError if data is None + """ + try: + if data_type in ["[str]"]: + data = ["" if d is None else d for d in data] + + output = self.serialize_data(data, data_type, **kwargs) + if data_type == "bool": + output = json.dumps(output) + except SerializationError: + raise TypeError("{} must be type {}.".format(name, data_type)) + else: + return str(output) + + def serialize_data(self, data, data_type, **kwargs): + """Serialize generic data according to supplied data type. + + :param data: The data to be serialized. + :param str data_type: The type to be serialized from. + :param bool required: Whether it's essential that the data not be + empty or None + :raises: AttributeError if required data is None. + :raises: ValueError if data is None + :raises: SerializationError if serialization fails. + """ + if data is None: + raise ValueError("No value for given attribute") + + try: + if data_type in self.basic_types.values(): + return self.serialize_basic(data, data_type, **kwargs) + + elif data_type in self.serialize_type: + return self.serialize_type[data_type](data, **kwargs) + + # If dependencies is empty, try with current data class + # It has to be a subclass of Enum anyway + enum_type = self.dependencies.get(data_type, data.__class__) + if issubclass(enum_type, Enum): + return Serializer.serialize_enum(data, enum_obj=enum_type) + + iter_type = data_type[0] + data_type[-1] + if iter_type in self.serialize_type: + return self.serialize_type[iter_type](data, data_type[1:-1], **kwargs) + + except (ValueError, TypeError) as err: + msg = "Unable to serialize value: {!r} as type: {!r}." + raise_with_traceback(SerializationError, msg.format(data, data_type), err) + else: + return self._serialize(data, **kwargs) + + @classmethod + def _get_custom_serializers(cls, data_type, **kwargs): + custom_serializer = kwargs.get("basic_types_serializers", {}).get(data_type) + if custom_serializer: + return custom_serializer + if kwargs.get("is_xml", False): + return cls._xml_basic_types_serializers.get(data_type) + + @classmethod + def serialize_basic(cls, data, data_type, **kwargs): + """Serialize basic builting data type. + Serializes objects to str, int, float or bool. + + Possible kwargs: + - basic_types_serializers dict[str, callable] : If set, use the callable as serializer + - is_xml bool : If set, use xml_basic_types_serializers + + :param data: Object to be serialized. + :param str data_type: Type of object in the iterable. + """ + custom_serializer = cls._get_custom_serializers(data_type, **kwargs) + if custom_serializer: + return custom_serializer(data) + if data_type == "str": + return cls.serialize_unicode(data) + return eval(data_type)(data) # nosec + + @classmethod + def serialize_unicode(cls, data): + """Special handling for serializing unicode strings in Py2. + Encode to UTF-8 if unicode, otherwise handle as a str. + + :param data: Object to be serialized. + :rtype: str + """ + try: # If I received an enum, return its value + return data.value + except AttributeError: + pass + + try: + if isinstance(data, unicode): + # Don't change it, JSON and XML ElementTree are totally able + # to serialize correctly u'' strings + return data + except NameError: + return str(data) + else: + return str(data) + + def serialize_iter(self, data, iter_type, div=None, **kwargs): + """Serialize iterable. + + Supported kwargs: + - serialization_ctxt dict : The current entry of _attribute_map, or same format. + serialization_ctxt['type'] should be same as data_type. + - is_xml bool : If set, serialize as XML + + :param list attr: Object to be serialized. + :param str iter_type: Type of object in the iterable. + :param bool required: Whether the objects in the iterable must + not be None or empty. + :param str div: If set, this str will be used to combine the elements + in the iterable into a combined string. Default is 'None'. + :rtype: list, str + """ + if isinstance(data, str): + raise SerializationError("Refuse str type as a valid iter type.") + + serialization_ctxt = kwargs.get("serialization_ctxt", {}) + is_xml = kwargs.get("is_xml", False) + + serialized = [] + for d in data: + try: + serialized.append(self.serialize_data(d, iter_type, **kwargs)) + except ValueError: + serialized.append(None) + + if div: + serialized = ["" if s is None else str(s) for s in serialized] + serialized = div.join(serialized) + + if "xml" in serialization_ctxt or is_xml: + # XML serialization is more complicated + xml_desc = serialization_ctxt.get("xml", {}) + xml_name = xml_desc.get("name") + if not xml_name: + xml_name = serialization_ctxt["key"] + + # Create a wrap node if necessary (use the fact that Element and list have "append") + is_wrapped = xml_desc.get("wrapped", False) + node_name = xml_desc.get("itemsName", xml_name) + if is_wrapped: + final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) + else: + final_result = [] + # All list elements to "local_node" + for el in serialized: + if isinstance(el, ET.Element): + el_node = el + else: + el_node = _create_xml_node(node_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) + if el is not None: # Otherwise it writes "None" :-p + el_node.text = str(el) + final_result.append(el_node) + return final_result + return serialized + + def serialize_dict(self, attr, dict_type, **kwargs): + """Serialize a dictionary of objects. + + :param dict attr: Object to be serialized. + :param str dict_type: Type of object in the dictionary. + :param bool required: Whether the objects in the dictionary must + not be None or empty. + :rtype: dict + """ + serialization_ctxt = kwargs.get("serialization_ctxt", {}) + serialized = {} + for key, value in attr.items(): + try: + serialized[self.serialize_unicode(key)] = self.serialize_data(value, dict_type, **kwargs) + except ValueError: + serialized[self.serialize_unicode(key)] = None + + if "xml" in serialization_ctxt: + # XML serialization is more complicated + xml_desc = serialization_ctxt["xml"] + xml_name = xml_desc["name"] + + final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) + for key, value in serialized.items(): + ET.SubElement(final_result, key).text = value + return final_result + + return serialized + + def serialize_object(self, attr, **kwargs): + """Serialize a generic object. + This will be handled as a dictionary. If object passed in is not + a basic type (str, int, float, dict, list) it will simply be + cast to str. + + :param dict attr: Object to be serialized. + :rtype: dict or str + """ + if attr is None: + return None + if isinstance(attr, ET.Element): + return attr + obj_type = type(attr) + if obj_type in self.basic_types: + return self.serialize_basic(attr, self.basic_types[obj_type], **kwargs) + if obj_type is _long_type: + return self.serialize_long(attr) + if obj_type is unicode_str: + return self.serialize_unicode(attr) + if obj_type is datetime.datetime: + return self.serialize_iso(attr) + if obj_type is datetime.date: + return self.serialize_date(attr) + if obj_type is datetime.time: + return self.serialize_time(attr) + if obj_type is datetime.timedelta: + return self.serialize_duration(attr) + if obj_type is decimal.Decimal: + return self.serialize_decimal(attr) + + # If it's a model or I know this dependency, serialize as a Model + elif obj_type in self.dependencies.values() or isinstance(attr, Model): + return self._serialize(attr) + + if obj_type == dict: + serialized = {} + for key, value in attr.items(): + try: + serialized[self.serialize_unicode(key)] = self.serialize_object(value, **kwargs) + except ValueError: + serialized[self.serialize_unicode(key)] = None + return serialized + + if obj_type == list: + serialized = [] + for obj in attr: + try: + serialized.append(self.serialize_object(obj, **kwargs)) + except ValueError: + pass + return serialized + return str(attr) + + @staticmethod + def serialize_enum(attr, enum_obj=None): + try: + result = attr.value + except AttributeError: + result = attr + try: + enum_obj(result) + return result + except ValueError: + for enum_value in enum_obj: + if enum_value.value.lower() == str(attr).lower(): + return enum_value.value + error = "{!r} is not valid value for enum {!r}" + raise SerializationError(error.format(attr, enum_obj)) + + @staticmethod + def serialize_bytearray(attr, **kwargs): + """Serialize bytearray into base-64 string. + + :param attr: Object to be serialized. + :rtype: str + """ + return b64encode(attr).decode() + + @staticmethod + def serialize_base64(attr, **kwargs): + """Serialize str into base-64 string. + + :param attr: Object to be serialized. + :rtype: str + """ + encoded = b64encode(attr).decode("ascii") + return encoded.strip("=").replace("+", "-").replace("/", "_") + + @staticmethod + def serialize_decimal(attr, **kwargs): + """Serialize Decimal object to float. + + :param attr: Object to be serialized. + :rtype: float + """ + return float(attr) + + @staticmethod + def serialize_long(attr, **kwargs): + """Serialize long (Py2) or int (Py3). + + :param attr: Object to be serialized. + :rtype: int/long + """ + return _long_type(attr) + + @staticmethod + def serialize_date(attr, **kwargs): + """Serialize Date object into ISO-8601 formatted string. + + :param Date attr: Object to be serialized. + :rtype: str + """ + if isinstance(attr, str): + attr = isodate.parse_date(attr) + t = "{:04}-{:02}-{:02}".format(attr.year, attr.month, attr.day) + return t + + @staticmethod + def serialize_time(attr, **kwargs): + """Serialize Time object into ISO-8601 formatted string. + + :param datetime.time attr: Object to be serialized. + :rtype: str + """ + if isinstance(attr, str): + attr = isodate.parse_time(attr) + t = "{:02}:{:02}:{:02}".format(attr.hour, attr.minute, attr.second) + if attr.microsecond: + t += ".{:02}".format(attr.microsecond) + return t + + @staticmethod + def serialize_duration(attr, **kwargs): + """Serialize TimeDelta object into ISO-8601 formatted string. + + :param TimeDelta attr: Object to be serialized. + :rtype: str + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + return isodate.duration_isoformat(attr) + + @staticmethod + def serialize_rfc(attr, **kwargs): + """Serialize Datetime object into RFC-1123 formatted string. + + :param Datetime attr: Object to be serialized. + :rtype: str + :raises: TypeError if format invalid. + """ + try: + if not attr.tzinfo: + _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") + utc = attr.utctimetuple() + except AttributeError: + raise TypeError("RFC1123 object must be valid Datetime object.") + + return "{}, {:02} {} {:04} {:02}:{:02}:{:02} GMT".format( + Serializer.days[utc.tm_wday], + utc.tm_mday, + Serializer.months[utc.tm_mon], + utc.tm_year, + utc.tm_hour, + utc.tm_min, + utc.tm_sec, + ) + + @staticmethod + def serialize_iso(attr, **kwargs): + """Serialize Datetime object into ISO-8601 formatted string. + + :param Datetime attr: Object to be serialized. + :rtype: str + :raises: SerializationError if format invalid. + """ + if isinstance(attr, str): + attr = isodate.parse_datetime(attr) + try: + if not attr.tzinfo: + _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") + utc = attr.utctimetuple() + if utc.tm_year > 9999 or utc.tm_year < 1: + raise OverflowError("Hit max or min date") + + microseconds = str(attr.microsecond).rjust(6, "0").rstrip("0").ljust(3, "0") + if microseconds: + microseconds = "." + microseconds + date = "{:04}-{:02}-{:02}T{:02}:{:02}:{:02}".format( + utc.tm_year, utc.tm_mon, utc.tm_mday, utc.tm_hour, utc.tm_min, utc.tm_sec + ) + return date + microseconds + "Z" + except (ValueError, OverflowError) as err: + msg = "Unable to serialize datetime object." + raise_with_traceback(SerializationError, msg, err) + except AttributeError as err: + msg = "ISO-8601 object must be valid Datetime object." + raise_with_traceback(TypeError, msg, err) + + @staticmethod + def serialize_unix(attr, **kwargs): + """Serialize Datetime object into IntTime format. + This is represented as seconds. + + :param Datetime attr: Object to be serialized. + :rtype: int + :raises: SerializationError if format invalid + """ + if isinstance(attr, int): + return attr + try: + if not attr.tzinfo: + _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") + return int(calendar.timegm(attr.utctimetuple())) + except AttributeError: + raise TypeError("Unix time object must be valid Datetime object.") + + +def rest_key_extractor(attr, attr_desc, data): + key = attr_desc["key"] + working_data = data + + while "." in key: + dict_keys = _FLATTEN.split(key) + if len(dict_keys) == 1: + key = _decode_attribute_map_key(dict_keys[0]) + break + working_key = _decode_attribute_map_key(dict_keys[0]) + working_data = working_data.get(working_key, data) + if working_data is None: + # If at any point while following flatten JSON path see None, it means + # that all properties under are None as well + # https://github.com/Azure/msrest-for-python/issues/197 + return None + key = ".".join(dict_keys[1:]) + + return working_data.get(key) + + +def rest_key_case_insensitive_extractor(attr, attr_desc, data): + key = attr_desc["key"] + working_data = data + + while "." in key: + dict_keys = _FLATTEN.split(key) + if len(dict_keys) == 1: + key = _decode_attribute_map_key(dict_keys[0]) + break + working_key = _decode_attribute_map_key(dict_keys[0]) + working_data = attribute_key_case_insensitive_extractor(working_key, None, working_data) + if working_data is None: + # If at any point while following flatten JSON path see None, it means + # that all properties under are None as well + # https://github.com/Azure/msrest-for-python/issues/197 + return None + key = ".".join(dict_keys[1:]) + + if working_data: + return attribute_key_case_insensitive_extractor(key, None, working_data) + + +def last_rest_key_extractor(attr, attr_desc, data): + """Extract the attribute in "data" based on the last part of the JSON path key.""" + key = attr_desc["key"] + dict_keys = _FLATTEN.split(key) + return attribute_key_extractor(dict_keys[-1], None, data) + + +def last_rest_key_case_insensitive_extractor(attr, attr_desc, data): + """Extract the attribute in "data" based on the last part of the JSON path key. + + This is the case insensitive version of "last_rest_key_extractor" + """ + key = attr_desc["key"] + dict_keys = _FLATTEN.split(key) + return attribute_key_case_insensitive_extractor(dict_keys[-1], None, data) + + +def attribute_key_extractor(attr, _, data): + return data.get(attr) + + +def attribute_key_case_insensitive_extractor(attr, _, data): + found_key = None + lower_attr = attr.lower() + for key in data: + if lower_attr == key.lower(): + found_key = key + break + + return data.get(found_key) + + +def _extract_name_from_internal_type(internal_type): + """Given an internal type XML description, extract correct XML name with namespace. + + :param dict internal_type: An model type + :rtype: tuple + :returns: A tuple XML name + namespace dict + """ + internal_type_xml_map = getattr(internal_type, "_xml_map", {}) + xml_name = internal_type_xml_map.get("name", internal_type.__name__) + xml_ns = internal_type_xml_map.get("ns", None) + if xml_ns: + xml_name = "{}{}".format(xml_ns, xml_name) + return xml_name + + +def xml_key_extractor(attr, attr_desc, data): + if isinstance(data, dict): + return None + + # Test if this model is XML ready first + if not isinstance(data, ET.Element): + return None + + xml_desc = attr_desc.get("xml", {}) + xml_name = xml_desc.get("name", attr_desc["key"]) + + # Look for a children + is_iter_type = attr_desc["type"].startswith("[") + is_wrapped = xml_desc.get("wrapped", False) + internal_type = attr_desc.get("internalType", None) + internal_type_xml_map = getattr(internal_type, "_xml_map", {}) + + # Integrate namespace if necessary + xml_ns = xml_desc.get("ns", internal_type_xml_map.get("ns", None)) + if xml_ns: + xml_name = "{}{}".format(xml_ns, xml_name) + + # If it's an attribute, that's simple + if xml_desc.get("attr", False): + return data.get(xml_name) + + # If it's x-ms-text, that's simple too + if xml_desc.get("text", False): + return data.text + + # Scenario where I take the local name: + # - Wrapped node + # - Internal type is an enum (considered basic types) + # - Internal type has no XML/Name node + if is_wrapped or (internal_type and (issubclass(internal_type, Enum) or "name" not in internal_type_xml_map)): + children = data.findall(xml_name) + # If internal type has a local name and it's not a list, I use that name + elif not is_iter_type and internal_type and "name" in internal_type_xml_map: + xml_name = _extract_name_from_internal_type(internal_type) + children = data.findall(xml_name) + # That's an array + else: + if internal_type: # Complex type, ignore itemsName and use the complex type name + items_name = _extract_name_from_internal_type(internal_type) + else: + items_name = xml_desc.get("itemsName", xml_name) + children = data.findall(items_name) + + if len(children) == 0: + if is_iter_type: + if is_wrapped: + return None # is_wrapped no node, we want None + else: + return [] # not wrapped, assume empty list + return None # Assume it's not there, maybe an optional node. + + # If is_iter_type and not wrapped, return all found children + if is_iter_type: + if not is_wrapped: + return children + else: # Iter and wrapped, should have found one node only (the wrap one) + if len(children) != 1: + raise DeserializationError( + "Tried to deserialize an array not wrapped, and found several nodes '{}'. Maybe you should declare this array as wrapped?".format( + xml_name + ) + ) + return list(children[0]) # Might be empty list and that's ok. + + # Here it's not a itertype, we should have found one element only or empty + if len(children) > 1: + raise DeserializationError("Find several XML '{}' where it was not expected".format(xml_name)) + return children[0] + + +class Deserializer(object): + """Response object model deserializer. + + :param dict classes: Class type dictionary for deserializing complex types. + :ivar list key_extractors: Ordered list of extractors to be used by this deserializer. + """ + + basic_types = {str: "str", int: "int", bool: "bool", float: "float"} + + valid_date = re.compile(r"\d{4}[-]\d{2}[-]\d{2}T\d{2}:\d{2}:\d{2}" r"\.?\d*Z?[-+]?[\d{2}]?:?[\d{2}]?") + + def __init__(self, classes=None): + self.deserialize_type = { + "iso-8601": Deserializer.deserialize_iso, + "rfc-1123": Deserializer.deserialize_rfc, + "unix-time": Deserializer.deserialize_unix, + "duration": Deserializer.deserialize_duration, + "date": Deserializer.deserialize_date, + "time": Deserializer.deserialize_time, + "decimal": Deserializer.deserialize_decimal, + "long": Deserializer.deserialize_long, + "bytearray": Deserializer.deserialize_bytearray, + "base64": Deserializer.deserialize_base64, + "object": self.deserialize_object, + "[]": self.deserialize_iter, + "{}": self.deserialize_dict, + } + self.deserialize_expected_types = { + "duration": (isodate.Duration, datetime.timedelta), + "iso-8601": (datetime.datetime), + } + self.dependencies = dict(classes) if classes else {} + self.key_extractors = [rest_key_extractor, xml_key_extractor] + # Additional properties only works if the "rest_key_extractor" is used to + # extract the keys. Making it to work whatever the key extractor is too much + # complicated, with no real scenario for now. + # So adding a flag to disable additional properties detection. This flag should be + # used if your expect the deserialization to NOT come from a JSON REST syntax. + # Otherwise, result are unexpected + self.additional_properties_detection = True + + def __call__(self, target_obj, response_data, content_type=None): + """Call the deserializer to process a REST response. + + :param str target_obj: Target data type to deserialize to. + :param requests.Response response_data: REST response object. + :param str content_type: Swagger "produces" if available. + :raises: DeserializationError if deserialization fails. + :return: Deserialized object. + """ + data = self._unpack_content(response_data, content_type) + return self._deserialize(target_obj, data) + + def _deserialize(self, target_obj, data): + """Call the deserializer on a model. + + Data needs to be already deserialized as JSON or XML ElementTree + + :param str target_obj: Target data type to deserialize to. + :param object data: Object to deserialize. + :raises: DeserializationError if deserialization fails. + :return: Deserialized object. + """ + # This is already a model, go recursive just in case + if hasattr(data, "_attribute_map"): + constants = [name for name, config in getattr(data, "_validation", {}).items() if config.get("constant")] + try: + for attr, mapconfig in data._attribute_map.items(): + if attr in constants: + continue + value = getattr(data, attr) + if value is None: + continue + local_type = mapconfig["type"] + internal_data_type = local_type.strip("[]{}") + if internal_data_type not in self.dependencies or isinstance(internal_data_type, Enum): + continue + setattr(data, attr, self._deserialize(local_type, value)) + return data + except AttributeError: + return + + response, class_name = self._classify_target(target_obj, data) + + if isinstance(response, basestring): + return self.deserialize_data(data, response) + elif isinstance(response, type) and issubclass(response, Enum): + return self.deserialize_enum(data, response) + + if data is None: + return data + try: + attributes = response._attribute_map + d_attrs = {} + for attr, attr_desc in attributes.items(): + # Check empty string. If it's not empty, someone has a real "additionalProperties"... + if attr == "additional_properties" and attr_desc["key"] == "": + continue + raw_value = None + # Enhance attr_desc with some dynamic data + attr_desc = attr_desc.copy() # Do a copy, do not change the real one + internal_data_type = attr_desc["type"].strip("[]{}") + if internal_data_type in self.dependencies: + attr_desc["internalType"] = self.dependencies[internal_data_type] + + for key_extractor in self.key_extractors: + found_value = key_extractor(attr, attr_desc, data) + if found_value is not None: + if raw_value is not None and raw_value != found_value: + msg = ( + "Ignoring extracted value '%s' from %s for key '%s'" + " (duplicate extraction, follow extractors order)" + ) + _LOGGER.warning(msg, found_value, key_extractor, attr) + continue + raw_value = found_value + + value = self.deserialize_data(raw_value, attr_desc["type"]) + d_attrs[attr] = value + except (AttributeError, TypeError, KeyError) as err: + msg = "Unable to deserialize to object: " + class_name + raise_with_traceback(DeserializationError, msg, err) + else: + additional_properties = self._build_additional_properties(attributes, data) + return self._instantiate_model(response, d_attrs, additional_properties) + + def _build_additional_properties(self, attribute_map, data): + if not self.additional_properties_detection: + return None + if "additional_properties" in attribute_map and attribute_map.get("additional_properties", {}).get("key") != "": + # Check empty string. If it's not empty, someone has a real "additionalProperties" + return None + if isinstance(data, ET.Element): + data = {el.tag: el.text for el in data} + + known_keys = { + _decode_attribute_map_key(_FLATTEN.split(desc["key"])[0]) + for desc in attribute_map.values() + if desc["key"] != "" + } + present_keys = set(data.keys()) + missing_keys = present_keys - known_keys + return {key: data[key] for key in missing_keys} + + def _classify_target(self, target, data): + """Check to see whether the deserialization target object can + be classified into a subclass. + Once classification has been determined, initialize object. + + :param str target: The target object type to deserialize to. + :param str/dict data: The response data to deseralize. + """ + if target is None: + return None, None + + if isinstance(target, basestring): + try: + target = self.dependencies[target] + except KeyError: + return target, target + + try: + target = target._classify(data, self.dependencies) + except AttributeError: + pass # Target is not a Model, no classify + return target, target.__class__.__name__ + + def failsafe_deserialize(self, target_obj, data, content_type=None): + """Ignores any errors encountered in deserialization, + and falls back to not deserializing the object. Recommended + for use in error deserialization, as we want to return the + HttpResponseError to users, and not have them deal with + a deserialization error. + + :param str target_obj: The target object type to deserialize to. + :param str/dict data: The response data to deseralize. + :param str content_type: Swagger "produces" if available. + """ + try: + return self(target_obj, data, content_type=content_type) + except: + _LOGGER.debug( + "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True + ) + return None + + @staticmethod + def _unpack_content(raw_data, content_type=None): + """Extract the correct structure for deserialization. + + If raw_data is a PipelineResponse, try to extract the result of RawDeserializer. + if we can't, raise. Your Pipeline should have a RawDeserializer. + + If not a pipeline response and raw_data is bytes or string, use content-type + to decode it. If no content-type, try JSON. + + If raw_data is something else, bypass all logic and return it directly. + + :param raw_data: Data to be processed. + :param content_type: How to parse if raw_data is a string/bytes. + :raises JSONDecodeError: If JSON is requested and parsing is impossible. + :raises UnicodeDecodeError: If bytes is not UTF8 + """ + # Assume this is enough to detect a Pipeline Response without importing it + context = getattr(raw_data, "context", {}) + if context: + if RawDeserializer.CONTEXT_NAME in context: + return context[RawDeserializer.CONTEXT_NAME] + raise ValueError("This pipeline didn't have the RawDeserializer policy; can't deserialize") + + # Assume this is enough to recognize universal_http.ClientResponse without importing it + if hasattr(raw_data, "body"): + return RawDeserializer.deserialize_from_http_generics(raw_data.text(), raw_data.headers) + + # Assume this enough to recognize requests.Response without importing it. + if hasattr(raw_data, "_content_consumed"): + return RawDeserializer.deserialize_from_http_generics(raw_data.text, raw_data.headers) + + if isinstance(raw_data, (basestring, bytes)) or hasattr(raw_data, "read"): + return RawDeserializer.deserialize_from_text(raw_data, content_type) + return raw_data + + def _instantiate_model(self, response, attrs, additional_properties=None): + """Instantiate a response model passing in deserialized args. + + :param response: The response model class. + :param d_attrs: The deserialized response attributes. + """ + if callable(response): + subtype = getattr(response, "_subtype_map", {}) + try: + readonly = [k for k, v in response._validation.items() if v.get("readonly")] + const = [k for k, v in response._validation.items() if v.get("constant")] + kwargs = {k: v for k, v in attrs.items() if k not in subtype and k not in readonly + const} + response_obj = response(**kwargs) + for attr in readonly: + setattr(response_obj, attr, attrs.get(attr)) + if additional_properties: + response_obj.additional_properties = additional_properties + return response_obj + except TypeError as err: + msg = "Unable to deserialize {} into model {}. ".format(kwargs, response) + raise DeserializationError(msg + str(err)) + else: + try: + for attr, value in attrs.items(): + setattr(response, attr, value) + return response + except Exception as exp: + msg = "Unable to populate response model. " + msg += "Type: {}, Error: {}".format(type(response), exp) + raise DeserializationError(msg) + + def deserialize_data(self, data, data_type): + """Process data for deserialization according to data type. + + :param str data: The response string to be deserialized. + :param str data_type: The type to deserialize to. + :raises: DeserializationError if deserialization fails. + :return: Deserialized object. + """ + if data is None: + return data + + try: + if not data_type: + return data + if data_type in self.basic_types.values(): + return self.deserialize_basic(data, data_type) + if data_type in self.deserialize_type: + if isinstance(data, self.deserialize_expected_types.get(data_type, tuple())): + return data + + is_a_text_parsing_type = lambda x: x not in ["object", "[]", r"{}"] + if isinstance(data, ET.Element) and is_a_text_parsing_type(data_type) and not data.text: + return None + data_val = self.deserialize_type[data_type](data) + return data_val + + iter_type = data_type[0] + data_type[-1] + if iter_type in self.deserialize_type: + return self.deserialize_type[iter_type](data, data_type[1:-1]) + + obj_type = self.dependencies[data_type] + if issubclass(obj_type, Enum): + if isinstance(data, ET.Element): + data = data.text + return self.deserialize_enum(data, obj_type) + + except (ValueError, TypeError, AttributeError) as err: + msg = "Unable to deserialize response data." + msg += " Data: {}, {}".format(data, data_type) + raise_with_traceback(DeserializationError, msg, err) + else: + return self._deserialize(obj_type, data) + + def deserialize_iter(self, attr, iter_type): + """Deserialize an iterable. + + :param list attr: Iterable to be deserialized. + :param str iter_type: The type of object in the iterable. + :rtype: list + """ + if attr is None: + return None + if isinstance(attr, ET.Element): # If I receive an element here, get the children + attr = list(attr) + if not isinstance(attr, (list, set)): + raise DeserializationError("Cannot deserialize as [{}] an object of type {}".format(iter_type, type(attr))) + return [self.deserialize_data(a, iter_type) for a in attr] + + def deserialize_dict(self, attr, dict_type): + """Deserialize a dictionary. + + :param dict/list attr: Dictionary to be deserialized. Also accepts + a list of key, value pairs. + :param str dict_type: The object type of the items in the dictionary. + :rtype: dict + """ + if isinstance(attr, list): + return {x["key"]: self.deserialize_data(x["value"], dict_type) for x in attr} + + if isinstance(attr, ET.Element): + # Transform value into {"Key": "value"} + attr = {el.tag: el.text for el in attr} + return {k: self.deserialize_data(v, dict_type) for k, v in attr.items()} + + def deserialize_object(self, attr, **kwargs): + """Deserialize a generic object. + This will be handled as a dictionary. + + :param dict attr: Dictionary to be deserialized. + :rtype: dict + :raises: TypeError if non-builtin datatype encountered. + """ + if attr is None: + return None + if isinstance(attr, ET.Element): + # Do no recurse on XML, just return the tree as-is + return attr + if isinstance(attr, basestring): + return self.deserialize_basic(attr, "str") + obj_type = type(attr) + if obj_type in self.basic_types: + return self.deserialize_basic(attr, self.basic_types[obj_type]) + if obj_type is _long_type: + return self.deserialize_long(attr) + + if obj_type == dict: + deserialized = {} + for key, value in attr.items(): + try: + deserialized[key] = self.deserialize_object(value, **kwargs) + except ValueError: + deserialized[key] = None + return deserialized + + if obj_type == list: + deserialized = [] + for obj in attr: + try: + deserialized.append(self.deserialize_object(obj, **kwargs)) + except ValueError: + pass + return deserialized + + else: + error = "Cannot deserialize generic object with type: " + raise TypeError(error + str(obj_type)) + + def deserialize_basic(self, attr, data_type): + """Deserialize basic builtin data type from string. + Will attempt to convert to str, int, float and bool. + This function will also accept '1', '0', 'true' and 'false' as + valid bool values. + + :param str attr: response string to be deserialized. + :param str data_type: deserialization data type. + :rtype: str, int, float or bool + :raises: TypeError if string format is not valid. + """ + # If we're here, data is supposed to be a basic type. + # If it's still an XML node, take the text + if isinstance(attr, ET.Element): + attr = attr.text + if not attr: + if data_type == "str": + # None or '', node is empty string. + return "" + else: + # None or '', node with a strong type is None. + # Don't try to model "empty bool" or "empty int" + return None + + if data_type == "bool": + if attr in [True, False, 1, 0]: + return bool(attr) + elif isinstance(attr, basestring): + if attr.lower() in ["true", "1"]: + return True + elif attr.lower() in ["false", "0"]: + return False + raise TypeError("Invalid boolean value: {}".format(attr)) + + if data_type == "str": + return self.deserialize_unicode(attr) + return eval(data_type)(attr) # nosec + + @staticmethod + def deserialize_unicode(data): + """Preserve unicode objects in Python 2, otherwise return data + as a string. + + :param str data: response string to be deserialized. + :rtype: str or unicode + """ + # We might be here because we have an enum modeled as string, + # and we try to deserialize a partial dict with enum inside + if isinstance(data, Enum): + return data + + # Consider this is real string + try: + if isinstance(data, unicode): + return data + except NameError: + return str(data) + else: + return str(data) + + @staticmethod + def deserialize_enum(data, enum_obj): + """Deserialize string into enum object. + + If the string is not a valid enum value it will be returned as-is + and a warning will be logged. + + :param str data: Response string to be deserialized. If this value is + None or invalid it will be returned as-is. + :param Enum enum_obj: Enum object to deserialize to. + :rtype: Enum + """ + if isinstance(data, enum_obj) or data is None: + return data + if isinstance(data, Enum): + data = data.value + if isinstance(data, int): + # Workaround. We might consider remove it in the future. + # https://github.com/Azure/azure-rest-api-specs/issues/141 + try: + return list(enum_obj.__members__.values())[data] + except IndexError: + error = "{!r} is not a valid index for enum {!r}" + raise DeserializationError(error.format(data, enum_obj)) + try: + return enum_obj(str(data)) + except ValueError: + for enum_value in enum_obj: + if enum_value.value.lower() == str(data).lower(): + return enum_value + # We don't fail anymore for unknown value, we deserialize as a string + _LOGGER.warning("Deserializer is not able to find %s as valid enum in %s", data, enum_obj) + return Deserializer.deserialize_unicode(data) + + @staticmethod + def deserialize_bytearray(attr): + """Deserialize string into bytearray. + + :param str attr: response string to be deserialized. + :rtype: bytearray + :raises: TypeError if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + return bytearray(b64decode(attr)) + + @staticmethod + def deserialize_base64(attr): + """Deserialize base64 encoded string into string. + + :param str attr: response string to be deserialized. + :rtype: bytearray + :raises: TypeError if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + padding = "=" * (3 - (len(attr) + 3) % 4) + attr = attr + padding + encoded = attr.replace("-", "+").replace("_", "/") + return b64decode(encoded) + + @staticmethod + def deserialize_decimal(attr): + """Deserialize string into Decimal object. + + :param str attr: response string to be deserialized. + :rtype: Decimal + :raises: DeserializationError if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + return decimal.Decimal(attr) + except decimal.DecimalException as err: + msg = "Invalid decimal {}".format(attr) + raise_with_traceback(DeserializationError, msg, err) + + @staticmethod + def deserialize_long(attr): + """Deserialize string into long (Py2) or int (Py3). + + :param str attr: response string to be deserialized. + :rtype: long or int + :raises: ValueError if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + return _long_type(attr) + + @staticmethod + def deserialize_duration(attr): + """Deserialize ISO-8601 formatted string into TimeDelta object. + + :param str attr: response string to be deserialized. + :rtype: TimeDelta + :raises: DeserializationError if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = isodate.parse_duration(attr) + except (ValueError, OverflowError, AttributeError) as err: + msg = "Cannot deserialize duration object." + raise_with_traceback(DeserializationError, msg, err) + else: + return duration + + @staticmethod + def deserialize_date(attr): + """Deserialize ISO-8601 formatted string into Date object. + + :param str attr: response string to be deserialized. + :rtype: Date + :raises: DeserializationError if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + if re.search(r"[^\W\d_]", attr, re.I + re.U): + raise DeserializationError("Date must have only digits and -. Received: %s" % attr) + # This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception. + return isodate.parse_date(attr, defaultmonth=None, defaultday=None) + + @staticmethod + def deserialize_time(attr): + """Deserialize ISO-8601 formatted string into time object. + + :param str attr: response string to be deserialized. + :rtype: datetime.time + :raises: DeserializationError if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + if re.search(r"[^\W\d_]", attr, re.I + re.U): + raise DeserializationError("Date must have only digits and -. Received: %s" % attr) + return isodate.parse_time(attr) + + @staticmethod + def deserialize_rfc(attr): + """Deserialize RFC-1123 formatted string into Datetime object. + + :param str attr: response string to be deserialized. + :rtype: Datetime + :raises: DeserializationError if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + parsed_date = email.utils.parsedate_tz(attr) + date_obj = datetime.datetime( + *parsed_date[:6], tzinfo=_FixedOffset(datetime.timedelta(minutes=(parsed_date[9] or 0) / 60)) + ) + if not date_obj.tzinfo: + date_obj = date_obj.astimezone(tz=TZ_UTC) + except ValueError as err: + msg = "Cannot deserialize to rfc datetime object." + raise_with_traceback(DeserializationError, msg, err) + else: + return date_obj + + @staticmethod + def deserialize_iso(attr): + """Deserialize ISO-8601 formatted string into Datetime object. + + :param str attr: response string to be deserialized. + :rtype: Datetime + :raises: DeserializationError if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + attr = attr.upper() + match = Deserializer.valid_date.match(attr) + if not match: + raise ValueError("Invalid datetime string: " + attr) + + check_decimal = attr.split(".") + if len(check_decimal) > 1: + decimal_str = "" + for digit in check_decimal[1]: + if digit.isdigit(): + decimal_str += digit + else: + break + if len(decimal_str) > 6: + attr = attr.replace(decimal_str, decimal_str[0:6]) + + date_obj = isodate.parse_datetime(attr) + test_utc = date_obj.utctimetuple() + if test_utc.tm_year > 9999 or test_utc.tm_year < 1: + raise OverflowError("Hit max or min date") + except (ValueError, OverflowError, AttributeError) as err: + msg = "Cannot deserialize datetime object." + raise_with_traceback(DeserializationError, msg, err) + else: + return date_obj + + @staticmethod + def deserialize_unix(attr): + """Serialize Datetime object into IntTime format. + This is represented as seconds. + + :param int attr: Object to be serialized. + :rtype: Datetime + :raises: DeserializationError if format invalid + """ + if isinstance(attr, ET.Element): + attr = int(attr.text) + try: + date_obj = datetime.datetime.fromtimestamp(attr, TZ_UTC) + except ValueError as err: + msg = "Cannot deserialize to unix datetime object." + raise_with_traceback(DeserializationError, msg, err) + else: + return date_obj diff --git a/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/_vendor.py b/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/_vendor.py index 138f663c53a4..9aad73fc743e 100644 --- a/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/_vendor.py +++ b/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/_vendor.py @@ -7,6 +7,7 @@ from azure.core.pipeline.transport import HttpRequest + def _convert_request(request, files=None): data = request.content if not files else None request = HttpRequest(method=request.method, url=request.url, headers=request.headers, data=data) @@ -14,6 +15,7 @@ def _convert_request(request, files=None): request.set_formdata_body(files) return request + def _format_url_section(template, **kwargs): components = template.split("/") while components: @@ -21,7 +23,5 @@ def _format_url_section(template, **kwargs): return template.format(**kwargs) except KeyError as key: formatted_components = template.split("/") - components = [ - c for c in formatted_components if "{}".format(key.args[0]) not in c - ] + components = [c for c in formatted_components if "{}".format(key.args[0]) not in c] template = "/".join(components) diff --git a/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/_version.py b/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/_version.py index 2ac18d10425f..c23f64adb662 100644 --- a/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/_version.py +++ b/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/_version.py @@ -6,4 +6,4 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -VERSION = "16.2.0" +VERSION = "14.0.0b1" diff --git a/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/aio/__init__.py b/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/aio/__init__.py index 5220f1b3d0f1..cd7e0aa0cf4e 100644 --- a/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/aio/__init__.py +++ b/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/aio/__init__.py @@ -7,9 +7,17 @@ # -------------------------------------------------------------------------- from ._batch_management_client import BatchManagementClient -__all__ = ['BatchManagementClient'] -# `._patch.py` is used for handwritten extensions to the generated code -# Example: https://github.com/Azure/azure-sdk-for-python/blob/main/doc/dev/customize_code/how-to-patch-sdk-code.md -from ._patch import patch_sdk -patch_sdk() +try: + from ._patch import __all__ as _patch_all + from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import +except ImportError: + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "BatchManagementClient", +] +__all__.extend([p for p in _patch_all if p not in __all__]) + +_patch_sdk() diff --git a/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/aio/_batch_management_client.py b/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/aio/_batch_management_client.py index 76d10a467aea..c35cc68b6068 100644 --- a/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/aio/_batch_management_client.py +++ b/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/aio/_batch_management_client.py @@ -9,20 +9,30 @@ from copy import deepcopy from typing import Any, Awaitable, TYPE_CHECKING -from msrest import Deserializer, Serializer - from azure.core.rest import AsyncHttpResponse, HttpRequest from azure.mgmt.core import AsyncARMPipelineClient from .. import models +from .._serialization import Deserializer, Serializer from ._configuration import BatchManagementClientConfiguration -from .operations import ApplicationOperations, ApplicationPackageOperations, BatchAccountOperations, CertificateOperations, LocationOperations, Operations, PoolOperations, PrivateEndpointConnectionOperations, PrivateLinkResourceOperations +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=too-many-instance-attributes + +class BatchManagementClient: # pylint: disable=client-accepts-api-version-keyword,too-many-instance-attributes """Batch Client. :ivar batch_account: BatchAccountOperations operations @@ -44,14 +54,14 @@ class BatchManagementClient: # pylint: disable=too-many-instance-attributes 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. + :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). + 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 "2022-06-01". Note that overriding this + :keyword api_version: Api Version. Default value is "2022-10-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 @@ -65,7 +75,9 @@ def __init__( base_url: str = "https://management.azure.com", **kwargs: Any ) -> None: - self._config = BatchManagementClientConfiguration(credential=credential, subscription_id=subscription_id, **kwargs) + self._config = BatchManagementClientConfiguration( + 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)} @@ -73,21 +85,22 @@ def __init__( 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_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.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]: + 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 @@ -96,7 +109,7 @@ def _send_request( >>> response = await client._send_request(request) - For more information on this code flow, see https://aka.ms/azsdk/python/protocol/quickstart + 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 diff --git a/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/aio/_configuration.py b/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/aio/_configuration.py index d33e34cbe6be..1fee99a327ec 100644 --- a/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/aio/_configuration.py +++ b/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/aio/_configuration.py @@ -6,6 +6,7 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +import sys from typing import Any, TYPE_CHECKING from azure.core.configuration import Configuration @@ -14,6 +15,11 @@ from .._version import VERSION +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 azure.core.credentials_async import AsyncTokenCredential @@ -25,24 +31,19 @@ class BatchManagementClientConfiguration(Configuration): # pylint: disable=too- 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. + :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). + 00000000-0000-0000-0000-000000000000). Required. :type subscription_id: str - :keyword api_version: Api Version. Default value is "2022-06-01". Note that overriding this + :keyword api_version: Api Version. Default value is "2022-10-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: + def __init__(self, credential: "AsyncTokenCredential", subscription_id: str, **kwargs: Any) -> None: super(BatchManagementClientConfiguration, self).__init__(**kwargs) - api_version = kwargs.pop('api_version', "2022-06-01") # type: str + api_version = kwargs.pop("api_version", "2022-10-01") # type: Literal["2022-10-01"] if credential is None: raise ValueError("Parameter 'credential' must not be None.") @@ -52,22 +53,21 @@ def __init__( 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.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') + 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) + self.authentication_policy = AsyncARMChallengeAuthenticationPolicy( + self.credential, *self.credential_scopes, **kwargs + ) diff --git a/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/aio/_patch.py b/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/aio/_patch.py index 74e48ecd07cf..f99e77fef986 100644 --- a/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/aio/_patch.py +++ b/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/aio/_patch.py @@ -28,4 +28,4 @@ # This file is used for handwritten extensions to the generated code. Example: # https://github.com/Azure/azure-sdk-for-python/blob/main/doc/dev/customize_code/how-to-patch-sdk-code.md def patch_sdk(): - pass \ No newline at end of file + pass diff --git a/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/aio/operations/__init__.py b/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/aio/operations/__init__.py index c4a185c29107..484efa0258a1 100644 --- a/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/aio/operations/__init__.py +++ b/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/aio/operations/__init__.py @@ -16,14 +16,20 @@ from ._private_endpoint_connection_operations import PrivateEndpointConnectionOperations from ._pool_operations import PoolOperations +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__ = [ - 'BatchAccountOperations', - 'ApplicationPackageOperations', - 'ApplicationOperations', - 'LocationOperations', - 'Operations', - 'CertificateOperations', - 'PrivateLinkResourceOperations', - 'PrivateEndpointConnectionOperations', - 'PoolOperations', + "BatchAccountOperations", + "ApplicationPackageOperations", + "ApplicationOperations", + "LocationOperations", + "Operations", + "CertificateOperations", + "PrivateLinkResourceOperations", + "PrivateEndpointConnectionOperations", + "PoolOperations", ] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/aio/operations/_application_operations.py b/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/aio/operations/_application_operations.py index 69a60adc2147..16ef24cbee36 100644 --- a/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/aio/operations/_application_operations.py +++ b/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/aio/operations/_application_operations.py @@ -6,82 +6,185 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar +import sys +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, map_error +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') +from ...operations._application_operations import ( + build_create_request, + build_delete_request, + build_get_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 ApplicationOperations: - """ApplicationOperations 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. +class ApplicationOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.batch.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. + Instead, you should access the following operations through + :class:`~azure.mgmt.batch.aio.BatchManagementClient`'s + :attr:`application` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + 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 + @overload async def create( self, resource_group_name: str, account_name: str, application_name: str, - parameters: Optional["_models.Application"] = None, + parameters: Optional[_models.Application] = None, + *, + content_type: str = "application/json", **kwargs: Any - ) -> "_models.Application": + ) -> _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. + :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) + :return: Application or the result of cls(response) :rtype: ~azure.mgmt.batch.models.Application - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Application"] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = kwargs.pop('api_version', "2022-06-01") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + @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: + """ - if parameters is not None: - _json = self._serialize.body(parameters, 'Application') + @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 model 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 = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.Application] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters else: - _json = None + if parameters is not None: + _json = self._serialize.body(parameters, "Application") + else: + _json = None request = build_create_request( resource_group_name=resource_group_name, @@ -91,78 +194,85 @@ async def create( api_version=api_version, content_type=content_type, json=_json, - template_url=self.create.metadata['url'], + content=_content, + template_url=self.create.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + 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) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('Application', pipeline_response) + 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}"} # type: ignore - + create.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/applications/{applicationName}"} # type: ignore @distributed_trace_async async def delete( # pylint: disable=inconsistent-return-statements - self, - resource_group_name: str, - account_name: str, - application_name: str, - **kwargs: Any + 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. + :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) + :return: None or the result of cls(response) :rtype: None - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + 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', "2022-06-01") # type: str + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[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'], + template_url=self.delete.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + 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, 204]: @@ -172,70 +282,138 @@ async def delete( # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) - delete.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/applications/{applicationName}"} # type: ignore - + delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/applications/{applicationName}"} # type: ignore @distributed_trace_async async def get( - self, - resource_group_name: str, - account_name: str, - application_name: str, - **kwargs: Any - ) -> "_models.Application": + 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. + :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) + :return: Application or the result of cls(response) :rtype: ~azure.mgmt.batch.models.Application - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Application"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + 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', "2022-06-01") # type: str + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.Application] - 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'], + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + 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) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('Application', pipeline_response) + 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}"} # type: ignore + get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/applications/{applicationName}"} # type: ignore + @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( @@ -243,34 +421,54 @@ async def update( resource_group_name: str, account_name: str, application_name: str, - parameters: "_models.Application", + parameters: Union[_models.Application, IO], **kwargs: Any - ) -> "_models.Application": + ) -> _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. + :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. - :type parameters: ~azure.mgmt.batch.models.Application + :param parameters: The parameters for the request. Is either a model 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) + :return: Application or the result of cls(response) :rtype: ~azure.mgmt.batch.models.Application - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Application"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - - api_version = kwargs.pop('api_version', "2022-06-01") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] - - _json = self._serialize.body(parameters, 'Application') + 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", self._config.api_version) + ) # type: Literal["2022-10-01"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.Application] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "Application") request = build_update_request( resource_group_name=resource_group_name, @@ -280,89 +478,99 @@ async def update( api_version=api_version, content_type=content_type, json=_json, - template_url=self.update.metadata['url'], + content=_content, + template_url=self.update.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + 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) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('Application', pipeline_response) + 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}"} # type: ignore - + update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/applications/{applicationName}"} # type: ignore @distributed_trace def list( - self, - resource_group_name: str, - account_name: str, - maxresults: Optional[int] = None, - **kwargs: Any - ) -> AsyncIterable["_models.ListApplicationsResult"]: + 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. + :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 ListApplicationsResult or the result of - cls(response) - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.batch.models.ListApplicationsResult] - :raises: ~azure.core.exceptions.HttpResponseError + :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: """ - api_version = kwargs.pop('api_version', "2022-06-01") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.ListApplicationsResult] - cls = kwargs.pop('cls', None) # type: ClsType["_models.ListApplicationsResult"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + 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, - api_version=api_version, maxresults=maxresults, - template_url=self.list.metadata['url'], + 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) + request.url = self._client.format_url(request.url) # type: ignore else: - - request = build_list_request( - resource_group_name=resource_group_name, - account_name=account_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - maxresults=maxresults, - template_url=next_link, + # 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.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request @@ -376,10 +584,8 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -389,8 +595,6 @@ async def get_next(next_link=None): return pipeline_response + return AsyncItemPaged(get_next, extract_data) - return AsyncItemPaged( - get_next, extract_data - ) - list.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/applications"} # type: ignore + list.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/applications"} # type: ignore diff --git a/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/aio/operations/_application_package_operations.py b/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/aio/operations/_application_package_operations.py index 6d261d671fd4..0c3708764c60 100644 --- a/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/aio/operations/_application_package_operations.py +++ b/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/aio/operations/_application_package_operations.py @@ -6,84 +6,197 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar +import sys +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, map_error +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') +from ...operations._application_package_operations import ( + build_activate_request, + build_create_request, + build_delete_request, + 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 ApplicationPackageOperations: - """ApplicationPackageOperations 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. +class ApplicationPackageOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.batch.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. + Instead, you should access the following operations through + :class:`~azure.mgmt.batch.aio.BatchManagementClient`'s + :attr:`application_package` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + 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 + @overload async def activate( self, resource_group_name: str, account_name: str, application_name: str, version_name: str, - parameters: "_models.ActivateApplicationPackageParameters", + parameters: _models.ActivateApplicationPackageParameters, + *, + content_type: str = "application/json", **kwargs: Any - ) -> "_models.ApplicationPackage": + ) -> _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. + :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. + :param version_name: The version of the application. Required. :type version_name: str - :param parameters: The parameters for the request. + :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) + :return: ApplicationPackage or the result of cls(response) :rtype: ~azure.mgmt.batch.models.ApplicationPackage - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.ApplicationPackage"] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = kwargs.pop('api_version', "2022-06-01") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + @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. - _json = self._serialize.body(parameters, 'ActivateApplicationPackageParameters') + :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 model 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 = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.ApplicationPackage] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "ActivateApplicationPackageParameters") request = build_activate_request( resource_group_name=resource_group_name, @@ -94,75 +207,172 @@ async def activate( api_version=api_version, content_type=content_type, json=_json, - template_url=self.activate.metadata['url'], + content=_content, + template_url=self.activate.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + 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) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('ApplicationPackage', pipeline_response) + 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"} # type: ignore + activate.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/applications/{applicationName}/versions/{versionName}/activate"} # type: ignore - - @distributed_trace_async + @overload async def create( self, resource_group_name: str, account_name: str, application_name: str, version_name: str, - parameters: Optional["_models.ApplicationPackage"] = None, + parameters: Optional[_models.ApplicationPackage] = None, + *, + content_type: str = "application/json", **kwargs: Any - ) -> "_models.ApplicationPackage": + ) -> _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. + :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. + :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) + :return: ApplicationPackage or the result of cls(response) :rtype: ~azure.mgmt.batch.models.ApplicationPackage - :raises: ~azure.core.exceptions.HttpResponseError + :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: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.ApplicationPackage"] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = kwargs.pop('api_version', "2022-06-01") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + @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. - if parameters is not None: - _json = self._serialize.body(parameters, 'ApplicationPackage') + :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 model 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 = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.ApplicationPackage] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters else: - _json = None + if parameters is not None: + _json = self._serialize.body(parameters, "ApplicationPackage") + else: + _json = None request = build_create_request( resource_group_name=resource_group_name, @@ -173,65 +383,70 @@ async def create( api_version=api_version, content_type=content_type, json=_json, - template_url=self.create.metadata['url'], + content=_content, + template_url=self.create.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + 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) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('ApplicationPackage', pipeline_response) + 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}"} # type: ignore - + create.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/applications/{applicationName}/versions/{versionName}"} # type: ignore @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 + 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. + :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. + :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) + :return: None or the result of cls(response) :rtype: None - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + 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', "2022-06-01") # type: str + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[None] - request = build_delete_request( resource_group_name=resource_group_name, account_name=account_name, @@ -239,16 +454,17 @@ async def delete( # pylint: disable=inconsistent-return-statements version_name=version_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.delete.metadata['url'], + template_url=self.delete.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + 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, 204]: @@ -258,42 +474,45 @@ async def delete( # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) - delete.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/applications/{applicationName}/versions/{versionName}"} # type: ignore - + delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/applications/{applicationName}/versions/{versionName}"} # type: ignore @distributed_trace_async async def get( - self, - resource_group_name: str, - account_name: str, - application_name: str, - version_name: str, - **kwargs: Any - ) -> "_models.ApplicationPackage": + 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. + :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. + :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) + :return: ApplicationPackage or the result of cls(response) :rtype: ~azure.mgmt.batch.models.ApplicationPackage - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.ApplicationPackage"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) - api_version = kwargs.pop('api_version', "2022-06-01") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.ApplicationPackage] - request = build_get_request( resource_group_name=resource_group_name, account_name=account_name, @@ -301,31 +520,31 @@ async def get( version_name=version_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get.metadata['url'], + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + 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) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('ApplicationPackage', pipeline_response) + 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}"} # type: ignore - + get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/applications/{applicationName}/versions/{versionName}"} # type: ignore @distributed_trace def list( @@ -335,60 +554,73 @@ def list( application_name: str, maxresults: Optional[int] = None, **kwargs: Any - ) -> AsyncIterable["_models.ListApplicationPackagesResult"]: + ) -> 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. + :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 ListApplicationPackagesResult or the result of - cls(response) - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.batch.models.ListApplicationPackagesResult] - :raises: ~azure.core.exceptions.HttpResponseError + :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: """ - api_version = kwargs.pop('api_version', "2022-06-01") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.ListApplicationPackagesResult] - cls = kwargs.pop('cls', None) # type: ClsType["_models.ListApplicationPackagesResult"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + 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, - api_version=api_version, maxresults=maxresults, - template_url=self.list.metadata['url'], + 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) + request.url = self._client.format_url(request.url) # type: ignore else: - - request = build_list_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, - maxresults=maxresults, - template_url=next_link, + # 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.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request @@ -402,10 +634,8 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -415,8 +645,6 @@ async def get_next(next_link=None): return pipeline_response + return AsyncItemPaged(get_next, extract_data) - return AsyncItemPaged( - get_next, extract_data - ) - list.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/applications/{applicationName}/versions"} # type: ignore + list.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/applications/{applicationName}/versions"} # type: ignore diff --git a/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/aio/operations/_batch_account_operations.py b/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/aio/operations/_batch_account_operations.py index 2ab82079ee46..bb20adde4058 100644 --- a/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/aio/operations/_batch_account_operations.py +++ b/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/aio/operations/_batch_account_operations.py @@ -6,82 +6,124 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar, Union +import sys +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, map_error +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_initial, build_delete_request_initial, 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') +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, +) + +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 BatchAccountOperations: - """BatchAccountOperations 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. +class BatchAccountOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.batch.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. + Instead, you should access the following operations through + :class:`~azure.mgmt.batch.aio.BatchManagementClient`'s + :attr:`batch_account` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + 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: "_models.BatchAccountCreateParameters", + parameters: Union[_models.BatchAccountCreateParameters, IO], **kwargs: Any - ) -> Optional["_models.BatchAccount"]: - cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.BatchAccount"]] + ) -> Optional[_models.BatchAccount]: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - - api_version = kwargs.pop('api_version', "2022-06-01") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] - - _json = self._serialize.body(parameters, 'BatchAccountCreateParameters') - - request = build_create_request_initial( + 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", self._config.api_version) + ) # type: Literal["2022-10-01"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.BatchAccount]] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, 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, - template_url=self._create_initial.metadata['url'], + 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) + request.url = self._client.format_url(request.url) # type: ignore - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + 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]: @@ -91,42 +133,127 @@ async def _create_initial( deserialized = None response_headers = {} if response.status_code == 200: - deserialized = self._deserialize('BatchAccount', pipeline_response) + 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')) - + 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}"} # type: ignore + _create_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}"} # type: ignore + + @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: "_models.BatchAccountCreateParameters", + parameters: Union[_models.BatchAccountCreateParameters, IO], **kwargs: Any - ) -> AsyncLROPoller["_models.BatchAccount"]: + ) -> 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/. + http://accountname.region.batch.azure.com/. Required. :type account_name: str - :param parameters: Additional parameters for account creation. - :type parameters: ~azure.mgmt.batch.models.BatchAccountCreateParameters + :param parameters: Additional parameters for account creation. Is either a model 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 @@ -138,82 +265,164 @@ async def begin_create( :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 + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2022-06-01") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] - polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType["_models.BatchAccount"] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + _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", self._config.api_version) + ) # type: Literal["2022-10-01"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.BatchAccount] + 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_initial( + raw_result = await self._create_initial( # type: ignore 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, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - response = pipeline_response.http_response - deserialized = self._deserialize('BatchAccount', pipeline_response) + deserialized = self._deserialize("BatchAccount", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - - if polling is True: polling_method = AsyncARMPolling(lro_delay, lro_options={'final-state-via': 'location'}, **kwargs) - elif polling is False: polling_method = AsyncNoPolling() - else: polling_method = polling + 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 + deserialization_callback=get_long_running_output, ) return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_create.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}"} # type: ignore + begin_create.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}"} # type: ignore - @distributed_trace_async + @overload async def update( self, resource_group_name: str, account_name: str, - parameters: "_models.BatchAccountUpdateParameters", + parameters: _models.BatchAccountUpdateParameters, + *, + content_type: str = "application/json", **kwargs: Any - ) -> "_models.BatchAccount": + ) -> _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. + :param account_name: The name of the Batch account. Required. :type account_name: str - :param parameters: Additional parameters for account update. + :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) + :return: BatchAccount or the result of cls(response) :rtype: ~azure.mgmt.batch.models.BatchAccount - :raises: ~azure.core.exceptions.HttpResponseError + :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 model 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: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.BatchAccount"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) - api_version = kwargs.pop('api_version', "2022-06-01") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - _json = self._serialize.body(parameters, 'BatchAccountUpdateParameters') + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.BatchAccount] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "BatchAccountUpdateParameters") request = build_update_request( resource_group_name=resource_group_name, @@ -222,62 +431,68 @@ async def update( api_version=api_version, content_type=content_type, json=_json, - template_url=self.update.metadata['url'], + content=_content, + template_url=self.update.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + 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) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('BatchAccount', pipeline_response) + 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}"} # type: ignore - + update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}"} # type: ignore async def _delete_initial( # pylint: disable=inconsistent-return-statements - self, - resource_group_name: str, - account_name: str, - **kwargs: Any + self, resource_group_name: str, account_name: str, **kwargs: Any ) -> None: - cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + 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', "2022-06-01") # type: str + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[None] - - request = build_delete_request_initial( + 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'], + template_url=self._delete_initial.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + 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, 204]: @@ -286,28 +501,22 @@ async def _delete_initial( # pylint: disable=inconsistent-return-statements 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')) - + 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}"} # type: ignore - + _delete_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}"} # type: ignore @distributed_trace_async - async def begin_delete( # pylint: disable=inconsistent-return-statements - self, - resource_group_name: str, - account_name: str, - **kwargs: Any - ) -> AsyncLROPoller[None]: + 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. + :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. @@ -319,144 +528,167 @@ async def begin_delete( # pylint: disable=inconsistent-return-statements 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 + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2022-06-01") # type: str - 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] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[None] + 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._delete_initial( + 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, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) - def get_long_running_output(pipeline_response): + 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 = AsyncARMPolling(lro_delay, lro_options={'final-state-via': 'location'}, **kwargs) - elif polling is False: polling_method = AsyncNoPolling() - else: polling_method = polling + 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 + deserialization_callback=get_long_running_output, ) return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_delete.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}"} # type: ignore + begin_delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}"} # type: ignore @distributed_trace_async - async def get( - self, - resource_group_name: str, - account_name: str, - **kwargs: Any - ) -> "_models.BatchAccount": + 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. + :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) + :return: BatchAccount or the result of cls(response) :rtype: ~azure.mgmt.batch.models.BatchAccount - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.BatchAccount"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) - api_version = kwargs.pop('api_version', "2022-06-01") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.BatchAccount] - 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'], + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + 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) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('BatchAccount', pipeline_response) + 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}"} # type: ignore - + get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}"} # type: ignore @distributed_trace - def list( - self, - **kwargs: Any - ) -> AsyncIterable["_models.BatchAccountListResult"]: + 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 BatchAccountListResult or the result of - cls(response) - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.batch.models.BatchAccountListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :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: """ - api_version = kwargs.pop('api_version', "2022-06-01") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.BatchAccountListResult] - cls = kwargs.pop('cls', None) # type: ClsType["_models.BatchAccountListResult"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + 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'], + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore else: - - request = build_list_request( - subscription_id=self._config.subscription_id, - api_version=api_version, - template_url=next_link, + # 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.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request @@ -470,10 +702,8 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -483,58 +713,67 @@ async def get_next(next_link=None): return pipeline_response + return AsyncItemPaged(get_next, extract_data) - return AsyncItemPaged( - get_next, extract_data - ) - list.metadata = {'url': "/subscriptions/{subscriptionId}/providers/Microsoft.Batch/batchAccounts"} # type: ignore + list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Batch/batchAccounts"} # type: ignore @distributed_trace - def list_by_resource_group( - self, - resource_group_name: str, - **kwargs: Any - ) -> AsyncIterable["_models.BatchAccountListResult"]: + 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 BatchAccountListResult or the result of - cls(response) - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.batch.models.BatchAccountListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :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: """ - api_version = kwargs.pop('api_version', "2022-06-01") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.BatchAccountListResult] - cls = kwargs.pop('cls', None) # type: ClsType["_models.BatchAccountListResult"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + 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'], + 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) + request.url = self._client.format_url(request.url) # type: ignore else: - - 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=next_link, + # 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.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request @@ -548,10 +787,8 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -561,55 +798,59 @@ async def get_next(next_link=None): return pipeline_response + return AsyncItemPaged(get_next, extract_data) - return AsyncItemPaged( - get_next, extract_data - ) - list_by_resource_group.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts"} # type: ignore + list_by_resource_group.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts"} # type: ignore @distributed_trace_async async def synchronize_auto_storage_keys( # pylint: disable=inconsistent-return-statements - self, - resource_group_name: str, - account_name: str, - **kwargs: Any + 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. + :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) + :return: None or the result of cls(response) :rtype: None - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + 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', "2022-06-01") # type: str + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[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'], + 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) + request.url = self._client.format_url(request.url) # type: ignore - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + 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 [204]: @@ -619,17 +860,82 @@ async def synchronize_auto_storage_keys( # pylint: disable=inconsistent-return- if cls: return cls(pipeline_response, None, {}) - synchronize_auto_storage_keys.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/syncAutoStorageKeys"} # type: ignore + synchronize_auto_storage_keys.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/syncAutoStorageKeys"} # type: ignore + + @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: "_models.BatchAccountRegenerateKeyParameters", + parameters: Union[_models.BatchAccountRegenerateKeyParameters, IO], **kwargs: Any - ) -> "_models.BatchAccountKeys": + ) -> _models.BatchAccountKeys: """Regenerates the specified account key for the Batch account. This operation applies only to Batch accounts with allowedAuthenticationModes containing @@ -638,26 +944,45 @@ async def regenerate_key( 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. + :param account_name: The name of the Batch account. Required. :type account_name: str - :param parameters: The type of key to regenerate. - :type parameters: ~azure.mgmt.batch.models.BatchAccountRegenerateKeyParameters + :param parameters: The type of key to regenerate. Is either a model 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) + :return: BatchAccountKeys or the result of cls(response) :rtype: ~azure.mgmt.batch.models.BatchAccountKeys - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.BatchAccountKeys"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + 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', "2022-06-01") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.BatchAccountKeys] - _json = self._serialize.body(parameters, 'BatchAccountRegenerateKeyParameters') + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "BatchAccountRegenerateKeyParameters") request = build_regenerate_key_request( resource_group_name=resource_group_name, @@ -666,39 +991,35 @@ async def regenerate_key( api_version=api_version, content_type=content_type, json=_json, - template_url=self.regenerate_key.metadata['url'], + 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) + request.url = self._client.format_url(request.url) # type: ignore - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + 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) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('BatchAccountKeys', pipeline_response) + 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"} # type: ignore - + regenerate_key.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/regenerateKeys"} # type: ignore @distributed_trace_async - async def get_keys( - self, - resource_group_name: str, - account_name: str, - **kwargs: Any - ) -> "_models.BatchAccountKeys": + 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 @@ -707,103 +1028,124 @@ async def get_keys( 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. + :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) + :return: BatchAccountKeys or the result of cls(response) :rtype: ~azure.mgmt.batch.models.BatchAccountKeys - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.BatchAccountKeys"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) - api_version = kwargs.pop('api_version', "2022-06-01") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.BatchAccountKeys] - 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'], + template_url=self.get_keys.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + 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) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('BatchAccountKeys', pipeline_response) + 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"} # type: ignore - + get_keys.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/listKeys"} # type: ignore @distributed_trace def list_detectors( - self, - resource_group_name: str, - account_name: str, - **kwargs: Any - ) -> AsyncIterable["_models.DetectorListResult"]: + 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. + :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 DetectorListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.batch.models.DetectorListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :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: """ - api_version = kwargs.pop('api_version', "2022-06-01") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.DetectorListResult] - cls = kwargs.pop('cls', None) # type: ClsType["_models.DetectorListResult"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + 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, - subscription_id=self._config.subscription_id, account_name=account_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_detectors.metadata['url'], + template_url=self.list_detectors.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore else: - - request = build_list_detectors_request( - resource_group_name=resource_group_name, - subscription_id=self._config.subscription_id, - account_name=account_name, - api_version=api_version, - template_url=next_link, + # 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.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request @@ -817,10 +1159,8 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -830,81 +1170,80 @@ async def get_next(next_link=None): return pipeline_response + return AsyncItemPaged(get_next, extract_data) - return AsyncItemPaged( - get_next, extract_data - ) - list_detectors.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/detectors"} # type: ignore + list_detectors.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/detectors"} # type: ignore @distributed_trace_async async def get_detector( - self, - resource_group_name: str, - account_name: str, - detector_id: str, - **kwargs: Any - ) -> "_models.DetectorResponse": + 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. + :param account_name: The name of the Batch account. Required. :type account_name: str - :param detector_id: The name of the detector. + :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) + :return: DetectorResponse or the result of cls(response) :rtype: ~azure.mgmt.batch.models.DetectorResponse - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.DetectorResponse"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + 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', "2022-06-01") # type: str + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.DetectorResponse] - request = build_get_detector_request( resource_group_name=resource_group_name, - subscription_id=self._config.subscription_id, 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'], + template_url=self.get_detector.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + 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) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('DetectorResponse', pipeline_response) + 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}"} # type: ignore - + get_detector.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/detectors/{detectorId}"} # type: ignore @distributed_trace def list_outbound_network_dependencies_endpoints( - self, - resource_group_name: str, - account_name: str, - **kwargs: Any - ) -> AsyncIterable["_models.OutboundEnvironmentEndpointCollection"]: + 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 @@ -913,47 +1252,63 @@ def list_outbound_network_dependencies_endpoints( 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. + :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 OutboundEnvironmentEndpointCollection or the - result of cls(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.OutboundEnvironmentEndpointCollection] - :raises: ~azure.core.exceptions.HttpResponseError + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.batch.models.OutboundEnvironmentEndpoint] + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2022-06-01") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.OutboundEnvironmentEndpointCollection] - cls = kwargs.pop('cls', None) # type: ClsType["_models.OutboundEnvironmentEndpointCollection"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + 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'], + 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) + request.url = self._client.format_url(request.url) # type: ignore else: - - 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=next_link, + # 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.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request @@ -967,10 +1322,8 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -980,8 +1333,6 @@ async def get_next(next_link=None): return pipeline_response + return AsyncItemPaged(get_next, extract_data) - return AsyncItemPaged( - get_next, extract_data - ) - list_outbound_network_dependencies_endpoints.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/outboundNetworkDependenciesEndpoints"} # type: ignore + list_outbound_network_dependencies_endpoints.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/outboundNetworkDependenciesEndpoints"} # type: ignore diff --git a/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/aio/operations/_certificate_operations.py b/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/aio/operations/_certificate_operations.py index 644cd1d5a4db..58a4d76750e2 100644 --- a/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/aio/operations/_certificate_operations.py +++ b/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/aio/operations/_certificate_operations.py @@ -6,46 +6,66 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar, Union +import sys +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, map_error +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_initial, build_get_request, build_list_by_batch_account_request, build_update_request -T = TypeVar('T') +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, +) + +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 CertificateOperations: - """CertificateOperations 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. +class CertificateOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.batch.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. + Instead, you should access the following operations through + :class:`~azure.mgmt.batch.aio.BatchManagementClient`'s + :attr:`certificate` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + 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( @@ -56,12 +76,17 @@ def list_by_batch_account( select: Optional[str] = None, filter: Optional[str] = None, **kwargs: Any - ) -> AsyncIterable["_models.ListCertificatesResult"]: + ) -> 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 + `_ 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. + :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. @@ -75,49 +100,59 @@ def list_by_batch_account( 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 ListCertificatesResult or the result of - cls(response) - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.batch.models.ListCertificatesResult] - :raises: ~azure.core.exceptions.HttpResponseError + :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: """ - api_version = kwargs.pop('api_version', "2022-06-01") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.ListCertificatesResult] - cls = kwargs.pop('cls', None) # type: ClsType["_models.ListCertificatesResult"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + 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, - api_version=api_version, maxresults=maxresults, select=select, filter=filter, - template_url=self.list_by_batch_account.metadata['url'], + 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) + request.url = self._client.format_url(request.url) # type: ignore else: - - request = build_list_by_batch_account_request( - resource_group_name=resource_group_name, - account_name=account_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - maxresults=maxresults, - select=select, - filter=filter, - template_url=next_link, + # 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.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request @@ -131,10 +166,8 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -144,34 +177,39 @@ async def get_next(next_link=None): return pipeline_response + return AsyncItemPaged(get_next, extract_data) - return AsyncItemPaged( - get_next, extract_data - ) - list_by_batch_account.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/certificates"} # type: ignore + list_by_batch_account.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/certificates"} # type: ignore - @distributed_trace_async + @overload async def create( self, resource_group_name: str, account_name: str, certificate_name: str, - parameters: "_models.CertificateCreateOrUpdateParameters", + parameters: _models.CertificateCreateOrUpdateParameters, if_match: Optional[str] = None, if_none_match: Optional[str] = None, + *, + content_type: str = "application/json", **kwargs: Any - ) -> "_models.Certificate": + ) -> _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 + `_ 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. + :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. + example SHA1-a3d1c5. Required. :type certificate_name: str - :param parameters: Additional parameters for certificate creation. + :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 @@ -180,42 +218,152 @@ async def create( :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 + `_ 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) + :return: Certificate or the result of cls(response) :rtype: ~azure.mgmt.batch.models.Certificate - :raises: ~azure.core.exceptions.HttpResponseError + :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 + `_ 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 model 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: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Certificate"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) - api_version = kwargs.pop('api_version', "2022-06-01") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - _json = self._serialize.body(parameters, 'CertificateCreateOrUpdateParameters') + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.Certificate] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, 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, - if_match=if_match, - if_none_match=if_none_match, - template_url=self.create.metadata['url'], + content=_content, + template_url=self.create.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + 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]: @@ -223,17 +371,98 @@ async def create( raise HttpResponseError(response=response, error_format=ARMErrorFormat) response_headers = {} - response_headers['ETag']=self._deserialize('str', response.headers.get('ETag')) + response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) - deserialized = self._deserialize('Certificate', pipeline_response) + 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}"} # type: ignore + create.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/certificates/{certificateName}"} # type: ignore + + @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 + `_ 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 + `_ 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( @@ -241,60 +470,84 @@ async def update( resource_group_name: str, account_name: str, certificate_name: str, - parameters: "_models.CertificateCreateOrUpdateParameters", + parameters: Union[_models.CertificateCreateOrUpdateParameters, IO], if_match: Optional[str] = None, **kwargs: Any - ) -> "_models.Certificate": + ) -> _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 + `_ 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. + :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. + example SHA1-a3d1c5. Required. :type certificate_name: str - :param parameters: Certificate entity to update. - :type parameters: ~azure.mgmt.batch.models.CertificateCreateOrUpdateParameters + :param parameters: Certificate entity to update. Is either a model 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) + :return: Certificate or the result of cls(response) :rtype: ~azure.mgmt.batch.models.Certificate - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Certificate"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + 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', "2022-06-01") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.Certificate] - _json = self._serialize.body(parameters, 'CertificateCreateOrUpdateParameters') + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, 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, - if_match=if_match, - template_url=self.update.metadata['url'], + content=_content, + template_url=self.update.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + 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]: @@ -302,50 +555,53 @@ async def update( raise HttpResponseError(response=response, error_format=ARMErrorFormat) response_headers = {} - response_headers['ETag']=self._deserialize('str', response.headers.get('ETag')) + response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) - deserialized = self._deserialize('Certificate', pipeline_response) + 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}"} # type: ignore - + update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/certificates/{certificateName}"} # type: ignore async def _delete_initial( # pylint: disable=inconsistent-return-statements - self, - resource_group_name: str, - account_name: str, - certificate_name: str, - **kwargs: Any + self, resource_group_name: str, account_name: str, certificate_name: str, **kwargs: Any ) -> None: - cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) - api_version = kwargs.pop('api_version', "2022-06-01") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - request = build_delete_request_initial( + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[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'], + template_url=self._delete_initial.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + 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, 204]: @@ -354,33 +610,32 @@ async def _delete_initial( # pylint: disable=inconsistent-return-statements 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')) - + 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}"} # type: ignore - + _delete_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/certificates/{certificateName}"} # type: ignore @distributed_trace_async - async def begin_delete( # pylint: disable=inconsistent-return-statements - self, - resource_group_name: str, - account_name: str, - certificate_name: str, - **kwargs: Any + 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 + `_ 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. + :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. + 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. @@ -392,94 +647,111 @@ async def begin_delete( # pylint: disable=inconsistent-return-statements 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 + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2022-06-01") # type: str - 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] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[None] + 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._delete_initial( + 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, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) - def get_long_running_output(pipeline_response): + 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 = AsyncARMPolling(lro_delay, lro_options={'final-state-via': 'location'}, **kwargs) - elif polling is False: polling_method = AsyncNoPolling() - else: polling_method = polling + 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 + deserialization_callback=get_long_running_output, ) return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_delete.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/certificates/{certificateName}"} # type: ignore + begin_delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/certificates/{certificateName}"} # type: ignore @distributed_trace_async async def get( - self, - resource_group_name: str, - account_name: str, - certificate_name: str, - **kwargs: Any - ) -> "_models.Certificate": + 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 + `_ 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. + :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. + 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) + :return: Certificate or the result of cls(response) :rtype: ~azure.mgmt.batch.models.Certificate - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Certificate"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) - api_version = kwargs.pop('api_version', "2022-06-01") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.Certificate] - 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'], + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + 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]: @@ -487,26 +759,21 @@ async def get( raise HttpResponseError(response=response, error_format=ARMErrorFormat) response_headers = {} - response_headers['ETag']=self._deserialize('str', response.headers.get('ETag')) + response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) - deserialized = self._deserialize('Certificate', pipeline_response) + 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}"} # type: ignore - + get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/certificates/{certificateName}"} # type: ignore @distributed_trace_async async def cancel_deletion( - self, - resource_group_name: str, - account_name: str, - certificate_name: str, - **kwargs: Any - ) -> "_models.Certificate": + 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 @@ -516,44 +783,57 @@ async def cancel_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 + `_ 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. + :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. + 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) + :return: Certificate or the result of cls(response) :rtype: ~azure.mgmt.batch.models.Certificate - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Certificate"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + 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', "2022-06-01") # type: str + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.Certificate] - 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'], + template_url=self.cancel_deletion.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + 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]: @@ -561,14 +841,13 @@ async def cancel_deletion( raise HttpResponseError(response=response, error_format=ARMErrorFormat) response_headers = {} - response_headers['ETag']=self._deserialize('str', response.headers.get('ETag')) + response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) - deserialized = self._deserialize('Certificate', pipeline_response) + 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"} # type: ignore - + cancel_deletion.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/certificates/{certificateName}/cancelDelete"} # type: ignore diff --git a/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/aio/operations/_location_operations.py b/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/aio/operations/_location_operations.py index dc40d2bf7e64..3e6fc89ac623 100644 --- a/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/aio/operations/_location_operations.py +++ b/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/aio/operations/_location_operations.py @@ -6,110 +6,127 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar +import sys +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, map_error +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') +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, +) + +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 LocationOperations: - """LocationOperations 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. +class LocationOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.batch.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. + Instead, you should access the following operations through + :class:`~azure.mgmt.batch.aio.BatchManagementClient`'s + :attr:`location` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + 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": + 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. + :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) + :return: BatchLocationQuota or the result of cls(response) :rtype: ~azure.mgmt.batch.models.BatchLocationQuota - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.BatchLocationQuota"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) - api_version = kwargs.pop('api_version', "2022-06-01") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.BatchLocationQuota] - 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'], + template_url=self.get_quotas.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + 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) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('BatchLocationQuota', pipeline_response) + 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"} # type: ignore - + get_quotas.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Batch/locations/{locationName}/quotas"} # type: ignore @distributed_trace def list_supported_virtual_machine_skus( - self, - location_name: str, - maxresults: Optional[int] = None, - filter: Optional[str] = None, - **kwargs: Any - ) -> AsyncIterable["_models.SupportedSkusResult"]: + 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. + :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. @@ -118,43 +135,57 @@ def list_supported_virtual_machine_skus( 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 SupportedSkusResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.batch.models.SupportedSkusResult] - :raises: ~azure.core.exceptions.HttpResponseError + :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: """ - api_version = kwargs.pop('api_version', "2022-06-01") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.SupportedSkusResult] - cls = kwargs.pop('cls', None) # type: ClsType["_models.SupportedSkusResult"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + 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, - api_version=api_version, maxresults=maxresults, filter=filter, - template_url=self.list_supported_virtual_machine_skus.metadata['url'], + 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) + request.url = self._client.format_url(request.url) # type: ignore else: - - request = build_list_supported_virtual_machine_skus_request( - location_name=location_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - maxresults=maxresults, - filter=filter, - template_url=next_link, + # 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.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request @@ -168,10 +199,8 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -181,23 +210,17 @@ async def get_next(next_link=None): return pipeline_response + return AsyncItemPaged(get_next, extract_data) - return AsyncItemPaged( - get_next, extract_data - ) - list_supported_virtual_machine_skus.metadata = {'url': "/subscriptions/{subscriptionId}/providers/Microsoft.Batch/locations/{locationName}/virtualMachineSkus"} # type: ignore + list_supported_virtual_machine_skus.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Batch/locations/{locationName}/virtualMachineSkus"} # type: ignore @distributed_trace def list_supported_cloud_service_skus( - self, - location_name: str, - maxresults: Optional[int] = None, - filter: Optional[str] = None, - **kwargs: Any - ) -> AsyncIterable["_models.SupportedSkusResult"]: + 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. + :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. @@ -206,43 +229,57 @@ def list_supported_cloud_service_skus( 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 SupportedSkusResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.batch.models.SupportedSkusResult] - :raises: ~azure.core.exceptions.HttpResponseError + :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: """ - api_version = kwargs.pop('api_version', "2022-06-01") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.SupportedSkusResult] - cls = kwargs.pop('cls', None) # type: ClsType["_models.SupportedSkusResult"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + 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, - api_version=api_version, maxresults=maxresults, filter=filter, - template_url=self.list_supported_cloud_service_skus.metadata['url'], + 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) + request.url = self._client.format_url(request.url) # type: ignore else: - - request = build_list_supported_cloud_service_skus_request( - location_name=location_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - maxresults=maxresults, - filter=filter, - template_url=next_link, + # 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.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request @@ -256,10 +293,8 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -269,40 +304,96 @@ async def get_next(next_link=None): return pipeline_response + return AsyncItemPaged(get_next, extract_data) - return AsyncItemPaged( - get_next, extract_data - ) - list_supported_cloud_service_skus.metadata = {'url': "/subscriptions/{subscriptionId}/providers/Microsoft.Batch/locations/{locationName}/cloudServiceSkus"} # type: ignore + list_supported_cloud_service_skus.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Batch/locations/{locationName}/cloudServiceSkus"} # type: ignore - @distributed_trace_async + @overload async def check_name_availability( self, location_name: str, - parameters: "_models.CheckNameAvailabilityParameters", + parameters: _models.CheckNameAvailabilityParameters, + *, + content_type: str = "application/json", **kwargs: Any - ) -> "_models.CheckNameAvailabilityResult": + ) -> _models.CheckNameAvailabilityResult: """Checks whether the Batch account name is available in the specified region. - :param location_name: The desired region for the name check. + :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. + :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) + :return: CheckNameAvailabilityResult or the result of cls(response) :rtype: ~azure.mgmt.batch.models.CheckNameAvailabilityResult - :raises: ~azure.core.exceptions.HttpResponseError + :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 model + 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: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.CheckNameAvailabilityResult"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) - api_version = kwargs.pop('api_version', "2022-06-01") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - _json = self._serialize.body(parameters, 'CheckNameAvailabilityParameters') + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.CheckNameAvailabilityResult] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "CheckNameAvailabilityParameters") request = build_check_name_availability_request( location_name=location_name, @@ -310,28 +401,29 @@ async def check_name_availability( api_version=api_version, content_type=content_type, json=_json, - template_url=self.check_name_availability.metadata['url'], + 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) + request.url = self._client.format_url(request.url) # type: ignore - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + 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) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('CheckNameAvailabilityResult', pipeline_response) + 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"} # type: ignore - + check_name_availability.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Batch/locations/{locationName}/checkNameAvailability"} # type: ignore diff --git a/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/aio/operations/_operations.py b/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/aio/operations/_operations.py index a1c905d00d6d..9b6e6b42996e 100644 --- a/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/aio/operations/_operations.py +++ b/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/aio/operations/_operations.py @@ -6,81 +6,109 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +import sys 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, map_error +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') + +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: - """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. +class Operations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.batch.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. + Instead, you should access the following operations through + :class:`~azure.mgmt.batch.aio.BatchManagementClient`'s + :attr:`operations` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + 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.OperationListResult"]: + 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 OperationListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.batch.models.OperationListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :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: """ - api_version = kwargs.pop('api_version', "2022-06-01") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.OperationListResult] - cls = kwargs.pop('cls', None) # type: ClsType["_models.OperationListResult"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + 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'], + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore else: - - request = build_list_request( - api_version=api_version, - template_url=next_link, + # 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.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request @@ -94,10 +122,8 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -107,8 +133,6 @@ async def get_next(next_link=None): return pipeline_response + return AsyncItemPaged(get_next, extract_data) - return AsyncItemPaged( - get_next, extract_data - ) - list.metadata = {'url': "/providers/Microsoft.Batch/operations"} # type: ignore + list.metadata = {"url": "/providers/Microsoft.Batch/operations"} # type: ignore diff --git a/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/aio/operations/_patch.py b/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/aio/operations/_patch.py new file mode 100644 index 000000000000..f7dd32510333 --- /dev/null +++ b/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/aio/operations/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/aio/operations/_pool_operations.py b/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/aio/operations/_pool_operations.py index 0763264e3e72..3337d742227c 100644 --- a/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/aio/operations/_pool_operations.py +++ b/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/aio/operations/_pool_operations.py @@ -6,46 +6,67 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar, Union +import sys +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, map_error +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_initial, build_disable_auto_scale_request, build_get_request, build_list_by_batch_account_request, build_stop_resize_request, build_update_request -T = TypeVar('T') +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, +) + +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 PoolOperations: - """PoolOperations 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. +class PoolOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.batch.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. + Instead, you should access the following operations through + :class:`~azure.mgmt.batch.aio.BatchManagementClient`'s + :attr:`pool` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + 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( @@ -56,12 +77,13 @@ def list_by_batch_account( select: Optional[str] = None, filter: Optional[str] = None, **kwargs: Any - ) -> AsyncIterable["_models.ListPoolsResult"]: + ) -> 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. + :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. @@ -85,47 +107,59 @@ def list_by_batch_account( 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 ListPoolsResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.batch.models.ListPoolsResult] - :raises: ~azure.core.exceptions.HttpResponseError + :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: """ - api_version = kwargs.pop('api_version', "2022-06-01") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.ListPoolsResult] - cls = kwargs.pop('cls', None) # type: ClsType["_models.ListPoolsResult"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + 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, - api_version=api_version, maxresults=maxresults, select=select, filter=filter, - template_url=self.list_by_batch_account.metadata['url'], + 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) + request.url = self._client.format_url(request.url) # type: ignore else: - - request = build_list_by_batch_account_request( - resource_group_name=resource_group_name, - account_name=account_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - maxresults=maxresults, - select=select, - filter=filter, - template_url=next_link, + # 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.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request @@ -139,10 +173,8 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -152,32 +184,33 @@ async def get_next(next_link=None): return pipeline_response + return AsyncItemPaged(get_next, extract_data) - return AsyncItemPaged( - get_next, extract_data - ) - list_by_batch_account.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/pools"} # type: ignore + list_by_batch_account.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/pools"} # type: ignore - @distributed_trace_async + @overload async def create( self, resource_group_name: str, account_name: str, pool_name: str, - parameters: "_models.Pool", + parameters: _models.Pool, if_match: Optional[str] = None, if_none_match: Optional[str] = None, + *, + content_type: str = "application/json", **kwargs: Any - ) -> "_models.Pool": + ) -> _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. + :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. + :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. + :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 @@ -186,42 +219,140 @@ async def create( :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) + :return: Pool or the result of cls(response) :rtype: ~azure.mgmt.batch.models.Pool - :raises: ~azure.core.exceptions.HttpResponseError + :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 model 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: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Pool"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + 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', "2022-06-01") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.Pool] - _json = self._serialize.body(parameters, 'Pool') + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, 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, - if_match=if_match, - if_none_match=if_none_match, - template_url=self.create.metadata['url'], + content=_content, + template_url=self.create.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + 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]: @@ -229,17 +360,88 @@ async def create( raise HttpResponseError(response=response, error_format=ARMErrorFormat) response_headers = {} - response_headers['ETag']=self._deserialize('str', response.headers.get('ETag')) + response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) - deserialized = self._deserialize('Pool', pipeline_response) + 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}"} # type: ignore + create.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/pools/{poolName}"} # type: ignore + + @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( @@ -247,59 +449,80 @@ async def update( resource_group_name: str, account_name: str, pool_name: str, - parameters: "_models.Pool", + parameters: Union[_models.Pool, IO], if_match: Optional[str] = None, **kwargs: Any - ) -> "_models.Pool": + ) -> _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. + :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. + :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. - :type parameters: ~azure.mgmt.batch.models.Pool + updated, any property not supplied will be unchanged. Is either a model 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) + :return: Pool or the result of cls(response) :rtype: ~azure.mgmt.batch.models.Pool - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Pool"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + 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', "2022-06-01") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.Pool] - _json = self._serialize.body(parameters, 'Pool') + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, 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, - if_match=if_match, - template_url=self.update.metadata['url'], + content=_content, + template_url=self.update.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + 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]: @@ -307,50 +530,53 @@ async def update( raise HttpResponseError(response=response, error_format=ARMErrorFormat) response_headers = {} - response_headers['ETag']=self._deserialize('str', response.headers.get('ETag')) + response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) - deserialized = self._deserialize('Pool', pipeline_response) + 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}"} # type: ignore - + update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/pools/{poolName}"} # type: ignore async def _delete_initial( # pylint: disable=inconsistent-return-statements - self, - resource_group_name: str, - account_name: str, - pool_name: str, - **kwargs: Any + self, resource_group_name: str, account_name: str, pool_name: str, **kwargs: Any ) -> None: - cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + 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', "2022-06-01") # type: str + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[None] - - request = build_delete_request_initial( + 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'], + template_url=self._delete_initial.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + 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, 204]: @@ -359,31 +585,26 @@ async def _delete_initial( # pylint: disable=inconsistent-return-statements 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')) - + 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}"} # type: ignore - + _delete_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/pools/{poolName}"} # type: ignore @distributed_trace_async - async def begin_delete( # pylint: disable=inconsistent-return-statements - self, - resource_group_name: str, - account_name: str, - pool_name: str, - **kwargs: Any + 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. + :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. + :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. @@ -395,92 +616,103 @@ async def begin_delete( # pylint: disable=inconsistent-return-statements 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 + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2022-06-01") # type: str - 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] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[None] + 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._delete_initial( + 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, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) - def get_long_running_output(pipeline_response): + 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 = AsyncARMPolling(lro_delay, lro_options={'final-state-via': 'location'}, **kwargs) - elif polling is False: polling_method = AsyncNoPolling() - else: polling_method = polling + 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 + deserialization_callback=get_long_running_output, ) return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_delete.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/pools/{poolName}"} # type: ignore + begin_delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/pools/{poolName}"} # type: ignore @distributed_trace_async - async def get( - self, - resource_group_name: str, - account_name: str, - pool_name: str, - **kwargs: Any - ) -> "_models.Pool": + 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. + :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. + :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) + :return: Pool or the result of cls(response) :rtype: ~azure.mgmt.batch.models.Pool - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Pool"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + 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', "2022-06-01") # type: str + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.Pool] - 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'], + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + 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]: @@ -488,64 +720,68 @@ async def get( raise HttpResponseError(response=response, error_format=ARMErrorFormat) response_headers = {} - response_headers['ETag']=self._deserialize('str', response.headers.get('ETag')) + response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) - deserialized = self._deserialize('Pool', pipeline_response) + 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}"} # type: ignore - + get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/pools/{poolName}"} # type: ignore @distributed_trace_async async def disable_auto_scale( - self, - resource_group_name: str, - account_name: str, - pool_name: str, - **kwargs: Any - ) -> "_models.Pool": + 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. + :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. + :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) + :return: Pool or the result of cls(response) :rtype: ~azure.mgmt.batch.models.Pool - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Pool"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + 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', "2022-06-01") # type: str + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.Pool] - 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'], + template_url=self.disable_auto_scale.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + 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]: @@ -553,26 +789,21 @@ async def disable_auto_scale( raise HttpResponseError(response=response, error_format=ARMErrorFormat) response_headers = {} - response_headers['ETag']=self._deserialize('str', response.headers.get('ETag')) + response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) - deserialized = self._deserialize('Pool', pipeline_response) + 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"} # type: ignore - + disable_auto_scale.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/pools/{poolName}/disableAutoScale"} # type: ignore @distributed_trace_async async def stop_resize( - self, - resource_group_name: str, - account_name: str, - pool_name: str, - **kwargs: Any - ) -> "_models.Pool": + 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 @@ -583,41 +814,50 @@ async def stop_resize( 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. + :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. + :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) + :return: Pool or the result of cls(response) :rtype: ~azure.mgmt.batch.models.Pool - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Pool"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + 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', "2022-06-01") # type: str + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.Pool] - 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'], + template_url=self.stop_resize.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + 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]: @@ -625,14 +865,13 @@ async def stop_resize( raise HttpResponseError(response=response, error_format=ARMErrorFormat) response_headers = {} - response_headers['ETag']=self._deserialize('str', response.headers.get('ETag')) + response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) - deserialized = self._deserialize('Pool', pipeline_response) + 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"} # type: ignore - + stop_resize.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/pools/{poolName}/stopResize"} # type: ignore diff --git a/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/aio/operations/_private_endpoint_connection_operations.py b/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/aio/operations/_private_endpoint_connection_operations.py index 8fc8a3f200a8..633fea39bc38 100644 --- a/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/aio/operations/_private_endpoint_connection_operations.py +++ b/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/aio/operations/_private_endpoint_connection_operations.py @@ -6,104 +6,133 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar, Union +import sys +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, map_error +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_initial, build_get_request, build_list_by_batch_account_request, build_update_request_initial -T = TypeVar('T') +from ...operations._private_endpoint_connection_operations import ( + build_delete_request, + build_get_request, + build_list_by_batch_account_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 PrivateEndpointConnectionOperations: - """PrivateEndpointConnectionOperations 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. +class PrivateEndpointConnectionOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.batch.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. + 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, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + 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.ListPrivateEndpointConnectionsResult"]: + 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. + :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 ListPrivateEndpointConnectionsResult or the result - of cls(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.ListPrivateEndpointConnectionsResult] - :raises: ~azure.core.exceptions.HttpResponseError + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.batch.models.PrivateEndpointConnection] + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2022-06-01") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.ListPrivateEndpointConnectionsResult] - cls = kwargs.pop('cls', None) # type: ClsType["_models.ListPrivateEndpointConnectionsResult"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + 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( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, account_name=account_name, - api_version=api_version, + subscription_id=self._config.subscription_id, maxresults=maxresults, - template_url=self.list_by_batch_account.metadata['url'], + 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) + request.url = self._client.format_url(request.url) # type: ignore else: - - request = build_list_by_batch_account_request( - subscription_id=self._config.subscription_id, - resource_group_name=resource_group_name, - account_name=account_name, - api_version=api_version, - maxresults=maxresults, - template_url=next_link, + # 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.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request @@ -117,10 +146,8 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -130,137 +157,245 @@ async def get_next(next_link=None): return pipeline_response + return AsyncItemPaged(get_next, extract_data) - return AsyncItemPaged( - get_next, extract_data - ) - list_by_batch_account.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/privateEndpointConnections"} # type: ignore + list_by_batch_account.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/privateEndpointConnections"} # type: ignore @distributed_trace_async async def get( - self, - resource_group_name: str, - account_name: str, - private_endpoint_connection_name: str, - **kwargs: Any - ) -> "_models.PrivateEndpointConnection": + 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. + :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. + 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) + :return: PrivateEndpointConnection or the result of cls(response) :rtype: ~azure.mgmt.batch.models.PrivateEndpointConnection - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.PrivateEndpointConnection"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) - api_version = kwargs.pop('api_version', "2022-06-01") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.PrivateEndpointConnection] - request = build_get_request( - subscription_id=self._config.subscription_id, 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'], + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + 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) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('PrivateEndpointConnection', pipeline_response) + 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}"} # type: ignore - + get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/privateEndpointConnections/{privateEndpointConnectionName}"} # type: ignore async def _update_initial( self, resource_group_name: str, account_name: str, private_endpoint_connection_name: str, - parameters: "_models.PrivateEndpointConnection", + parameters: Union[_models.PrivateEndpointConnection, IO], if_match: Optional[str] = None, **kwargs: Any - ) -> Optional["_models.PrivateEndpointConnection"]: - cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.PrivateEndpointConnection"]] + ) -> Optional[_models.PrivateEndpointConnection]: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - - api_version = kwargs.pop('api_version', "2022-06-01") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] - - _json = self._serialize.body(parameters, 'PrivateEndpointConnection') - - request = build_update_request_initial( - subscription_id=self._config.subscription_id, + 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", self._config.api_version) + ) # type: Literal["2022-10-01"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.PrivateEndpointConnection]] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, 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, - if_match=if_match, - template_url=self._update_initial.metadata['url'], + 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) + request.url = self._client.format_url(request.url) # type: ignore - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + 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, 204]: + 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) + 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')) - + 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}"} # type: ignore + _update_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/privateEndpointConnections/{privateEndpointConnectionName}"} # type: ignore + @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( @@ -268,26 +403,31 @@ async def begin_update( resource_group_name: str, account_name: str, private_endpoint_connection_name: str, - parameters: "_models.PrivateEndpointConnection", + parameters: Union[_models.PrivateEndpointConnection, IO], if_match: Optional[str] = None, **kwargs: Any - ) -> AsyncLROPoller["_models.PrivateEndpointConnection"]: + ) -> 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. + :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. + 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. - :type parameters: ~azure.mgmt.batch.models.PrivateEndpointConnection + are supplied will be updated, any property not supplied will be unchanged. Is either a model + 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 @@ -299,19 +439,21 @@ async def begin_update( :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 + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2022-06-01") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] - polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType["_models.PrivateEndpointConnection"] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + _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", self._config.api_version) + ) # type: Literal["2022-10-01"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.PrivateEndpointConnection] + 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( + raw_result = await self._update_initial( # type: ignore resource_group_name=resource_group_name, account_name=account_name, private_endpoint_connection_name=private_endpoint_connection_name, @@ -319,65 +461,75 @@ async def begin_update( if_match=if_match, api_version=api_version, content_type=content_type, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - response = pipeline_response.http_response - deserialized = self._deserialize('PrivateEndpointConnection', pipeline_response) + deserialized = self._deserialize("PrivateEndpointConnection", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - - if polling is True: polling_method = AsyncARMPolling(lro_delay, lro_options={'final-state-via': 'azure-async-operation'}, **kwargs) - elif polling is False: polling_method = AsyncNoPolling() - else: polling_method = polling + 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 + deserialization_callback=get_long_running_output, ) return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_update.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/privateEndpointConnections/{privateEndpointConnectionName}"} # type: ignore + begin_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/privateEndpointConnections/{privateEndpointConnectionName}"} # type: ignore async def _delete_initial( # pylint: disable=inconsistent-return-statements - self, - resource_group_name: str, - account_name: str, - private_endpoint_connection_name: str, - **kwargs: Any + self, resource_group_name: str, account_name: str, private_endpoint_connection_name: str, **kwargs: Any ) -> None: - cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) - api_version = kwargs.pop('api_version', "2022-06-01") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - request = build_delete_request_initial( - subscription_id=self._config.subscription_id, + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[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'], + template_url=self._delete_initial.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + 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 [202, 204]: @@ -386,32 +538,27 @@ async def _delete_initial( # pylint: disable=inconsistent-return-statements 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')) - + 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}"} # type: ignore - + _delete_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/privateEndpointConnections/{privateEndpointConnectionName}"} # type: ignore @distributed_trace_async - async def begin_delete( # pylint: disable=inconsistent-return-statements - self, - resource_group_name: str, - account_name: str, - private_endpoint_connection_name: str, - **kwargs: Any + 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. + :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. + 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. @@ -423,42 +570,51 @@ async def begin_delete( # pylint: disable=inconsistent-return-statements 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 + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2022-06-01") # type: str - 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] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[None] + 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._delete_initial( + 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, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) - def get_long_running_output(pipeline_response): + 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 = AsyncARMPolling(lro_delay, lro_options={'final-state-via': 'azure-async-operation'}, **kwargs) - elif polling is False: polling_method = AsyncNoPolling() - else: polling_method = polling + 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 + deserialization_callback=get_long_running_output, ) return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_delete.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/privateEndpointConnections/{privateEndpointConnectionName}"} # type: ignore + begin_delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/privateEndpointConnections/{privateEndpointConnectionName}"} # type: ignore diff --git a/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/aio/operations/_private_link_resource_operations.py b/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/aio/operations/_private_link_resource_operations.py index 8e3a435f39ae..2b417daeafa6 100644 --- a/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/aio/operations/_private_link_resource_operations.py +++ b/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/aio/operations/_private_link_resource_operations.py @@ -6,102 +6,124 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +import sys 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, map_error +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') + +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 PrivateLinkResourceOperations: - """PrivateLinkResourceOperations 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. +class PrivateLinkResourceOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.batch.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. + 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, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + 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.ListPrivateLinkResourcesResult"]: + 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. + :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 ListPrivateLinkResourcesResult or the result of - cls(response) - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.batch.models.ListPrivateLinkResourcesResult] - :raises: ~azure.core.exceptions.HttpResponseError + :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: """ - api_version = kwargs.pop('api_version', "2022-06-01") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.ListPrivateLinkResourcesResult] - cls = kwargs.pop('cls', None) # type: ClsType["_models.ListPrivateLinkResourcesResult"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + 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( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, account_name=account_name, - api_version=api_version, + subscription_id=self._config.subscription_id, maxresults=maxresults, - template_url=self.list_by_batch_account.metadata['url'], + 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) + request.url = self._client.format_url(request.url) # type: ignore else: - - request = build_list_by_batch_account_request( - subscription_id=self._config.subscription_id, - resource_group_name=resource_group_name, - account_name=account_name, - api_version=api_version, - maxresults=maxresults, - template_url=next_link, + # 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.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request @@ -115,10 +137,8 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -128,71 +148,73 @@ async def get_next(next_link=None): return pipeline_response + return AsyncItemPaged(get_next, extract_data) - return AsyncItemPaged( - get_next, extract_data - ) - list_by_batch_account.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/privateLinkResources"} # type: ignore + list_by_batch_account.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/privateLinkResources"} # type: ignore @distributed_trace_async async def get( - self, - resource_group_name: str, - account_name: str, - private_link_resource_name: str, - **kwargs: Any - ) -> "_models.PrivateLinkResource": + 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. + :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. + 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) + :return: PrivateLinkResource or the result of cls(response) :rtype: ~azure.mgmt.batch.models.PrivateLinkResource - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.PrivateLinkResource"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + 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', "2022-06-01") # type: str + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.PrivateLinkResource] - request = build_get_request( - subscription_id=self._config.subscription_id, 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'], + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + 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) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('PrivateLinkResource', pipeline_response) + 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}"} # type: ignore - + get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/privateLinkResources/{privateLinkResourceName}"} # type: ignore diff --git a/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/models/__init__.py b/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/models/__init__.py index af6716ffd7a8..41cf71a645f3 100644 --- a/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/models/__init__.py +++ b/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/models/__init__.py @@ -107,179 +107,183 @@ from ._models_py3 import WindowsConfiguration from ._models_py3 import WindowsUserConfiguration - -from ._batch_management_client_enums import ( - AccountKeyType, - AllocationState, - AuthenticationMode, - AutoStorageAuthenticationMode, - AutoUserScope, - CachingType, - CertificateFormat, - CertificateProvisioningState, - CertificateStoreLocation, - CertificateVisibility, - ComputeNodeDeallocationOption, - ComputeNodeFillType, - ContainerWorkingDirectory, - DiskEncryptionTarget, - DynamicVNetAssignmentScope, - ElevationLevel, - EndpointAccessDefaultAction, - IPAddressProvisioningType, - InboundEndpointProtocol, - InterNodeCommunicationState, - KeySource, - LoginMode, - NameAvailabilityReason, - NetworkSecurityGroupRuleAccess, - NodePlacementPolicyType, - PackageState, - PoolAllocationMode, - PoolIdentityType, - PoolProvisioningState, - PrivateEndpointConnectionProvisioningState, - PrivateLinkServiceConnectionStatus, - ProvisioningState, - PublicNetworkAccessType, - ResourceIdentityType, - StorageAccountType, -) +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 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 * # type: ignore # 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', - 'ContainerWorkingDirectory', - 'DiskEncryptionTarget', - 'DynamicVNetAssignmentScope', - 'ElevationLevel', - 'EndpointAccessDefaultAction', - 'IPAddressProvisioningType', - 'InboundEndpointProtocol', - 'InterNodeCommunicationState', - 'KeySource', - 'LoginMode', - 'NameAvailabilityReason', - 'NetworkSecurityGroupRuleAccess', - 'NodePlacementPolicyType', - 'PackageState', - 'PoolAllocationMode', - 'PoolIdentityType', - 'PoolProvisioningState', - 'PrivateEndpointConnectionProvisioningState', - 'PrivateLinkServiceConnectionStatus', - 'ProvisioningState', - 'PublicNetworkAccessType', - 'ResourceIdentityType', - 'StorageAccountType', + "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", + "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() diff --git a/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/models/_batch_management_client_enums.py b/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/models/_batch_management_client_enums.py index a5b553f83d30..ea1809b7ae1e 100644 --- a/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/models/_batch_management_client_enums.py +++ b/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/models/_batch_management_client_enums.py @@ -7,22 +7,20 @@ # -------------------------------------------------------------------------- from enum import Enum -from six import with_metaclass from azure.core import CaseInsensitiveEnumMeta -class AccountKeyType(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): - """The type of account key to regenerate. - """ +class AccountKeyType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The type of account key to regenerate.""" #: The primary account key. PRIMARY = "Primary" #: The secondary account key. SECONDARY = "Secondary" -class AllocationState(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): - """Whether the pool is resizing. - """ + +class AllocationState(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Whether the pool is resizing.""" #: 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 @@ -34,9 +32,9 @@ class AllocationState(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): #: request has not yet been completed. STOPPING = "Stopping" -class AuthenticationMode(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): - """The authentication mode for the Batch account. - """ + +class AuthenticationMode(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The authentication mode for the Batch account.""" #: The authentication mode using shared keys. SHARED_KEY = "SharedKey" @@ -45,9 +43,9 @@ class AuthenticationMode(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): #: The authentication mode using task authentication tokens. TASK_AUTHENTICATION_TOKEN = "TaskAuthenticationToken" -class AutoStorageAuthenticationMode(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): - """The authentication mode which the Batch service will use to manage the auto-storage account. - """ + +class AutoStorageAuthenticationMode(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The authentication mode which the Batch service will use to manage the auto-storage account.""" #: The Batch service will authenticate requests to auto-storage using storage account keys. STORAGE_KEYS = "StorageKeys" @@ -55,7 +53,8 @@ class AutoStorageAuthenticationMode(with_metaclass(CaseInsensitiveEnumMeta, str, #: assigned to the Batch account. BATCH_ACCOUNT_MANAGED_IDENTITY = "BatchAccountManagedIdentity" -class AutoUserScope(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): + +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 @@ -68,9 +67,9 @@ class AutoUserScope(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): #: a pool. POOL = "Pool" -class CachingType(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): - """The type of caching to enable for the disk. - """ + +class CachingType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The type of caching to enable for the disk.""" #: The caching mode for the disk is not enabled. NONE = "None" @@ -79,16 +78,18 @@ class CachingType(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): #: The caching mode for the disk is read and write. READ_WRITE = "ReadWrite" -class CertificateFormat(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): - """The format of the certificate - either Pfx or Cer. If omitted, the default is Pfx. - """ + +class CertificateFormat(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The format of the certificate - either Pfx or Cer. If omitted, the default is Pfx.""" #: The certificate is a PFX (PKCS#12) formatted certificate or certificate chain. PFX = "Pfx" #: The certificate is a base64-encoded X.509 certificate. CER = "Cer" -class CertificateProvisioningState(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): + +class CertificateProvisioningState(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """CertificateProvisioningState.""" #: The certificate is available for use in pools. SUCCEEDED = "Succeeded" @@ -103,7 +104,8 @@ class CertificateProvisioningState(with_metaclass(CaseInsensitiveEnumMeta, str, #: the delete. FAILED = "Failed" -class CertificateStoreLocation(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): + +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 @@ -118,7 +120,9 @@ class CertificateStoreLocation(with_metaclass(CaseInsensitiveEnumMeta, str, Enum #: Certificates should be installed to the LocalMachine certificate store. LOCAL_MACHINE = "LocalMachine" -class CertificateVisibility(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): + +class CertificateVisibility(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """CertificateVisibility.""" #: 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 @@ -130,7 +134,8 @@ class CertificateVisibility(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): #: node. REMOTE_USER = "RemoteUser" -class ComputeNodeDeallocationOption(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): + +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. """ @@ -149,9 +154,9 @@ class ComputeNodeDeallocationOption(with_metaclass(CaseInsensitiveEnumMeta, str, #: expired. RETAINED_DATA = "RetainedData" -class ComputeNodeFillType(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): - """How tasks should be distributed across compute nodes. - """ + +class ComputeNodeFillType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """How tasks should be distributed across compute nodes.""" #: Tasks should be assigned evenly across all nodes in the pool. SPREAD = "Spread" @@ -159,7 +164,8 @@ class ComputeNodeFillType(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): #: any tasks are assigned to the next node in the pool. PACK = "Pack" -class ContainerWorkingDirectory(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): + +class ContainerWorkingDirectory(str, Enum, metaclass=CaseInsensitiveEnumMeta): """A flag to indicate where the container task working directory is. The default is 'taskWorkingDirectory'. """ @@ -171,9 +177,9 @@ class ContainerWorkingDirectory(with_metaclass(CaseInsensitiveEnumMeta, str, Enu #: the resource files downloaded by Batch. CONTAINER_IMAGE_DEFAULT = "ContainerImageDefault" -class DiskEncryptionTarget(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): - """If omitted, no disks on the compute nodes in the pool will be encrypted. - """ + +class DiskEncryptionTarget(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """If omitted, no disks on the compute nodes in the pool will be encrypted.""" #: The OS Disk on the compute node is encrypted. OS_DISK = "OsDisk" @@ -181,44 +187,45 @@ class DiskEncryptionTarget(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): #: partitions (such as those on mounted data disks) when encryption occurs at boot time. TEMPORARY_DISK = "TemporaryDisk" -class DynamicVNetAssignmentScope(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): - """The scope of dynamic vnet assignment. - """ + +class DynamicVNetAssignmentScope(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The scope of dynamic vnet assignment.""" #: No dynamic VNet assignment is enabled. NONE = "none" #: 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. + #: ID must also be set. This feature requires approval before use, please contact support JOB = "job" -class ElevationLevel(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): - """The elevation level of the user. - """ + +class ElevationLevel(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The elevation level of the user.""" #: The user is a standard user without elevated access. NON_ADMIN = "NonAdmin" #: The user is a user with elevated access and operates with full Administrator permissions. ADMIN = "Admin" -class EndpointAccessDefaultAction(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): - """Default action for endpoint access. It is only applicable when publicNetworkAccess is enabled. - """ + +class EndpointAccessDefaultAction(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Default action for endpoint access. It is only applicable when publicNetworkAccess is enabled.""" #: Allow client access. ALLOW = "Allow" #: Deny client access. DENY = "Deny" -class InboundEndpointProtocol(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): - """The protocol of the endpoint. - """ + +class InboundEndpointProtocol(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The protocol of the endpoint.""" #: Use TCP for the endpoint. TCP = "TCP" #: Use UDP for the endpoint. UDP = "UDP" -class InterNodeCommunicationState(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): + +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'. @@ -229,9 +236,9 @@ class InterNodeCommunicationState(with_metaclass(CaseInsensitiveEnumMeta, str, E #: Disable network communication between virtual machines. DISABLED = "Disabled" -class IPAddressProvisioningType(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): - """The provisioning type for Public IP Addresses for the Batch Pool. - """ + +class IPAddressProvisioningType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The provisioning type for Public IP Addresses for the Batch Pool.""" #: A public IP will be created and managed by Batch. There may be multiple public IPs depending on #: the size of the Pool. @@ -241,9 +248,9 @@ class IPAddressProvisioningType(with_metaclass(CaseInsensitiveEnumMeta, str, Enu #: No public IP Address will be created for the Compute Nodes in the Pool. NO_PUBLIC_IP_ADDRESSES = "NoPublicIPAddresses" -class KeySource(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): - """Type of the key source. - """ + +class KeySource(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Type of the key source.""" #: Batch creates and manages the encryption keys used to protect the account data. MICROSOFT_BATCH = "Microsoft.Batch" @@ -252,7 +259,8 @@ class KeySource(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): #: Identifier must also be supplied under the keyVaultProperties. MICROSOFT_KEY_VAULT = "Microsoft.KeyVault" -class LoginMode(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): + +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. """ @@ -265,7 +273,8 @@ class LoginMode(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): #: task, then this option is recommended. INTERACTIVE = "Interactive" -class NameAvailabilityReason(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): + +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. """ @@ -275,45 +284,59 @@ class NameAvailabilityReason(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)) #: The requested name is already in use. ALREADY_EXISTS = "AlreadyExists" -class NetworkSecurityGroupRuleAccess(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): - """The action that should be taken for a specified IP address, subnet range or tag. - """ + +class NetworkSecurityGroupRuleAccess(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The action that should be taken for a specified IP address, subnet range or tag.""" #: Allow access. ALLOW = "Allow" #: Deny access. DENY = "Deny" -class NodePlacementPolicyType(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): - """The default value is regional. - """ + +class NodeCommunicationMode(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Determines how a pool communicates with the Batch service.""" + + #: The node communication mode is automatically set by the Batch service. + DEFAULT = "Default" + #: 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. + CLASSIC = "Classic" + #: 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. + SIMPLIFIED = "Simplified" + + +class NodePlacementPolicyType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The default value is regional.""" #: All nodes in the pool will be allocated in the same region. REGIONAL = "Regional" #: Nodes in the pool will be spread across different zones with best effort balancing. ZONAL = "Zonal" -class PackageState(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): - """The current state of the application package. - """ + +class PackageState(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The current state of the application package.""" #: The application package has been created but has not yet been activated. PENDING = "Pending" #: The application package is ready for use. ACTIVE = "Active" -class PoolAllocationMode(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): - """The allocation mode for creating pools in the Batch account. - """ + +class PoolAllocationMode(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The allocation mode for creating pools in the Batch account.""" #: Pools will be allocated in subscriptions owned by the Batch service. BATCH_SERVICE = "BatchService" #: Pools will be allocated in a subscription owned by the user. USER_SUBSCRIPTION = "UserSubscription" -class PoolIdentityType(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): - """The type of identity used for the Batch Pool. - """ + +class PoolIdentityType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The type of identity used for the Batch Pool.""" #: Batch pool has user assigned identities with it. USER_ASSIGNED = "UserAssigned" @@ -321,9 +344,9 @@ class PoolIdentityType(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): #: existing identities. NONE = "None" -class PoolProvisioningState(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): - """The current state of the pool. - """ + +class PoolProvisioningState(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The current state of the pool.""" #: The pool is available to run tasks subject to the availability of compute nodes. SUCCEEDED = "Succeeded" @@ -331,9 +354,9 @@ class PoolProvisioningState(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): #: completed. DELETING = "Deleting" -class PrivateEndpointConnectionProvisioningState(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): - """The provisioning state of the private endpoint connection. - """ + +class PrivateEndpointConnectionProvisioningState(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The provisioning state of the private endpoint connection.""" #: The connection is creating. CREATING = "Creating" @@ -350,22 +373,22 @@ class PrivateEndpointConnectionProvisioningState(with_metaclass(CaseInsensitiveE #: The user has cancelled the connection creation. CANCELLED = "Cancelled" -class PrivateLinkServiceConnectionStatus(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): - """The status of the Batch private endpoint connection - """ - #: The private endpoint connection is approved and can be used to access Batch account. +class PrivateLinkServiceConnectionStatus(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The status of the Batch private endpoint connection.""" + + #: The private endpoint connection is approved and can be used to access Batch account APPROVED = "Approved" - #: The private endpoint connection is pending and cannot be used to access Batch account. + #: The private endpoint connection is pending and cannot be used to access Batch account PENDING = "Pending" - #: The private endpoint connection is rejected and cannot be used to access Batch account. + #: The private endpoint connection is rejected and cannot be used to access Batch account REJECTED = "Rejected" - #: The private endpoint connection is disconnected and cannot be used to access Batch account. + #: The private endpoint connection is disconnected and cannot be used to access Batch account DISCONNECTED = "Disconnected" -class ProvisioningState(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): - """The provisioned state of the resource - """ + +class ProvisioningState(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The provisioned state of the resource.""" #: The account is in an invalid state. INVALID = "Invalid" @@ -380,9 +403,9 @@ class ProvisioningState(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): #: The last operation for the account is cancelled. CANCELLED = "Cancelled" -class PublicNetworkAccessType(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): - """The network access type for operating on the resources in the Batch account. - """ + +class PublicNetworkAccessType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The network access type for operating on the resources in the Batch account.""" #: Enables connectivity to Azure Batch through public DNS. ENABLED = "Enabled" @@ -390,9 +413,9 @@ class PublicNetworkAccessType(with_metaclass(CaseInsensitiveEnumMeta, str, Enum) #: private endpoint resource. DISABLED = "Disabled" -class ResourceIdentityType(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): - """The type of identity used for the Batch account. - """ + +class ResourceIdentityType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The type of identity used for the Batch account.""" #: Batch account has a system assigned identity with it. SYSTEM_ASSIGNED = "SystemAssigned" @@ -402,9 +425,9 @@ class ResourceIdentityType(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): #: remove existing identities. NONE = "None" -class StorageAccountType(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): - """The storage account type for use in creating data disks. - """ + +class StorageAccountType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The storage account type for use in creating data disks.""" #: The data disk should use standard locally redundant storage. STANDARD_LRS = "Standard_LRS" diff --git a/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/models/_models_py3.py b/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/models/_models_py3.py index e0a569a0d8da..d8e8458841c5 100644 --- a/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/models/_models_py3.py +++ b/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/models/_models_py3.py @@ -1,4 +1,5 @@ # coding=utf-8 +# pylint: disable=too-many-lines # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. @@ -7,45 +8,53 @@ # -------------------------------------------------------------------------- import datetime -from typing import Any, Dict, List, Optional, Union +import sys +from typing import Any, Dict, List, Optional, TYPE_CHECKING, Union -import msrest.serialization +from .. import _serialization -from ._batch_management_client_enums import * +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(msrest.serialization.Model): + +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: Required. The format of the application package binary file. + :ivar format: The format of the application package binary file. Required. :vartype format: str """ _validation = { - 'format': {'required': True}, + "format": {"required": True}, } _attribute_map = { - 'format': {'key': 'format', 'type': 'str'}, + "format": {"key": "format", "type": "str"}, } - def __init__( - self, - *, - format: str, - **kwargs - ): + def __init__(self, *, format: str, **kwargs): """ - :keyword format: Required. The format of the application package binary file. + :keyword format: The format of the application package binary file. Required. :paramtype format: str """ - super(ActivateApplicationPackageParameters, self).__init__(**kwargs) + super().__init__(**kwargs) self.format = format -class ProxyResource(msrest.serialization.Model): +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. @@ -61,26 +70,22 @@ class ProxyResource(msrest.serialization.Model): """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'etag': {'readonly': True}, + "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'}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "etag": {"key": "etag", "type": "str"}, } - def __init__( - self, - **kwargs - ): - """ - """ - super(ProxyResource, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.id = None self.name = None self.type = None @@ -111,20 +116,20 @@ class Application(ProxyResource): """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'etag': {'readonly': True}, + "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'}, + "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__( @@ -145,7 +150,7 @@ def __init__( specify a version. This property can only be set to the name of an existing package. :paramtype default_version: str """ - super(Application, self).__init__(**kwargs) + super().__init__(**kwargs) self.display_name = display_name self.allow_updates = allow_updates self.default_version = default_version @@ -164,7 +169,7 @@ class ApplicationPackage(ProxyResource): :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. Possible values include: "Pending", + :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. @@ -179,36 +184,32 @@ class ApplicationPackage(ProxyResource): """ _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}, + "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 - ): - """ - """ - super(ApplicationPackage, self).__init__(**kwargs) + "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): + """ """ + super().__init__(**kwargs) self.state = None self.format = None self.storage_url = None @@ -216,14 +217,14 @@ def __init__( self.last_activation_time = None -class ApplicationPackageReference(msrest.serialization.Model): +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: Required. 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. + :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 @@ -232,42 +233,36 @@ class ApplicationPackageReference(msrest.serialization.Model): """ _validation = { - 'id': {'required': True}, + "id": {"required": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'version': {'key': 'version', 'type': 'str'}, + "id": {"key": "id", "type": "str"}, + "version": {"key": "version", "type": "str"}, } - def __init__( - self, - *, - id: str, - version: Optional[str] = None, - **kwargs - ): + def __init__(self, *, id: str, version: Optional[str] = None, **kwargs): # pylint: disable=redefined-builtin """ - :keyword id: Required. 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. + :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(ApplicationPackageReference, self).__init__(**kwargs) + super().__init__(**kwargs) self.id = id self.version = version -class AutoScaleRun(msrest.serialization.Model): +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: Required. The time at which the autoscale formula was last evaluated. + :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. @@ -277,13 +272,13 @@ class AutoScaleRun(msrest.serialization.Model): """ _validation = { - 'evaluation_time': {'required': True}, + "evaluation_time": {"required": True}, } _attribute_map = { - 'evaluation_time': {'key': 'evaluationTime', 'type': 'iso-8601'}, - 'results': {'key': 'results', 'type': 'str'}, - 'error': {'key': 'error', 'type': 'AutoScaleRunError'}, + "evaluation_time": {"key": "evaluationTime", "type": "iso-8601"}, + "results": {"key": "results", "type": "str"}, + "error": {"key": "error", "type": "AutoScaleRunError"}, } def __init__( @@ -291,11 +286,11 @@ def __init__( *, evaluation_time: datetime.datetime, results: Optional[str] = None, - error: Optional["AutoScaleRunError"] = None, + error: Optional["_models.AutoScaleRunError"] = None, **kwargs ): """ - :keyword evaluation_time: Required. The time at which the autoscale formula was last evaluated. + :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. @@ -303,111 +298,99 @@ def __init__( :keyword error: An error that occurred when autoscaling a pool. :paramtype error: ~azure.mgmt.batch.models.AutoScaleRunError """ - super(AutoScaleRun, self).__init__(**kwargs) + super().__init__(**kwargs) self.evaluation_time = evaluation_time self.results = results self.error = error -class AutoScaleRunError(msrest.serialization.Model): +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: Required. An identifier for the error. Codes are invariant and are intended to be - consumed programmatically. + :ivar code: An identifier for the error. Codes are invariant and are intended to be consumed + programmatically. Required. :vartype code: str - :ivar message: Required. A message describing the error, intended to be suitable for display in - a user interface. + :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}, + "code": {"required": True}, + "message": {"required": True}, } _attribute_map = { - 'code': {'key': 'code', 'type': 'str'}, - 'message': {'key': 'message', 'type': 'str'}, - 'details': {'key': 'details', 'type': '[AutoScaleRunError]'}, + "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["AutoScaleRunError"]] = None, - **kwargs + self, *, code: str, message: str, details: Optional[List["_models.AutoScaleRunError"]] = None, **kwargs ): """ - :keyword code: Required. An identifier for the error. Codes are invariant and are intended to - be consumed programmatically. + :keyword code: An identifier for the error. Codes are invariant and are intended to be consumed + programmatically. Required. :paramtype code: str - :keyword message: Required. A message describing the error, intended to be suitable for display - in a user interface. + :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(AutoScaleRunError, self).__init__(**kwargs) + super().__init__(**kwargs) self.code = code self.message = message self.details = details -class AutoScaleSettings(msrest.serialization.Model): +class AutoScaleSettings(_serialization.Model): """AutoScale settings for the pool. All required parameters must be populated in order to send to Azure. - :ivar formula: Required. A formula for the desired number of compute nodes in the pool. + :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}, + "formula": {"required": True}, } _attribute_map = { - 'formula': {'key': 'formula', 'type': 'str'}, - 'evaluation_interval': {'key': 'evaluationInterval', 'type': 'duration'}, + "formula": {"key": "formula", "type": "str"}, + "evaluation_interval": {"key": "evaluationInterval", "type": "duration"}, } - def __init__( - self, - *, - formula: str, - evaluation_interval: Optional[datetime.timedelta] = None, - **kwargs - ): + def __init__(self, *, formula: str, evaluation_interval: Optional[datetime.timedelta] = None, **kwargs): """ - :keyword formula: Required. A formula for the desired number of compute nodes in the pool. + :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(AutoScaleSettings, self).__init__(**kwargs) + super().__init__(**kwargs) self.formula = formula self.evaluation_interval = evaluation_interval -class AutoStorageBaseProperties(msrest.serialization.Model): +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: Required. The resource ID of the storage account to be used for - auto-storage account. + :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. Possible values include: "StorageKeys", - "BatchAccountManagedIdentity". Default value: "StorageKeys". + 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. @@ -415,36 +398,36 @@ class AutoStorageBaseProperties(msrest.serialization.Model): """ _validation = { - 'storage_account_id': {'required': True}, + "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'}, + "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: Optional[Union[str, "AutoStorageAuthenticationMode"]] = "StorageKeys", - node_identity_reference: Optional["ComputeNodeIdentityReference"] = None, + authentication_mode: Union[str, "_models.AutoStorageAuthenticationMode"] = "StorageKeys", + node_identity_reference: Optional["_models.ComputeNodeIdentityReference"] = None, **kwargs ): """ - :keyword storage_account_id: Required. The resource ID of the storage account to be used for - auto-storage account. + :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. Possible values include: "StorageKeys", - "BatchAccountManagedIdentity". Default value: "StorageKeys". + 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(AutoStorageBaseProperties, self).__init__(**kwargs) + super().__init__(**kwargs) self.storage_account_id = storage_account_id self.authentication_mode = authentication_mode self.node_identity_reference = node_identity_reference @@ -455,31 +438,30 @@ class AutoStorageProperties(AutoStorageBaseProperties): All required parameters must be populated in order to send to Azure. - :ivar storage_account_id: Required. The resource ID of the storage account to be used for - auto-storage account. + :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. Possible values include: "StorageKeys", - "BatchAccountManagedIdentity". Default value: "StorageKeys". + 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: Required. The UTC time at which storage keys were last synchronized with - the Batch account. + :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}, + "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'}, + "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__( @@ -487,53 +469,57 @@ def __init__( *, storage_account_id: str, last_key_sync: datetime.datetime, - authentication_mode: Optional[Union[str, "AutoStorageAuthenticationMode"]] = "StorageKeys", - node_identity_reference: Optional["ComputeNodeIdentityReference"] = None, + authentication_mode: Union[str, "_models.AutoStorageAuthenticationMode"] = "StorageKeys", + node_identity_reference: Optional["_models.ComputeNodeIdentityReference"] = None, **kwargs ): """ - :keyword storage_account_id: Required. The resource ID of the storage account to be used for - auto-storage account. + :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. Possible values include: "StorageKeys", - "BatchAccountManagedIdentity". Default value: "StorageKeys". + 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: Required. The UTC time at which storage keys were last synchronized - with the Batch account. + :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(AutoStorageProperties, self).__init__(storage_account_id=storage_account_id, authentication_mode=authentication_mode, node_identity_reference=node_identity_reference, **kwargs) + 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(msrest.serialization.Model): +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. Possible values include: "Task", "Pool". + tasks. Known values are: "Task" and "Pool". :vartype scope: str or ~azure.mgmt.batch.models.AutoUserScope - :ivar elevation_level: The default value is nonAdmin. Possible values include: "NonAdmin", - "Admin". + :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'}, + "scope": {"key": "scope", "type": "str"}, + "elevation_level": {"key": "elevationLevel", "type": "str"}, } def __init__( self, *, - scope: Optional[Union[str, "AutoUserScope"]] = None, - elevation_level: Optional[Union[str, "ElevationLevel"]] = None, + scope: Optional[Union[str, "_models.AutoUserScope"]] = None, + elevation_level: Optional[Union[str, "_models.ElevationLevel"]] = None, **kwargs ): """ @@ -541,25 +527,25 @@ def __init__( 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. Possible values include: "Task", "Pool". + 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. Possible values include: "NonAdmin", + :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(AutoUserSpecification, self).__init__(**kwargs) + super().__init__(**kwargs) self.scope = scope self.elevation_level = elevation_level -class AzureBlobFileSystemConfiguration(msrest.serialization.Model): +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: Required. The Azure Storage Account name. + :ivar account_name: The Azure Storage Account name. Required. :vartype account_name: str - :ivar container_name: Required. The Azure Blob Storage Container name. + :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. @@ -569,8 +555,8 @@ class AzureBlobFileSystemConfiguration(msrest.serialization.Model): :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: Required. All file systems are mounted relative to the Batch mounts - directory, accessible via the AZ_BATCH_NODE_MOUNTS_DIR environment variable. + :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. @@ -578,19 +564,19 @@ class AzureBlobFileSystemConfiguration(msrest.serialization.Model): """ _validation = { - 'account_name': {'required': True}, - 'container_name': {'required': True}, - 'relative_mount_path': {'required': True}, + "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'}, + "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__( @@ -602,13 +588,13 @@ def __init__( account_key: Optional[str] = None, sas_key: Optional[str] = None, blobfuse_options: Optional[str] = None, - identity_reference: Optional["ComputeNodeIdentityReference"] = None, + identity_reference: Optional["_models.ComputeNodeIdentityReference"] = None, **kwargs ): """ - :keyword account_name: Required. The Azure Storage Account name. + :keyword account_name: The Azure Storage Account name. Required. :paramtype account_name: str - :keyword container_name: Required. The Azure Blob Storage Container name. + :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. @@ -618,14 +604,14 @@ def __init__( :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: Required. All file systems are mounted relative to the Batch - mounts directory, accessible via the AZ_BATCH_NODE_MOUNTS_DIR environment variable. + :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(AzureBlobFileSystemConfiguration, self).__init__(**kwargs) + super().__init__(**kwargs) self.account_name = account_name self.container_name = container_name self.account_key = account_key @@ -635,37 +621,36 @@ def __init__( self.identity_reference = identity_reference -class AzureFileShareConfiguration(msrest.serialization.Model): +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: Required. The Azure Storage account name. + :ivar account_name: The Azure Storage account name. Required. :vartype account_name: str - :ivar azure_file_url: Required. This is of the form 'https://{account}.file.core.windows.net/'. + :ivar azure_file_url: This is of the form 'https://{account}.file.core.windows.net/'. Required. :vartype azure_file_url: str - :ivar account_key: Required. The Azure Storage account key. + :ivar account_key: The Azure Storage account key. :vartype account_key: str - :ivar relative_mount_path: Required. All file systems are mounted relative to the Batch mounts - directory, accessible via the AZ_BATCH_NODE_MOUNTS_DIR environment variable. + :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}, + "account_name": {"required": True}, + "azure_file_url": {"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'}, + "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__( @@ -673,26 +658,26 @@ def __init__( *, account_name: str, azure_file_url: str, - account_key: str, relative_mount_path: str, + account_key: Optional[str] = None, mount_options: Optional[str] = None, **kwargs ): """ - :keyword account_name: Required. The Azure Storage account name. + :keyword account_name: The Azure Storage account name. Required. :paramtype account_name: str - :keyword azure_file_url: Required. This is of the form - 'https://{account}.file.core.windows.net/'. + :keyword azure_file_url: This is of the form 'https://{account}.file.core.windows.net/'. + Required. :paramtype azure_file_url: str - :keyword account_key: Required. The Azure Storage account key. + :keyword account_key: The Azure Storage account key. :paramtype account_key: str - :keyword relative_mount_path: Required. All file systems are mounted relative to the Batch - mounts directory, accessible via the AZ_BATCH_NODE_MOUNTS_DIR environment variable. + :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(AzureFileShareConfiguration, self).__init__(**kwargs) + super().__init__(**kwargs) self.account_name = account_name self.azure_file_url = azure_file_url self.account_key = account_key @@ -700,7 +685,7 @@ def __init__( self.mount_options = mount_options -class Resource(msrest.serialization.Model): +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. @@ -713,33 +698,29 @@ class Resource(msrest.serialization.Model): :vartype type: str :ivar location: The location of the resource. :vartype location: str - :ivar tags: A set of tags. The tags of the resource. + :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}, + "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}'}, + "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) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.id = None self.name = None self.type = None @@ -747,7 +728,7 @@ def __init__( self.tags = None -class BatchAccount(Resource): +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. @@ -760,7 +741,7 @@ class BatchAccount(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. + :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 @@ -769,16 +750,16 @@ class BatchAccount(Resource): :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. Possible values include: - "Invalid", "Creating", "Deleting", "Succeeded", "Failed", "Cancelled". + :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. - Possible values include: "BatchService", "UserSubscription". + :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'. Possible values - include: "Enabled", "Disabled". Default value: "Enabled". + :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. @@ -821,73 +802,82 @@ class BatchAccount(Resource): """ _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}, + "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]'}, + "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["BatchAccountIdentity"] = None, - public_network_access: Optional[Union[str, "PublicNetworkAccessType"]] = "Enabled", - network_profile: Optional["NetworkProfile"] = None, + identity: Optional["_models.BatchAccountIdentity"] = None, + public_network_access: Union[str, "_models.PublicNetworkAccessType"] = "Enabled", + network_profile: Optional["_models.NetworkProfile"] = None, **kwargs ): """ :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'. Possible - values include: "Enabled", "Disabled". Default value: "Enabled". + :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(BatchAccount, self).__init__(**kwargs) + super().__init__(**kwargs) self.identity = identity self.account_endpoint = None self.node_management_endpoint = None @@ -908,14 +898,14 @@ def __init__( self.allowed_authentication_modes = None -class BatchAccountCreateParameters(msrest.serialization.Model): +class BatchAccountCreateParameters(_serialization.Model): """Parameters supplied to the Create operation. All required parameters must be populated in order to send to Azure. - :ivar location: Required. The region in which to create the account. + :ivar location: The region in which to create the account. Required. :vartype location: str - :ivar tags: A set of tags. The user-specified tags associated with the 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 @@ -924,14 +914,14 @@ class BatchAccountCreateParameters(msrest.serialization.Model): :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. Possible values include: "BatchService", + 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'. Possible values - include: "Enabled", "Disabled". Default value: "Enabled". + :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. @@ -947,20 +937,20 @@ class BatchAccountCreateParameters(msrest.serialization.Model): """ _validation = { - 'location': {'required': True}, + "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]'}, + "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__( @@ -968,20 +958,20 @@ def __init__( *, location: str, tags: Optional[Dict[str, str]] = None, - identity: Optional["BatchAccountIdentity"] = None, - auto_storage: Optional["AutoStorageBaseProperties"] = None, - pool_allocation_mode: Optional[Union[str, "PoolAllocationMode"]] = None, - key_vault_reference: Optional["KeyVaultReference"] = None, - public_network_access: Optional[Union[str, "PublicNetworkAccessType"]] = "Enabled", - network_profile: Optional["NetworkProfile"] = None, - encryption: Optional["EncryptionProperties"] = None, - allowed_authentication_modes: Optional[List[Union[str, "AuthenticationMode"]]] = 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 ): """ - :keyword location: Required. The region in which to create the account. + :keyword location: The region in which to create the account. Required. :paramtype location: str - :keyword tags: A set of tags. The user-specified tags associated with the account. + :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 @@ -990,14 +980,14 @@ def __init__( :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. Possible values include: "BatchService", + 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'. Possible - values include: "Enabled", "Disabled". Default value: "Enabled". + :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. @@ -1012,7 +1002,7 @@ def __init__( :paramtype allowed_authentication_modes: list[str or ~azure.mgmt.batch.models.AuthenticationMode] """ - super(BatchAccountCreateParameters, self).__init__(**kwargs) + super().__init__(**kwargs) self.location = location self.tags = tags self.identity = identity @@ -1025,7 +1015,7 @@ def __init__( self.allowed_authentication_modes = allowed_authentication_modes -class BatchAccountIdentity(msrest.serialization.Model): +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. @@ -1038,49 +1028,49 @@ class BatchAccountIdentity(msrest.serialization.Model): :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: Required. The type of identity used for the Batch account. Possible values include: - "SystemAssigned", "UserAssigned", "None". + :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}, + "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}'}, + "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, "ResourceIdentityType"], - user_assigned_identities: Optional[Dict[str, "UserAssignedIdentities"]] = None, + type: Union[str, "_models.ResourceIdentityType"], + user_assigned_identities: Optional[Dict[str, "_models.UserAssignedIdentities"]] = None, **kwargs ): """ - :keyword type: Required. The type of identity used for the Batch account. Possible values - include: "SystemAssigned", "UserAssigned", "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(BatchAccountIdentity, self).__init__(**kwargs) + super().__init__(**kwargs) self.principal_id = None self.tenant_id = None self.type = type self.user_assigned_identities = user_assigned_identities -class BatchAccountKeys(msrest.serialization.Model): +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. @@ -1094,30 +1084,26 @@ class BatchAccountKeys(msrest.serialization.Model): """ _validation = { - 'account_name': {'readonly': True}, - 'primary': {'readonly': True}, - 'secondary': {'readonly': True}, + "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'}, + "account_name": {"key": "accountName", "type": "str"}, + "primary": {"key": "primary", "type": "str"}, + "secondary": {"key": "secondary", "type": "str"}, } - def __init__( - self, - **kwargs - ): - """ - """ - super(BatchAccountKeys, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.account_name = None self.primary = None self.secondary = None -class BatchAccountListResult(msrest.serialization.Model): +class BatchAccountListResult(_serialization.Model): """Values returned by the List operation. :ivar value: The collection of Batch accounts returned by the listing operation. @@ -1127,16 +1113,12 @@ class BatchAccountListResult(msrest.serialization.Model): """ _attribute_map = { - 'value': {'key': 'value', 'type': '[BatchAccount]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "value": {"key": "value", "type": "[BatchAccount]"}, + "next_link": {"key": "nextLink", "type": "str"}, } def __init__( - self, - *, - value: Optional[List["BatchAccount"]] = None, - next_link: Optional[str] = None, - **kwargs + self, *, value: Optional[List["_models.BatchAccount"]] = None, next_link: Optional[str] = None, **kwargs ): """ :keyword value: The collection of Batch accounts returned by the listing operation. @@ -1144,48 +1126,43 @@ def __init__( :keyword next_link: The continuation token. :paramtype next_link: str """ - super(BatchAccountListResult, self).__init__(**kwargs) + super().__init__(**kwargs) self.value = value self.next_link = next_link -class BatchAccountRegenerateKeyParameters(msrest.serialization.Model): +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: Required. The type of account key to regenerate. Possible values include: - "Primary", "Secondary". + :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}, + "key_name": {"required": True}, } _attribute_map = { - 'key_name': {'key': 'keyName', 'type': 'str'}, + "key_name": {"key": "keyName", "type": "str"}, } - def __init__( - self, - *, - key_name: Union[str, "AccountKeyType"], - **kwargs - ): + def __init__(self, *, key_name: Union[str, "_models.AccountKeyType"], **kwargs): """ - :keyword key_name: Required. The type of account key to regenerate. Possible values include: - "Primary", "Secondary". + :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(BatchAccountRegenerateKeyParameters, self).__init__(**kwargs) + super().__init__(**kwargs) self.key_name = key_name -class BatchAccountUpdateParameters(msrest.serialization.Model): +class BatchAccountUpdateParameters(_serialization.Model): """Parameters for updating an Azure Batch account. - :ivar tags: A set of tags. The user-specified tags associated with the 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 @@ -1199,8 +1176,8 @@ class BatchAccountUpdateParameters(msrest.serialization.Model): 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'. Possible values - include: "Enabled", "Disabled". Default value: "Enabled". + :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. @@ -1208,29 +1185,29 @@ class BatchAccountUpdateParameters(msrest.serialization.Model): """ _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'}, + "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["BatchAccountIdentity"] = None, - auto_storage: Optional["AutoStorageBaseProperties"] = None, - encryption: Optional["EncryptionProperties"] = None, - allowed_authentication_modes: Optional[List[Union[str, "AuthenticationMode"]]] = None, - public_network_access: Optional[Union[str, "PublicNetworkAccessType"]] = "Enabled", - network_profile: Optional["NetworkProfile"] = 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 ): """ - :keyword tags: A set of tags. The user-specified tags associated with the account. + :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 @@ -1245,14 +1222,14 @@ def __init__( 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'. Possible - values include: "Enabled", "Disabled". Default value: "Enabled". + :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(BatchAccountUpdateParameters, self).__init__(**kwargs) + super().__init__(**kwargs) self.tags = tags self.identity = identity self.auto_storage = auto_storage @@ -1262,7 +1239,7 @@ def __init__( self.network_profile = network_profile -class BatchLocationQuota(msrest.serialization.Model): +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. @@ -1273,64 +1250,60 @@ class BatchLocationQuota(msrest.serialization.Model): """ _validation = { - 'account_quota': {'readonly': True}, + "account_quota": {"readonly": True}, } _attribute_map = { - 'account_quota': {'key': 'accountQuota', 'type': 'int'}, + "account_quota": {"key": "accountQuota", "type": "int"}, } - def __init__( - self, - **kwargs - ): - """ - """ - super(BatchLocationQuota, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.account_quota = None -class BatchPoolIdentity(msrest.serialization.Model): +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: Required. The type of identity used for the Batch Pool. Possible values include: - "UserAssigned", "None". + :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}, + "type": {"required": True}, } _attribute_map = { - 'type': {'key': 'type', 'type': 'str'}, - 'user_assigned_identities': {'key': 'userAssignedIdentities', 'type': '{UserAssignedIdentities}'}, + "type": {"key": "type", "type": "str"}, + "user_assigned_identities": {"key": "userAssignedIdentities", "type": "{UserAssignedIdentities}"}, } def __init__( self, *, - type: Union[str, "PoolIdentityType"], - user_assigned_identities: Optional[Dict[str, "UserAssignedIdentities"]] = None, + type: Union[str, "_models.PoolIdentityType"], + user_assigned_identities: Optional[Dict[str, "_models.UserAssignedIdentities"]] = None, **kwargs ): """ - :keyword type: Required. The type of identity used for the Batch Pool. Possible values include: - "UserAssigned", "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(BatchPoolIdentity, self).__init__(**kwargs) + super().__init__(**kwargs) self.type = type self.user_assigned_identities = user_assigned_identities -class Certificate(ProxyResource): +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. @@ -1349,15 +1322,15 @@ class Certificate(ProxyResource): :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. Possible values include: "Pfx", "Cer". + Pfx. Known values are: "Pfx" and "Cer". :vartype format: str or ~azure.mgmt.batch.models.CertificateFormat - :ivar provisioning_state: Possible values include: "Succeeded", "Deleting", "Failed". + :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. Possible - values include: "Succeeded", "Deleting", "Failed". + :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 @@ -1371,32 +1344,35 @@ class Certificate(ProxyResource): """ _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}, + "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'}, + "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__( @@ -1404,7 +1380,7 @@ def __init__( *, thumbprint_algorithm: Optional[str] = None, thumbprint: Optional[str] = None, - format: Optional[Union[str, "CertificateFormat"]] = None, + format: Optional[Union[str, "_models.CertificateFormat"]] = None, **kwargs ): """ @@ -1414,10 +1390,10 @@ def __init__( :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. Possible values include: "Pfx", "Cer". + Pfx. Known values are: "Pfx" and "Cer". :paramtype format: str or ~azure.mgmt.batch.models.CertificateFormat """ - super(Certificate, self).__init__(**kwargs) + super().__init__(**kwargs) self.thumbprint_algorithm = thumbprint_algorithm self.thumbprint = thumbprint self.format = format @@ -1429,7 +1405,7 @@ def __init__( self.delete_certificate_error = None -class CertificateBaseProperties(msrest.serialization.Model): +class CertificateBaseProperties(_serialization.Model): """Base certificate properties. :ivar thumbprint_algorithm: This must match the first portion of the certificate name. @@ -1438,14 +1414,14 @@ class CertificateBaseProperties(msrest.serialization.Model): :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. Possible values include: "Pfx", "Cer". + 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'}, + "thumbprint_algorithm": {"key": "thumbprintAlgorithm", "type": "str"}, + "thumbprint": {"key": "thumbprint", "type": "str"}, + "format": {"key": "format", "type": "str"}, } def __init__( @@ -1453,7 +1429,7 @@ def __init__( *, thumbprint_algorithm: Optional[str] = None, thumbprint: Optional[str] = None, - format: Optional[Union[str, "CertificateFormat"]] = None, + format: Optional[Union[str, "_models.CertificateFormat"]] = None, **kwargs ): """ @@ -1463,10 +1439,10 @@ def __init__( :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. Possible values include: "Pfx", "Cer". + Pfx. Known values are: "Pfx" and "Cer". :paramtype format: str or ~azure.mgmt.batch.models.CertificateFormat """ - super(CertificateBaseProperties, self).__init__(**kwargs) + super().__init__(**kwargs) self.thumbprint_algorithm = thumbprint_algorithm self.thumbprint = thumbprint self.format = format @@ -1491,7 +1467,7 @@ class CertificateCreateOrUpdateParameters(ProxyResource): :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. Possible values include: "Pfx", "Cer". + 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 @@ -1500,22 +1476,22 @@ class CertificateCreateOrUpdateParameters(ProxyResource): """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'etag': {'readonly': True}, + "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'}, + "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__( @@ -1523,7 +1499,7 @@ def __init__( *, thumbprint_algorithm: Optional[str] = None, thumbprint: Optional[str] = None, - format: Optional[Union[str, "CertificateFormat"]] = None, + format: Optional[Union[str, "_models.CertificateFormat"]] = None, data: Optional[str] = None, password: Optional[str] = None, **kwargs @@ -1535,14 +1511,14 @@ def __init__( :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. Possible values include: "Pfx", "Cer". + 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(CertificateCreateOrUpdateParameters, self).__init__(**kwargs) + super().__init__(**kwargs) self.thumbprint_algorithm = thumbprint_algorithm self.thumbprint = thumbprint self.format = format @@ -1561,24 +1537,24 @@ class CertificateCreateOrUpdateProperties(CertificateBaseProperties): :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. Possible values include: "Pfx", "Cer". + Pfx. Known values are: "Pfx" and "Cer". :vartype format: str or ~azure.mgmt.batch.models.CertificateFormat - :ivar data: Required. The maximum size is 10KB. + :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}, + "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'}, + "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__( @@ -1587,7 +1563,7 @@ def __init__( data: str, thumbprint_algorithm: Optional[str] = None, thumbprint: Optional[str] = None, - format: Optional[Union[str, "CertificateFormat"]] = None, + format: Optional[Union[str, "_models.CertificateFormat"]] = None, password: Optional[str] = None, **kwargs ): @@ -1598,14 +1574,14 @@ def __init__( :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. Possible values include: "Pfx", "Cer". + Pfx. Known values are: "Pfx" and "Cer". :paramtype format: str or ~azure.mgmt.batch.models.CertificateFormat - :keyword data: Required. The maximum size is 10KB. + :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(CertificateCreateOrUpdateProperties, self).__init__(thumbprint_algorithm=thumbprint_algorithm, thumbprint=thumbprint, format=format, **kwargs) + super().__init__(thumbprint_algorithm=thumbprint_algorithm, thumbprint=thumbprint, format=format, **kwargs) self.data = data self.password = password @@ -1621,15 +1597,15 @@ class CertificateProperties(CertificateBaseProperties): :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. Possible values include: "Pfx", "Cer". + Pfx. Known values are: "Pfx" and "Cer". :vartype format: str or ~azure.mgmt.batch.models.CertificateFormat - :ivar provisioning_state: Possible values include: "Succeeded", "Deleting", "Failed". + :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. Possible - values include: "Succeeded", "Deleting", "Failed". + :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 @@ -1643,24 +1619,27 @@ class CertificateProperties(CertificateBaseProperties): """ _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}, + "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'}, + "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__( @@ -1668,7 +1647,7 @@ def __init__( *, thumbprint_algorithm: Optional[str] = None, thumbprint: Optional[str] = None, - format: Optional[Union[str, "CertificateFormat"]] = None, + format: Optional[Union[str, "_models.CertificateFormat"]] = None, **kwargs ): """ @@ -1678,10 +1657,10 @@ def __init__( :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. Possible values include: "Pfx", "Cer". + Pfx. Known values are: "Pfx" and "Cer". :paramtype format: str or ~azure.mgmt.batch.models.CertificateFormat """ - super(CertificateProperties, self).__init__(thumbprint_algorithm=thumbprint_algorithm, thumbprint=thumbprint, format=format, **kwargs) + 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 @@ -1690,13 +1669,13 @@ def __init__( self.delete_certificate_error = None -class CertificateReference(msrest.serialization.Model): - """A reference to a certificate to be installed on compute nodes in a pool. This must exist inside the same account as the pool. +class CertificateReference(_serialization.Model): + """Warning: This object is deprecated and will be removed after February, 2024. Please use the `Azure KeyVault Extension `_ instead. All required parameters must be populated in order to send to Azure. - :ivar id: Required. The fully qualified ID of the certificate to install on the pool. This must - be inside the same batch account as the pool. + :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 @@ -1704,8 +1683,8 @@ class CertificateReference(msrest.serialization.Model): 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. - Possible values include: "CurrentUser", "LocalMachine". + 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 @@ -1719,28 +1698,28 @@ class CertificateReference(msrest.serialization.Model): """ _validation = { - 'id': {'required': True}, + "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]'}, + "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, - store_location: Optional[Union[str, "CertificateStoreLocation"]] = None, + id: str, # pylint: disable=redefined-builtin + store_location: Optional[Union[str, "_models.CertificateStoreLocation"]] = None, store_name: Optional[str] = None, - visibility: Optional[List[Union[str, "CertificateVisibility"]]] = None, + visibility: Optional[List[Union[str, "_models.CertificateVisibility"]]] = None, **kwargs ): """ - :keyword id: Required. The fully qualified ID of the certificate to install on the pool. This - must be inside the same batch account as the pool. + :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 @@ -1748,8 +1727,8 @@ def __init__( 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. - Possible values include: "CurrentUser", "LocalMachine". + 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 @@ -1761,53 +1740,48 @@ def __init__( data of the certificate. :paramtype visibility: list[str or ~azure.mgmt.batch.models.CertificateVisibility] """ - super(CertificateReference, self).__init__(**kwargs) + super().__init__(**kwargs) self.id = id self.store_location = store_location self.store_name = store_name self.visibility = visibility -class CheckNameAvailabilityParameters(msrest.serialization.Model): +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: Required. The name to check for availability. + :ivar name: The name to check for availability. Required. :vartype name: str - :ivar type: The resource type. Has constant value: "Microsoft.Batch/batchAccounts". + :ivar type: The resource type. Required. Default value is "Microsoft.Batch/batchAccounts". :vartype type: str """ _validation = { - 'name': {'required': True}, - 'type': {'required': True, 'constant': True}, + "name": {"required": True}, + "type": {"required": True, "constant": True}, } _attribute_map = { - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, } type = "Microsoft.Batch/batchAccounts" - def __init__( - self, - *, - name: str, - **kwargs - ): + def __init__(self, *, name: str, **kwargs): """ - :keyword name: Required. The name to check for availability. + :keyword name: The name to check for availability. Required. :paramtype name: str """ - super(CheckNameAvailabilityParameters, self).__init__(**kwargs) + super().__init__(**kwargs) self.name = name -class CheckNameAvailabilityResult(msrest.serialization.Model): +class CheckNameAvailabilityResult(_serialization.Model): """The CheckNameAvailability operation response. Variables are only populated by the server, and will be ignored when sending a request. @@ -1817,103 +1791,97 @@ class CheckNameAvailabilityResult(msrest.serialization.Model): 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. Possible values include: "Invalid", - "AlreadyExists". + 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}, + "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'}, + "name_available": {"key": "nameAvailable", "type": "bool"}, + "reason": {"key": "reason", "type": "str"}, + "message": {"key": "message", "type": "str"}, } - def __init__( - self, - **kwargs - ): - """ - """ - super(CheckNameAvailabilityResult, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.name_available = None self.reason = None self.message = None -class CIFSMountConfiguration(msrest.serialization.Model): +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 username: Required. The user to use for authentication against the CIFS file system. - :vartype username: str - :ivar source: Required. The URI of the file system to mount. + :ivar user_name: The user to use for authentication against the CIFS file system. + :vartype user_name: str + :ivar source: The URI of the file system to mount. Required. :vartype source: str - :ivar relative_mount_path: Required. All file systems are mounted relative to the Batch mounts - directory, accessible via the AZ_BATCH_NODE_MOUNTS_DIR environment variable. + :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: Required. The password to use for authentication against the CIFS file system. + :ivar password: The password to use for authentication against the CIFS file system. Required. :vartype password: str """ _validation = { - 'username': {'required': True}, - 'source': {'required': True}, - 'relative_mount_path': {'required': True}, - 'password': {'required': True}, + "source": {"required": True}, + "relative_mount_path": {"required": True}, + "password": {"required": True}, } _attribute_map = { - 'username': {'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'}, + "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, *, - username: str, source: str, relative_mount_path: str, password: str, + user_name: Optional[str] = None, mount_options: Optional[str] = None, **kwargs ): """ - :keyword username: Required. The user to use for authentication against the CIFS file system. - :paramtype username: str - :keyword source: Required. The URI of the file system to mount. + :keyword user_name: The user to use for authentication against the CIFS file system. + :paramtype user_name: str + :keyword source: The URI of the file system to mount. Required. :paramtype source: str - :keyword relative_mount_path: Required. All file systems are mounted relative to the Batch - mounts directory, accessible via the AZ_BATCH_NODE_MOUNTS_DIR environment variable. + :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: Required. The password to use for authentication against the CIFS file - system. + :keyword password: The password to use for authentication against the CIFS file system. + Required. :paramtype password: str """ - super(CIFSMountConfiguration, self).__init__(**kwargs) - self.username = username + 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(msrest.serialization.Model): +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 @@ -1930,10 +1898,10 @@ class CloudErrorBody(msrest.serialization.Model): """ _attribute_map = { - 'code': {'key': 'code', 'type': 'str'}, - 'message': {'key': 'message', 'type': 'str'}, - 'target': {'key': 'target', 'type': 'str'}, - 'details': {'key': 'details', 'type': '[CloudErrorBody]'}, + "code": {"key": "code", "type": "str"}, + "message": {"key": "message", "type": "str"}, + "target": {"key": "target", "type": "str"}, + "details": {"key": "details", "type": "[CloudErrorBody]"}, } def __init__( @@ -1942,7 +1910,7 @@ def __init__( code: Optional[str] = None, message: Optional[str] = None, target: Optional[str] = None, - details: Optional[List["CloudErrorBody"]] = None, + details: Optional[List["_models.CloudErrorBody"]] = None, **kwargs ): """ @@ -1958,23 +1926,24 @@ def __init__( :keyword details: A list of additional details about the error. :paramtype details: list[~azure.mgmt.batch.models.CloudErrorBody] """ - super(CloudErrorBody, self).__init__(**kwargs) + super().__init__(**kwargs) self.code = code self.message = message self.target = target self.details = details -class CloudServiceConfiguration(msrest.serialization.Model): +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: Required. 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 + :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. @@ -1982,39 +1951,33 @@ class CloudServiceConfiguration(msrest.serialization.Model): """ _validation = { - 'os_family': {'required': True}, + "os_family": {"required": True}, } _attribute_map = { - 'os_family': {'key': 'osFamily', 'type': 'str'}, - 'os_version': {'key': 'osVersion', 'type': 'str'}, + "os_family": {"key": "osFamily", "type": "str"}, + "os_version": {"key": "osVersion", "type": "str"}, } - def __init__( - self, - *, - os_family: str, - os_version: Optional[str] = None, - **kwargs - ): + def __init__(self, *, os_family: str, os_version: Optional[str] = None, **kwargs): """ - :keyword os_family: Required. 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 + :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(CloudServiceConfiguration, self).__init__(**kwargs) + super().__init__(**kwargs) self.os_family = os_family self.os_version = os_version -class ComputeNodeIdentityReference(msrest.serialization.Model): +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. @@ -2022,31 +1985,26 @@ class ComputeNodeIdentityReference(msrest.serialization.Model): """ _attribute_map = { - 'resource_id': {'key': 'resourceId', 'type': 'str'}, + "resource_id": {"key": "resourceId", "type": "str"}, } - def __init__( - self, - *, - resource_id: Optional[str] = None, - **kwargs - ): + def __init__(self, *, resource_id: Optional[str] = None, **kwargs): """ :keyword resource_id: The ARM resource id of the user assigned identity. :paramtype resource_id: str """ - super(ComputeNodeIdentityReference, self).__init__(**kwargs) + super().__init__(**kwargs) self.resource_id = resource_id -class ContainerConfiguration(msrest.serialization.Model): +class ContainerConfiguration(_serialization.Model): """The configuration for container-enabled pools. 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 type: The container technology to be used. Has constant value: "DockerCompatible". + :ivar type: The container technology to be used. Required. Default value is "DockerCompatible". :vartype type: str :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 @@ -2058,13 +2016,13 @@ class ContainerConfiguration(msrest.serialization.Model): """ _validation = { - 'type': {'required': True, 'constant': True}, + "type": {"required": True, "constant": True}, } _attribute_map = { - 'type': {'key': 'type', 'type': 'str'}, - 'container_image_names': {'key': 'containerImageNames', 'type': '[str]'}, - 'container_registries': {'key': 'containerRegistries', 'type': '[ContainerRegistry]'}, + "type": {"key": "type", "type": "str"}, + "container_image_names": {"key": "containerImageNames", "type": "[str]"}, + "container_registries": {"key": "containerRegistries", "type": "[ContainerRegistry]"}, } type = "DockerCompatible" @@ -2073,7 +2031,7 @@ def __init__( self, *, container_image_names: Optional[List[str]] = None, - container_registries: Optional[List["ContainerRegistry"]] = None, + container_registries: Optional[List["_models.ContainerRegistry"]] = None, **kwargs ): """ @@ -2085,12 +2043,12 @@ def __init__( requires credentials, then those credentials must be provided here. :paramtype container_registries: list[~azure.mgmt.batch.models.ContainerRegistry] """ - super(ContainerConfiguration, self).__init__(**kwargs) + super().__init__(**kwargs) self.container_image_names = container_image_names self.container_registries = container_registries -class ContainerRegistry(msrest.serialization.Model): +class ContainerRegistry(_serialization.Model): """A private container registry. :ivar user_name: The user name to log into the registry server. @@ -2105,10 +2063,10 @@ class ContainerRegistry(msrest.serialization.Model): """ _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'}, + "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__( @@ -2117,7 +2075,7 @@ def __init__( user_name: Optional[str] = None, password: Optional[str] = None, registry_server: Optional[str] = None, - identity_reference: Optional["ComputeNodeIdentityReference"] = None, + identity_reference: Optional["_models.ComputeNodeIdentityReference"] = None, **kwargs ): """ @@ -2131,51 +2089,51 @@ def __init__( Batch pool which a compute node will use. :paramtype identity_reference: ~azure.mgmt.batch.models.ComputeNodeIdentityReference """ - super(ContainerRegistry, self).__init__(**kwargs) + super().__init__(**kwargs) self.user_name = user_name self.password = password self.registry_server = registry_server self.identity_reference = identity_reference -class DataDisk(msrest.serialization.Model): +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: Required. 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. + :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/. - Possible values include: "None", "ReadOnly", "ReadWrite". + Known values are: "None", "ReadOnly", and "ReadWrite". :vartype caching: str or ~azure.mgmt.batch.models.CachingType - :ivar disk_size_gb: Required. The initial disk size in GB when creating new data disk. + :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. Possible values - include: "Standard_LRS", "Premium_LRS". + 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}, + "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'}, + "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__( @@ -2183,50 +2141,50 @@ def __init__( *, lun: int, disk_size_gb: int, - caching: Optional[Union[str, "CachingType"]] = None, - storage_account_type: Optional[Union[str, "StorageAccountType"]] = None, + caching: Optional[Union[str, "_models.CachingType"]] = None, + storage_account_type: Optional[Union[str, "_models.StorageAccountType"]] = None, **kwargs ): """ - :keyword lun: Required. 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. + :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/. - Possible values include: "None", "ReadOnly", "ReadWrite". + Known values are: "None", "ReadOnly", and "ReadWrite". :paramtype caching: str or ~azure.mgmt.batch.models.CachingType - :keyword disk_size_gb: Required. The initial disk size in GB when creating new data disk. + :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. Possible values - include: "Standard_LRS", "Premium_LRS". + 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(DataDisk, self).__init__(**kwargs) + 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(msrest.serialization.Model): +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: Required. An identifier for the error. Codes are invariant and are intended to be - consumed programmatically. + :ivar code: An identifier for the error. Codes are invariant and are intended to be consumed + programmatically. Required. :vartype code: str - :ivar message: Required. A message describing the error, intended to be suitable for display in - a user interface. + :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. @@ -2236,15 +2194,15 @@ class DeleteCertificateError(msrest.serialization.Model): """ _validation = { - 'code': {'required': True}, - 'message': {'required': True}, + "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]'}, + "code": {"key": "code", "type": "str"}, + "message": {"key": "message", "type": "str"}, + "target": {"key": "target", "type": "str"}, + "details": {"key": "details", "type": "[DeleteCertificateError]"}, } def __init__( @@ -2253,15 +2211,15 @@ def __init__( code: str, message: str, target: Optional[str] = None, - details: Optional[List["DeleteCertificateError"]] = None, + details: Optional[List["_models.DeleteCertificateError"]] = None, **kwargs ): """ - :keyword code: Required. An identifier for the error. Codes are invariant and are intended to - be consumed programmatically. + :keyword code: An identifier for the error. Codes are invariant and are intended to be consumed + programmatically. Required. :paramtype code: str - :keyword message: Required. A message describing the error, intended to be suitable for display - in a user interface. + :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. @@ -2269,14 +2227,14 @@ def __init__( :keyword details: A list of additional details about the error. :paramtype details: list[~azure.mgmt.batch.models.DeleteCertificateError] """ - super(DeleteCertificateError, self).__init__(**kwargs) + super().__init__(**kwargs) self.code = code self.message = message self.target = target self.details = details -class DeploymentConfiguration(msrest.serialization.Model): +class DeploymentConfiguration(_serialization.Model): """Deployment configuration properties. :ivar cloud_service_configuration: This property and virtualMachineConfiguration are mutually @@ -2289,15 +2247,15 @@ class DeploymentConfiguration(msrest.serialization.Model): """ _attribute_map = { - 'cloud_service_configuration': {'key': 'cloudServiceConfiguration', 'type': 'CloudServiceConfiguration'}, - 'virtual_machine_configuration': {'key': 'virtualMachineConfiguration', 'type': 'VirtualMachineConfiguration'}, + "cloud_service_configuration": {"key": "cloudServiceConfiguration", "type": "CloudServiceConfiguration"}, + "virtual_machine_configuration": {"key": "virtualMachineConfiguration", "type": "VirtualMachineConfiguration"}, } def __init__( self, *, - cloud_service_configuration: Optional["CloudServiceConfiguration"] = None, - virtual_machine_configuration: Optional["VirtualMachineConfiguration"] = None, + cloud_service_configuration: Optional["_models.CloudServiceConfiguration"] = None, + virtual_machine_configuration: Optional["_models.VirtualMachineConfiguration"] = None, **kwargs ): """ @@ -2310,12 +2268,12 @@ def __init__( mutually exclusive and one of the properties must be specified. :paramtype virtual_machine_configuration: ~azure.mgmt.batch.models.VirtualMachineConfiguration """ - super(DeploymentConfiguration, self).__init__(**kwargs) + super().__init__(**kwargs) self.cloud_service_configuration = cloud_service_configuration self.virtual_machine_configuration = virtual_machine_configuration -class DetectorListResult(msrest.serialization.Model): +class DetectorListResult(_serialization.Model): """Values returned by the List operation. :ivar value: The collection of Batch account detectors returned by the listing operation. @@ -2325,16 +2283,12 @@ class DetectorListResult(msrest.serialization.Model): """ _attribute_map = { - 'value': {'key': 'value', 'type': '[DetectorResponse]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "value": {"key": "value", "type": "[DetectorResponse]"}, + "next_link": {"key": "nextLink", "type": "str"}, } def __init__( - self, - *, - value: Optional[List["DetectorResponse"]] = None, - next_link: Optional[str] = None, - **kwargs + self, *, value: Optional[List["_models.DetectorResponse"]] = None, next_link: Optional[str] = None, **kwargs ): """ :keyword value: The collection of Batch account detectors returned by the listing operation. @@ -2342,7 +2296,7 @@ def __init__( :keyword next_link: The URL to get the next set of results. :paramtype next_link: str """ - super(DetectorListResult, self).__init__(**kwargs) + super().__init__(**kwargs) self.value = value self.next_link = next_link @@ -2365,35 +2319,30 @@ class DetectorResponse(ProxyResource): """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'etag': {'readonly': True}, + "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'}, + "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 - ): + def __init__(self, *, value: Optional[str] = None, **kwargs): """ :keyword value: A base64 encoded string that represents the content of a detector. :paramtype value: str """ - super(DetectorResponse, self).__init__(**kwargs) + super().__init__(**kwargs) self.value = value -class DiffDiskSettings(msrest.serialization.Model): +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 @@ -2403,20 +2352,15 @@ class DiffDiskSettings(msrest.serialization.Model): 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. - The only acceptable values to pass in are None and "CacheDisk". The default value is None. + Default value is "CacheDisk". :vartype placement: str """ _attribute_map = { - 'placement': {'key': 'placement', 'type': 'str'}, + "placement": {"key": "placement", "type": "str"}, } - def __init__( - self, - *, - placement: Optional[str] = None, - **kwargs - ): + def __init__(self, *, placement: Optional[Literal["CacheDisk"]] = None, **kwargs): """ :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. @@ -2425,14 +2369,14 @@ def __init__( 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. - The only acceptable values to pass in are None and "CacheDisk". The default value is None. + Default value is "CacheDisk". :paramtype placement: str """ - super(DiffDiskSettings, self).__init__(**kwargs) + super().__init__(**kwargs) self.placement = placement -class DiskEncryptionConfiguration(msrest.serialization.Model): +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 @@ -2441,28 +2385,23 @@ class DiskEncryptionConfiguration(msrest.serialization.Model): """ _attribute_map = { - 'targets': {'key': 'targets', 'type': '[str]'}, + "targets": {"key": "targets", "type": "[str]"}, } - def __init__( - self, - *, - targets: Optional[List[Union[str, "DiskEncryptionTarget"]]] = None, - **kwargs - ): + def __init__(self, *, targets: Optional[List[Union[str, "_models.DiskEncryptionTarget"]]] = None, **kwargs): """ :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(DiskEncryptionConfiguration, self).__init__(**kwargs) + super().__init__(**kwargs) self.targets = targets -class EncryptionProperties(msrest.serialization.Model): +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. Possible values include: "Microsoft.Batch", + :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. @@ -2470,70 +2409,70 @@ class EncryptionProperties(msrest.serialization.Model): """ _attribute_map = { - 'key_source': {'key': 'keySource', 'type': 'str'}, - 'key_vault_properties': {'key': 'keyVaultProperties', 'type': 'KeyVaultProperties'}, + "key_source": {"key": "keySource", "type": "str"}, + "key_vault_properties": {"key": "keyVaultProperties", "type": "KeyVaultProperties"}, } def __init__( self, *, - key_source: Optional[Union[str, "KeySource"]] = None, - key_vault_properties: Optional["KeyVaultProperties"] = None, + key_source: Optional[Union[str, "_models.KeySource"]] = None, + key_vault_properties: Optional["_models.KeyVaultProperties"] = None, **kwargs ): """ - :keyword key_source: Type of the key source. Possible values include: "Microsoft.Batch", + :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(EncryptionProperties, self).__init__(**kwargs) + super().__init__(**kwargs) self.key_source = key_source self.key_vault_properties = key_vault_properties -class EndpointAccessProfile(msrest.serialization.Model): +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: Required. Default action for endpoint access. It is only applicable when - publicNetworkAccess is enabled. Possible values include: "Allow", "Deny". + :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}, + "default_action": {"required": True}, } _attribute_map = { - 'default_action': {'key': 'defaultAction', 'type': 'str'}, - 'ip_rules': {'key': 'ipRules', 'type': '[IPRule]'}, + "default_action": {"key": "defaultAction", "type": "str"}, + "ip_rules": {"key": "ipRules", "type": "[IPRule]"}, } def __init__( self, *, - default_action: Union[str, "EndpointAccessDefaultAction"], - ip_rules: Optional[List["IPRule"]] = None, + default_action: Union[str, "_models.EndpointAccessDefaultAction"], + ip_rules: Optional[List["_models.IPRule"]] = None, **kwargs ): """ - :keyword default_action: Required. Default action for endpoint access. It is only applicable - when publicNetworkAccess is enabled. Possible values include: "Allow", "Deny". + :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(EndpointAccessProfile, self).__init__(**kwargs) + super().__init__(**kwargs) self.default_action = default_action self.ip_rules = ip_rules -class EndpointDependency(msrest.serialization.Model): +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. @@ -2549,30 +2488,26 @@ class EndpointDependency(msrest.serialization.Model): """ _validation = { - 'domain_name': {'readonly': True}, - 'description': {'readonly': True}, - 'endpoint_details': {'readonly': True}, + "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]'}, + "domain_name": {"key": "domainName", "type": "str"}, + "description": {"key": "description", "type": "str"}, + "endpoint_details": {"key": "endpointDetails", "type": "[EndpointDetail]"}, } - def __init__( - self, - **kwargs - ): - """ - """ - super(EndpointDependency, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.domain_name = None self.description = None self.endpoint_details = None -class EndpointDetail(msrest.serialization.Model): +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. @@ -2582,62 +2517,52 @@ class EndpointDetail(msrest.serialization.Model): """ _validation = { - 'port': {'readonly': True}, + "port": {"readonly": True}, } _attribute_map = { - 'port': {'key': 'port', 'type': 'int'}, + "port": {"key": "port", "type": "int"}, } - def __init__( - self, - **kwargs - ): - """ - """ - super(EndpointDetail, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.port = None -class EnvironmentSetting(msrest.serialization.Model): +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: Required. The name of the environment variable. + :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}, + "name": {"required": True}, } _attribute_map = { - 'name': {'key': 'name', 'type': 'str'}, - 'value': {'key': 'value', 'type': 'str'}, + "name": {"key": "name", "type": "str"}, + "value": {"key": "value", "type": "str"}, } - def __init__( - self, - *, - name: str, - value: Optional[str] = None, - **kwargs - ): + def __init__(self, *, name: str, value: Optional[str] = None, **kwargs): """ - :keyword name: Required. The name of the environment variable. + :keyword name: The name of the environment variable. Required. :paramtype name: str :keyword value: The value of the environment variable. :paramtype value: str """ - super(EnvironmentSetting, self).__init__(**kwargs) + super().__init__(**kwargs) self.name = name self.value = value -class FixedScaleSettings(msrest.serialization.Model): +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 @@ -2651,17 +2576,17 @@ class FixedScaleSettings(msrest.serialization.Model): :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. Possible values - include: "Requeue", "Terminate", "TaskCompletion", "RetainedData". + :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'}, + "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__( @@ -2670,7 +2595,7 @@ def __init__( 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, "ComputeNodeDeallocationOption"]] = None, + node_deallocation_option: Optional[Union[str, "_models.ComputeNodeDeallocationOption"]] = None, **kwargs ): """ @@ -2685,19 +2610,19 @@ def __init__( :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. Possible values - include: "Requeue", "Terminate", "TaskCompletion", "RetainedData". + :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(FixedScaleSettings, self).__init__(**kwargs) + 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(msrest.serialization.Model): +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. @@ -2717,11 +2642,11 @@ class ImageReference(msrest.serialization.Model): """ _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'}, + "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__( @@ -2731,7 +2656,7 @@ def __init__( offer: Optional[str] = None, sku: Optional[str] = None, version: Optional[str] = None, - id: Optional[str] = None, + id: Optional[str] = None, # pylint: disable=redefined-builtin **kwargs ): """ @@ -2750,7 +2675,7 @@ def __init__( https://docs.microsoft.com/en-us/azure/batch/batch-api-basics#virtual-network-vnet-and-firewall-configuration. :paramtype id: str """ - super(ImageReference, self).__init__(**kwargs) + super().__init__(**kwargs) self.publisher = publisher self.offer = offer self.sku = sku @@ -2758,31 +2683,31 @@ def __init__( self.id = id -class InboundNatPool(msrest.serialization.Model): +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: Required. 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. + :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: Required. The protocol of the endpoint. Possible values include: "TCP", "UDP". + :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: Required. 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. + :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: Required. 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. + :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: Required. 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. + :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 @@ -2793,55 +2718,54 @@ class InboundNatPool(msrest.serialization.Model): """ _validation = { - 'name': {'required': True}, - 'protocol': {'required': True}, - 'backend_port': {'required': True}, - 'frontend_port_range_start': {'required': True}, - 'frontend_port_range_end': {'required': True}, + "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]'}, + "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, "InboundEndpointProtocol"], + protocol: Union[str, "_models.InboundEndpointProtocol"], backend_port: int, frontend_port_range_start: int, frontend_port_range_end: int, - network_security_group_rules: Optional[List["NetworkSecurityGroupRule"]] = None, + network_security_group_rules: Optional[List["_models.NetworkSecurityGroupRule"]] = None, **kwargs ): """ - :keyword name: Required. 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. + :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: Required. The protocol of the endpoint. Possible values include: "TCP", - "UDP". + :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: Required. 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. + :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: Required. 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. + :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: Required. 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. + :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 @@ -2851,7 +2775,7 @@ def __init__( :paramtype network_security_group_rules: list[~azure.mgmt.batch.models.NetworkSecurityGroupRule] """ - super(InboundNatPool, self).__init__(**kwargs) + super().__init__(**kwargs) self.name = name self.protocol = protocol self.backend_port = backend_port @@ -2860,52 +2784,47 @@ def __init__( self.network_security_group_rules = network_security_group_rules -class IPRule(msrest.serialization.Model): +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. Has constant value: "Allow". + :ivar action: Action when client IP address is matched. Required. Default value is "Allow". :vartype action: str - :ivar value: Required. IPv4 address, or IPv4 address range in CIDR format. + :ivar value: IPv4 address, or IPv4 address range in CIDR format. Required. :vartype value: str """ _validation = { - 'action': {'required': True, 'constant': True}, - 'value': {'required': True}, + "action": {"required": True, "constant": True}, + "value": {"required": True}, } _attribute_map = { - 'action': {'key': 'action', 'type': 'str'}, - 'value': {'key': 'value', 'type': 'str'}, + "action": {"key": "action", "type": "str"}, + "value": {"key": "value", "type": "str"}, } action = "Allow" - def __init__( - self, - *, - value: str, - **kwargs - ): + def __init__(self, *, value: str, **kwargs): """ - :keyword value: Required. IPv4 address, or IPv4 address range in CIDR format. + :keyword value: IPv4 address, or IPv4 address range in CIDR format. Required. :paramtype value: str """ - super(IPRule, self).__init__(**kwargs) + super().__init__(**kwargs) self.value = value -class KeyVaultProperties(msrest.serialization.Model): +class KeyVaultProperties(_serialization.Model): """KeyVault configuration when using an encryption KeySource of Microsoft.KeyVault. :ivar key_identifier: Full path to the versioned secret. Example https://mykeyvault.vault.azure.net/keys/testkey/6e34a81fef704045975661e297a4c053. 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. @@ -2913,70 +2832,59 @@ class KeyVaultProperties(msrest.serialization.Model): """ _attribute_map = { - 'key_identifier': {'key': 'keyIdentifier', 'type': 'str'}, + "key_identifier": {"key": "keyIdentifier", "type": "str"}, } - def __init__( - self, - *, - key_identifier: Optional[str] = None, - **kwargs - ): + def __init__(self, *, key_identifier: Optional[str] = None, **kwargs): """ :keyword key_identifier: Full path to the versioned secret. Example https://mykeyvault.vault.azure.net/keys/testkey/6e34a81fef704045975661e297a4c053. 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(KeyVaultProperties, self).__init__(**kwargs) + super().__init__(**kwargs) self.key_identifier = key_identifier -class KeyVaultReference(msrest.serialization.Model): +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: Required. The resource ID of the Azure key vault associated with the Batch account. + :ivar id: The resource ID of the Azure key vault associated with the Batch account. Required. :vartype id: str - :ivar url: Required. The URL of the Azure key vault associated with the Batch account. + :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}, + "id": {"required": True}, + "url": {"required": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'url': {'key': 'url', 'type': 'str'}, + "id": {"key": "id", "type": "str"}, + "url": {"key": "url", "type": "str"}, } - def __init__( - self, - *, - id: str, - url: str, - **kwargs - ): + def __init__(self, *, id: str, url: str, **kwargs): # pylint: disable=redefined-builtin """ - :keyword id: Required. The resource ID of the Azure key vault associated with the Batch - account. + :keyword id: The resource ID of the Azure key vault associated with the Batch account. + Required. :paramtype id: str - :keyword url: Required. The URL of the Azure key vault associated with the Batch account. + :keyword url: The URL of the Azure key vault associated with the Batch account. Required. :paramtype url: str """ - super(KeyVaultReference, self).__init__(**kwargs) + super().__init__(**kwargs) self.id = id self.url = url -class LinuxUserConfiguration(msrest.serialization.Model): +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 @@ -2995,18 +2903,13 @@ class LinuxUserConfiguration(msrest.serialization.Model): """ _attribute_map = { - 'uid': {'key': 'uid', 'type': 'int'}, - 'gid': {'key': 'gid', 'type': 'int'}, - 'ssh_private_key': {'key': 'sshPrivateKey', 'type': 'str'}, + "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 + self, *, uid: Optional[int] = None, gid: Optional[int] = None, ssh_private_key: Optional[str] = None, **kwargs ): """ :keyword uid: The uid and gid properties must be specified together or not at all. If not @@ -3023,13 +2926,13 @@ def __init__( modification of the user's .ssh directory is done). :paramtype ssh_private_key: str """ - super(LinuxUserConfiguration, self).__init__(**kwargs) + super().__init__(**kwargs) self.uid = uid self.gid = gid self.ssh_private_key = ssh_private_key -class ListApplicationPackagesResult(msrest.serialization.Model): +class ListApplicationPackagesResult(_serialization.Model): """The result of performing list application packages. :ivar value: The list of application packages. @@ -3039,16 +2942,12 @@ class ListApplicationPackagesResult(msrest.serialization.Model): """ _attribute_map = { - 'value': {'key': 'value', 'type': '[ApplicationPackage]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "value": {"key": "value", "type": "[ApplicationPackage]"}, + "next_link": {"key": "nextLink", "type": "str"}, } def __init__( - self, - *, - value: Optional[List["ApplicationPackage"]] = None, - next_link: Optional[str] = None, - **kwargs + self, *, value: Optional[List["_models.ApplicationPackage"]] = None, next_link: Optional[str] = None, **kwargs ): """ :keyword value: The list of application packages. @@ -3056,12 +2955,12 @@ def __init__( :keyword next_link: The URL to get the next set of results. :paramtype next_link: str """ - super(ListApplicationPackagesResult, self).__init__(**kwargs) + super().__init__(**kwargs) self.value = value self.next_link = next_link -class ListApplicationsResult(msrest.serialization.Model): +class ListApplicationsResult(_serialization.Model): """The result of performing list applications. :ivar value: The list of applications. @@ -3071,16 +2970,12 @@ class ListApplicationsResult(msrest.serialization.Model): """ _attribute_map = { - 'value': {'key': 'value', 'type': '[Application]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "value": {"key": "value", "type": "[Application]"}, + "next_link": {"key": "nextLink", "type": "str"}, } def __init__( - self, - *, - value: Optional[List["Application"]] = None, - next_link: Optional[str] = None, - **kwargs + self, *, value: Optional[List["_models.Application"]] = None, next_link: Optional[str] = None, **kwargs ): """ :keyword value: The list of applications. @@ -3088,12 +2983,12 @@ def __init__( :keyword next_link: The URL to get the next set of results. :paramtype next_link: str """ - super(ListApplicationsResult, self).__init__(**kwargs) + super().__init__(**kwargs) self.value = value self.next_link = next_link -class ListCertificatesResult(msrest.serialization.Model): +class ListCertificatesResult(_serialization.Model): """Values returned by the List operation. :ivar value: The collection of returned certificates. @@ -3103,16 +2998,12 @@ class ListCertificatesResult(msrest.serialization.Model): """ _attribute_map = { - 'value': {'key': 'value', 'type': '[Certificate]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "value": {"key": "value", "type": "[Certificate]"}, + "next_link": {"key": "nextLink", "type": "str"}, } def __init__( - self, - *, - value: Optional[List["Certificate"]] = None, - next_link: Optional[str] = None, - **kwargs + self, *, value: Optional[List["_models.Certificate"]] = None, next_link: Optional[str] = None, **kwargs ): """ :keyword value: The collection of returned certificates. @@ -3120,12 +3011,12 @@ def __init__( :keyword next_link: The continuation token. :paramtype next_link: str """ - super(ListCertificatesResult, self).__init__(**kwargs) + super().__init__(**kwargs) self.value = value self.next_link = next_link -class ListPoolsResult(msrest.serialization.Model): +class ListPoolsResult(_serialization.Model): """Values returned by the List operation. :ivar value: The collection of returned pools. @@ -3135,29 +3026,23 @@ class ListPoolsResult(msrest.serialization.Model): """ _attribute_map = { - 'value': {'key': 'value', 'type': '[Pool]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "value": {"key": "value", "type": "[Pool]"}, + "next_link": {"key": "nextLink", "type": "str"}, } - def __init__( - self, - *, - value: Optional[List["Pool"]] = None, - next_link: Optional[str] = None, - **kwargs - ): + def __init__(self, *, value: Optional[List["_models.Pool"]] = None, next_link: Optional[str] = None, **kwargs): """ :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(ListPoolsResult, self).__init__(**kwargs) + super().__init__(**kwargs) self.value = value self.next_link = next_link -class ListPrivateEndpointConnectionsResult(msrest.serialization.Model): +class ListPrivateEndpointConnectionsResult(_serialization.Model): """Values returned by the List operation. :ivar value: The collection of returned private endpoint connection. @@ -3167,14 +3052,14 @@ class ListPrivateEndpointConnectionsResult(msrest.serialization.Model): """ _attribute_map = { - 'value': {'key': 'value', 'type': '[PrivateEndpointConnection]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "value": {"key": "value", "type": "[PrivateEndpointConnection]"}, + "next_link": {"key": "nextLink", "type": "str"}, } def __init__( self, *, - value: Optional[List["PrivateEndpointConnection"]] = None, + value: Optional[List["_models.PrivateEndpointConnection"]] = None, next_link: Optional[str] = None, **kwargs ): @@ -3184,12 +3069,12 @@ def __init__( :keyword next_link: The continuation token. :paramtype next_link: str """ - super(ListPrivateEndpointConnectionsResult, self).__init__(**kwargs) + super().__init__(**kwargs) self.value = value self.next_link = next_link -class ListPrivateLinkResourcesResult(msrest.serialization.Model): +class ListPrivateLinkResourcesResult(_serialization.Model): """Values returned by the List operation. :ivar value: The collection of returned private link resources. @@ -3199,16 +3084,12 @@ class ListPrivateLinkResourcesResult(msrest.serialization.Model): """ _attribute_map = { - 'value': {'key': 'value', 'type': '[PrivateLinkResource]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "value": {"key": "value", "type": "[PrivateLinkResource]"}, + "next_link": {"key": "nextLink", "type": "str"}, } def __init__( - self, - *, - value: Optional[List["PrivateLinkResource"]] = None, - next_link: Optional[str] = None, - **kwargs + self, *, value: Optional[List["_models.PrivateLinkResource"]] = None, next_link: Optional[str] = None, **kwargs ): """ :keyword value: The collection of returned private link resources. @@ -3216,51 +3097,45 @@ def __init__( :keyword next_link: The continuation token. :paramtype next_link: str """ - super(ListPrivateLinkResourcesResult, self).__init__(**kwargs) + super().__init__(**kwargs) self.value = value self.next_link = next_link -class MetadataItem(msrest.serialization.Model): +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: Required. The name of the metadata item. + :ivar name: The name of the metadata item. Required. :vartype name: str - :ivar value: Required. The value of the metadata item. + :ivar value: The value of the metadata item. Required. :vartype value: str """ _validation = { - 'name': {'required': True}, - 'value': {'required': True}, + "name": {"required": True}, + "value": {"required": True}, } _attribute_map = { - 'name': {'key': 'name', 'type': 'str'}, - 'value': {'key': 'value', 'type': 'str'}, + "name": {"key": "name", "type": "str"}, + "value": {"key": "value", "type": "str"}, } - def __init__( - self, - *, - name: str, - value: str, - **kwargs - ): + def __init__(self, *, name: str, value: str, **kwargs): """ - :keyword name: Required. The name of the metadata item. + :keyword name: The name of the metadata item. Required. :paramtype name: str - :keyword value: Required. The value of the metadata item. + :keyword value: The value of the metadata item. Required. :paramtype value: str """ - super(MetadataItem, self).__init__(**kwargs) + super().__init__(**kwargs) self.name = name self.value = value -class MountConfiguration(msrest.serialization.Model): +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 @@ -3277,19 +3152,22 @@ class MountConfiguration(msrest.serialization.Model): """ _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'}, + "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["AzureBlobFileSystemConfiguration"] = None, - nfs_mount_configuration: Optional["NFSMountConfiguration"] = None, - cifs_mount_configuration: Optional["CIFSMountConfiguration"] = None, - azure_file_share_configuration: Optional["AzureFileShareConfiguration"] = None, + 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 ): """ @@ -3307,14 +3185,14 @@ def __init__( properties. :paramtype azure_file_share_configuration: ~azure.mgmt.batch.models.AzureFileShareConfiguration """ - super(MountConfiguration, self).__init__(**kwargs) + 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(msrest.serialization.Model): +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 @@ -3335,9 +3213,9 @@ class NetworkConfiguration(msrest.serialization.Model): 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_v_net_assignment_scope: The scope of dynamic vnet assignment. Possible values - include: "none", "job". - :vartype dynamic_v_net_assignment_scope: str or + :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. @@ -3348,19 +3226,22 @@ class NetworkConfiguration(msrest.serialization.Model): """ _attribute_map = { - 'subnet_id': {'key': 'subnetId', 'type': 'str'}, - 'dynamic_v_net_assignment_scope': {'key': 'dynamicVNetAssignmentScope', 'type': 'str'}, - 'endpoint_configuration': {'key': 'endpointConfiguration', 'type': 'PoolEndpointConfiguration'}, - 'public_ip_address_configuration': {'key': 'publicIPAddressConfiguration', 'type': 'PublicIPAddressConfiguration'}, + "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", + }, } def __init__( self, *, subnet_id: Optional[str] = None, - dynamic_v_net_assignment_scope: Optional[Union[str, "DynamicVNetAssignmentScope"]] = None, - endpoint_configuration: Optional["PoolEndpointConfiguration"] = None, - public_ip_address_configuration: Optional["PublicIPAddressConfiguration"] = 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, **kwargs ): """ @@ -3382,9 +3263,9 @@ def __init__( 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_v_net_assignment_scope: The scope of dynamic vnet assignment. Possible values - include: "none", "job". - :paramtype dynamic_v_net_assignment_scope: str or + :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. @@ -3394,14 +3275,14 @@ def __init__( :paramtype public_ip_address_configuration: ~azure.mgmt.batch.models.PublicIPAddressConfiguration """ - super(NetworkConfiguration, self).__init__(**kwargs) + super().__init__(**kwargs) self.subnet_id = subnet_id - self.dynamic_v_net_assignment_scope = dynamic_v_net_assignment_scope + self.dynamic_vnet_assignment_scope = dynamic_vnet_assignment_scope self.endpoint_configuration = endpoint_configuration self.public_ip_address_configuration = public_ip_address_configuration -class NetworkProfile(msrest.serialization.Model): +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 @@ -3413,15 +3294,15 @@ class NetworkProfile(msrest.serialization.Model): """ _attribute_map = { - 'account_access': {'key': 'accountAccess', 'type': 'EndpointAccessProfile'}, - 'node_management_access': {'key': 'nodeManagementAccess', 'type': 'EndpointAccessProfile'}, + "account_access": {"key": "accountAccess", "type": "EndpointAccessProfile"}, + "node_management_access": {"key": "nodeManagementAccess", "type": "EndpointAccessProfile"}, } def __init__( self, *, - account_access: Optional["EndpointAccessProfile"] = None, - node_management_access: Optional["EndpointAccessProfile"] = None, + account_access: Optional["_models.EndpointAccessProfile"] = None, + node_management_access: Optional["_models.EndpointAccessProfile"] = None, **kwargs ): """ @@ -3432,28 +3313,28 @@ def __init__( service managing compute nodes for Batch pools). :paramtype node_management_access: ~azure.mgmt.batch.models.EndpointAccessProfile """ - super(NetworkProfile, self).__init__(**kwargs) + super().__init__(**kwargs) self.account_access = account_access self.node_management_access = node_management_access -class NetworkSecurityGroupRule(msrest.serialization.Model): +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: Required. 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. + :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: Required. The action that should be taken for a specified IP address, subnet - range or tag. Possible values include: "Allow", "Deny". + :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: Required. 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. + :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 @@ -3463,40 +3344,40 @@ class NetworkSecurityGroupRule(msrest.serialization.Model): """ _validation = { - 'priority': {'required': True}, - 'access': {'required': True}, - 'source_address_prefix': {'required': True}, + "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]'}, + "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, "NetworkSecurityGroupRuleAccess"], + access: Union[str, "_models.NetworkSecurityGroupRuleAccess"], source_address_prefix: str, source_port_ranges: Optional[List[str]] = None, **kwargs ): """ - :keyword priority: Required. 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. + :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: Required. The action that should be taken for a specified IP address, subnet - range or tag. Possible values include: "Allow", "Deny". + :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: Required. 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. + :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 @@ -3504,89 +3385,77 @@ def __init__( status code 400. Default value will be *. :paramtype source_port_ranges: list[str] """ - super(NetworkSecurityGroupRule, self).__init__(**kwargs) + 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(msrest.serialization.Model): +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: Required. The URI of the file system to mount. + :ivar source: The URI of the file system to mount. Required. :vartype source: str - :ivar relative_mount_path: Required. All file systems are mounted relative to the Batch mounts - directory, accessible via the AZ_BATCH_NODE_MOUNTS_DIR environment variable. + :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}, + "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'}, + "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 - ): + def __init__(self, *, source: str, relative_mount_path: str, mount_options: Optional[str] = None, **kwargs): """ - :keyword source: Required. The URI of the file system to mount. + :keyword source: The URI of the file system to mount. Required. :paramtype source: str - :keyword relative_mount_path: Required. All file systems are mounted relative to the Batch - mounts directory, accessible via the AZ_BATCH_NODE_MOUNTS_DIR environment variable. + :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(NFSMountConfiguration, self).__init__(**kwargs) + super().__init__(**kwargs) self.source = source self.relative_mount_path = relative_mount_path self.mount_options = mount_options -class NodePlacementConfiguration(msrest.serialization.Model): +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. Possible values include: "Regional", "Zonal". + 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'}, + "policy": {"key": "policy", "type": "str"}, } - def __init__( - self, - *, - policy: Optional[Union[str, "NodePlacementPolicyType"]] = None, - **kwargs - ): + def __init__(self, *, policy: Optional[Union[str, "_models.NodePlacementPolicyType"]] = None, **kwargs): """ :keyword policy: Allocation policy used by Batch Service to provision the nodes. If not - specified, Batch will use the regional policy. Possible values include: "Regional", "Zonal". + specified, Batch will use the regional policy. Known values are: "Regional" and "Zonal". :paramtype policy: str or ~azure.mgmt.batch.models.NodePlacementPolicyType """ - super(NodePlacementConfiguration, self).__init__(**kwargs) + super().__init__(**kwargs) self.policy = policy -class Operation(msrest.serialization.Model): +class Operation(_serialization.Model): """A REST API operation. :ivar name: This is of the format {provider}/{resource}/{operation}. @@ -3597,16 +3466,16 @@ class Operation(msrest.serialization.Model): :vartype display: ~azure.mgmt.batch.models.OperationDisplay :ivar origin: The intended executor of the operation. :vartype origin: str - :ivar properties: Any object. - :vartype properties: any + :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'}, + "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__( @@ -3614,9 +3483,9 @@ def __init__( *, name: Optional[str] = None, is_data_action: Optional[bool] = None, - display: Optional["OperationDisplay"] = None, + display: Optional["_models.OperationDisplay"] = None, origin: Optional[str] = None, - properties: Optional[Any] = None, + properties: Optional[JSON] = None, **kwargs ): """ @@ -3628,10 +3497,10 @@ def __init__( :paramtype display: ~azure.mgmt.batch.models.OperationDisplay :keyword origin: The intended executor of the operation. :paramtype origin: str - :keyword properties: Any object. - :paramtype properties: any + :keyword properties: Properties of the operation. + :paramtype properties: JSON """ - super(Operation, self).__init__(**kwargs) + super().__init__(**kwargs) self.name = name self.is_data_action = is_data_action self.display = display @@ -3639,7 +3508,7 @@ def __init__( self.properties = properties -class OperationDisplay(msrest.serialization.Model): +class OperationDisplay(_serialization.Model): """The object that describes the operation. :ivar provider: Friendly name of the resource provider. @@ -3653,10 +3522,10 @@ class OperationDisplay(msrest.serialization.Model): """ _attribute_map = { - 'provider': {'key': 'provider', 'type': 'str'}, - 'operation': {'key': 'operation', 'type': 'str'}, - 'resource': {'key': 'resource', 'type': 'str'}, - 'description': {'key': 'description', 'type': 'str'}, + "provider": {"key": "provider", "type": "str"}, + "operation": {"key": "operation", "type": "str"}, + "resource": {"key": "resource", "type": "str"}, + "description": {"key": "description", "type": "str"}, } def __init__( @@ -3678,14 +3547,14 @@ def __init__( :keyword description: The friendly name of the operation. :paramtype description: str """ - super(OperationDisplay, self).__init__(**kwargs) + super().__init__(**kwargs) self.provider = provider self.operation = operation self.resource = resource self.description = description -class OperationListResult(msrest.serialization.Model): +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. @@ -3695,29 +3564,23 @@ class OperationListResult(msrest.serialization.Model): """ _attribute_map = { - 'value': {'key': 'value', 'type': '[Operation]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "value": {"key": "value", "type": "[Operation]"}, + "next_link": {"key": "nextLink", "type": "str"}, } - def __init__( - self, - *, - value: Optional[List["Operation"]] = None, - next_link: Optional[str] = None, - **kwargs - ): + def __init__(self, *, value: Optional[List["_models.Operation"]] = None, next_link: Optional[str] = None, **kwargs): """ :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(OperationListResult, self).__init__(**kwargs) + super().__init__(**kwargs) self.value = value self.next_link = next_link -class OSDisk(msrest.serialization.Model): +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 @@ -3726,25 +3589,20 @@ class OSDisk(msrest.serialization.Model): """ _attribute_map = { - 'ephemeral_os_disk_settings': {'key': 'ephemeralOSDiskSettings', 'type': 'DiffDiskSettings'}, + "ephemeral_os_disk_settings": {"key": "ephemeralOSDiskSettings", "type": "DiffDiskSettings"}, } - def __init__( - self, - *, - ephemeral_os_disk_settings: Optional["DiffDiskSettings"] = None, - **kwargs - ): + def __init__(self, *, ephemeral_os_disk_settings: Optional["_models.DiffDiskSettings"] = None, **kwargs): """ :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(OSDisk, self).__init__(**kwargs) + super().__init__(**kwargs) self.ephemeral_os_disk_settings = ephemeral_os_disk_settings -class OutboundEnvironmentEndpoint(msrest.serialization.Model): +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. @@ -3757,27 +3615,23 @@ class OutboundEnvironmentEndpoint(msrest.serialization.Model): """ _validation = { - 'category': {'readonly': True}, - 'endpoints': {'readonly': True}, + "category": {"readonly": True}, + "endpoints": {"readonly": True}, } _attribute_map = { - 'category': {'key': 'category', 'type': 'str'}, - 'endpoints': {'key': 'endpoints', 'type': '[EndpointDependency]'}, + "category": {"key": "category", "type": "str"}, + "endpoints": {"key": "endpoints", "type": "[EndpointDependency]"}, } - def __init__( - self, - **kwargs - ): - """ - """ - super(OutboundEnvironmentEndpoint, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.category = None self.endpoints = None -class OutboundEnvironmentEndpointCollection(msrest.serialization.Model): +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. @@ -3790,30 +3644,25 @@ class OutboundEnvironmentEndpointCollection(msrest.serialization.Model): """ _validation = { - 'value': {'readonly': True}, + "value": {"readonly": True}, } _attribute_map = { - 'value': {'key': 'value', 'type': '[OutboundEnvironmentEndpoint]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "value": {"key": "value", "type": "[OutboundEnvironmentEndpoint]"}, + "next_link": {"key": "nextLink", "type": "str"}, } - def __init__( - self, - *, - next_link: Optional[str] = None, - **kwargs - ): + def __init__(self, *, next_link: Optional[str] = None, **kwargs): """ :keyword next_link: The continuation token. :paramtype next_link: str """ - super(OutboundEnvironmentEndpointCollection, self).__init__(**kwargs) + super().__init__(**kwargs) self.value = None self.next_link = next_link -class Pool(ProxyResource): +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. @@ -3837,13 +3686,13 @@ class Pool(ProxyResource): :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. Possible values include: "Succeeded", + :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. Possible values include: "Steady", - "Resizing", "Stopping". + :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. @@ -3864,10 +3713,10 @@ class Pool(ProxyResource): 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 compute nodes currently in the pool. + :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 low-priority compute nodes currently in the - pool. + :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 @@ -3879,8 +3728,8 @@ class Pool(ProxyResource): :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'. Possible values - include: "Enabled", "Disabled". + 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 @@ -3903,6 +3752,10 @@ class Pool(ProxyResource): 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 + `_ 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 @@ -3919,77 +3772,87 @@ class Pool(ProxyResource): :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}, + "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]'}, - } - - def __init__( + "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["BatchPoolIdentity"] = None, + identity: Optional["_models.BatchPoolIdentity"] = None, display_name: Optional[str] = None, vm_size: Optional[str] = None, - deployment_configuration: Optional["DeploymentConfiguration"] = None, - scale_settings: Optional["ScaleSettings"] = None, - inter_node_communication: Optional[Union[str, "InterNodeCommunicationState"]] = None, - network_configuration: Optional["NetworkConfiguration"] = 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["TaskSchedulingPolicy"] = None, - user_accounts: Optional[List["UserAccount"]] = None, - metadata: Optional[List["MetadataItem"]] = None, - start_task: Optional["StartTask"] = None, - certificates: Optional[List["CertificateReference"]] = None, - application_packages: Optional[List["ApplicationPackageReference"]] = 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["MountConfiguration"]] = None, + mount_configuration: Optional[List["_models.MountConfiguration"]] = None, + target_node_communication_mode: Optional[Union[str, "_models.NodeCommunicationMode"]] = None, **kwargs ): """ @@ -4021,8 +3884,8 @@ def __init__( :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'. Possible values - include: "Enabled", "Disabled". + 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. @@ -4046,6 +3909,10 @@ def __init__( 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 + `_ 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 @@ -4058,8 +3925,12 @@ def __init__( :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(Pool, self).__init__(**kwargs) + super().__init__(**kwargs) self.identity = identity self.display_name = display_name self.last_modified = None @@ -4086,44 +3957,41 @@ def __init__( 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(msrest.serialization.Model): +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: Required. 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. + :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}, + "inbound_nat_pools": {"required": True}, } _attribute_map = { - 'inbound_nat_pools': {'key': 'inboundNatPools', 'type': '[InboundNatPool]'}, + "inbound_nat_pools": {"key": "inboundNatPools", "type": "[InboundNatPool]"}, } - def __init__( - self, - *, - inbound_nat_pools: List["InboundNatPool"], - **kwargs - ): + def __init__(self, *, inbound_nat_pools: List["_models.InboundNatPool"], **kwargs): """ - :keyword inbound_nat_pools: Required. 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. + :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(PoolEndpointConfiguration, self).__init__(**kwargs) + super().__init__(**kwargs) self.inbound_nat_pools = inbound_nat_pools -class PrivateEndpoint(msrest.serialization.Model): +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. @@ -4134,20 +4002,16 @@ class PrivateEndpoint(msrest.serialization.Model): """ _validation = { - 'id': {'readonly': True}, + "id": {"readonly": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, + "id": {"key": "id", "type": "str"}, } - def __init__( - self, - **kwargs - ): - """ - """ - super(PrivateEndpoint, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.id = None @@ -4164,8 +4028,8 @@ class PrivateEndpointConnection(ProxyResource): :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. Possible - values include: "Creating", "Updating", "Deleting", "Succeeded", "Failed", "Cancelled". + :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. @@ -4179,30 +4043,33 @@ class PrivateEndpointConnection(ProxyResource): """ _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}, + "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'}, + "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["PrivateLinkServiceConnectionState"] = None, + private_link_service_connection_state: Optional["_models.PrivateLinkServiceConnectionState"] = None, **kwargs ): """ @@ -4211,7 +4078,7 @@ def __init__( :paramtype private_link_service_connection_state: ~azure.mgmt.batch.models.PrivateLinkServiceConnectionState """ - super(PrivateEndpointConnection, self).__init__(**kwargs) + super().__init__(**kwargs) self.provisioning_state = None self.private_endpoint = None self.group_ids = None @@ -4241,189 +4108,179 @@ class PrivateLinkResource(ProxyResource): """ _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}, + "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 - ): - """ - """ - super(PrivateLinkResource, self).__init__(**kwargs) + "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): + """ """ + super().__init__(**kwargs) self.group_id = None self.required_members = None self.required_zone_names = None -class PrivateLinkServiceConnectionState(msrest.serialization.Model): +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: Required. The status of the Batch private endpoint connection. Possible values - include: "Approved", "Pending", "Rejected", "Disconnected". + :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 action_required: Action required on the private connection state. - :vartype action_required: str + :ivar actions_required: Action required on the private connection state. + :vartype actions_required: str """ _validation = { - 'status': {'required': True}, - 'action_required': {'readonly': True}, + "status": {"required": True}, + "actions_required": {"readonly": True}, } _attribute_map = { - 'status': {'key': 'status', 'type': 'str'}, - 'description': {'key': 'description', 'type': 'str'}, - 'action_required': {'key': 'actionRequired', 'type': 'str'}, + "status": {"key": "status", "type": "str"}, + "description": {"key": "description", "type": "str"}, + "actions_required": {"key": "actionsRequired", "type": "str"}, } def __init__( self, *, - status: Union[str, "PrivateLinkServiceConnectionStatus"], + status: Union[str, "_models.PrivateLinkServiceConnectionStatus"], description: Optional[str] = None, **kwargs ): """ - :keyword status: Required. The status of the Batch private endpoint connection. Possible values - include: "Approved", "Pending", "Rejected", "Disconnected". + :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(PrivateLinkServiceConnectionState, self).__init__(**kwargs) + super().__init__(**kwargs) self.status = status self.description = description - self.action_required = None + self.actions_required = None -class PublicIPAddressConfiguration(msrest.serialization.Model): +class PublicIPAddressConfiguration(_serialization.Model): """The public IP Address configuration of the networking configuration of a Pool. - :ivar provision: The default value is BatchManaged. Possible values include: "BatchManaged", - "UserManaged", "NoPublicIPAddresses". + :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 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: + 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]'}, + "provision": {"key": "provision", "type": "str"}, + "ip_address_ids": {"key": "ipAddressIds", "type": "[str]"}, } def __init__( self, *, - provision: Optional[Union[str, "IPAddressProvisioningType"]] = None, + provision: Optional[Union[str, "_models.IPAddressProvisioningType"]] = None, ip_address_ids: Optional[List[str]] = None, **kwargs ): """ - :keyword provision: The default value is BatchManaged. Possible values include: "BatchManaged", - "UserManaged", "NoPublicIPAddresses". + :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 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: + 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(PublicIPAddressConfiguration, self).__init__(**kwargs) + super().__init__(**kwargs) self.provision = provision self.ip_address_ids = ip_address_ids -class ResizeError(msrest.serialization.Model): +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: Required. An identifier for the error. Codes are invariant and are intended to be - consumed programmatically. + :ivar code: An identifier for the error. Codes are invariant and are intended to be consumed + programmatically. Required. :vartype code: str - :ivar message: Required. A message describing the error, intended to be suitable for display in - a user interface. + :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}, + "code": {"required": True}, + "message": {"required": True}, } _attribute_map = { - 'code': {'key': 'code', 'type': 'str'}, - 'message': {'key': 'message', 'type': 'str'}, - 'details': {'key': 'details', 'type': '[ResizeError]'}, + "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["ResizeError"]] = None, - **kwargs - ): + def __init__(self, *, code: str, message: str, details: Optional[List["_models.ResizeError"]] = None, **kwargs): """ - :keyword code: Required. An identifier for the error. Codes are invariant and are intended to - be consumed programmatically. + :keyword code: An identifier for the error. Codes are invariant and are intended to be consumed + programmatically. Required. :paramtype code: str - :keyword message: Required. A message describing the error, intended to be suitable for display - in a user interface. + :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(ResizeError, self).__init__(**kwargs) + super().__init__(**kwargs) self.code = code self.message = message self.details = details -class ResizeOperationStatus(msrest.serialization.Model): +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 low-priority compute nodes in the pool. + :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. Possible values include: - "Requeue", "Terminate", "TaskCompletion", "RetainedData". + :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. @@ -4434,12 +4291,12 @@ class ResizeOperationStatus(msrest.serialization.Model): """ _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]'}, + "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__( @@ -4448,23 +4305,23 @@ def __init__( 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, "ComputeNodeDeallocationOption"]] = None, + node_deallocation_option: Optional[Union[str, "_models.ComputeNodeDeallocationOption"]] = None, start_time: Optional[datetime.datetime] = None, - errors: Optional[List["ResizeError"]] = None, + errors: Optional[List["_models.ResizeError"]] = None, **kwargs ): """ :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 low-priority compute nodes in the - pool. + :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. Possible values include: - "Requeue", "Terminate", "TaskCompletion", "RetainedData". + :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. @@ -4473,7 +4330,7 @@ def __init__( and only when the pool allocationState is Steady. :paramtype errors: list[~azure.mgmt.batch.models.ResizeError] """ - super(ResizeOperationStatus, self).__init__(**kwargs) + super().__init__(**kwargs) self.target_dedicated_nodes = target_dedicated_nodes self.target_low_priority_nodes = target_low_priority_nodes self.resize_timeout = resize_timeout @@ -4482,7 +4339,7 @@ def __init__( self.errors = errors -class ResourceFile(msrest.serialization.Model): +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 @@ -4525,13 +4382,13 @@ class ResourceFile(msrest.serialization.Model): """ _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'}, + "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__( @@ -4543,7 +4400,7 @@ def __init__( blob_prefix: Optional[str] = None, file_path: Optional[str] = None, file_mode: Optional[str] = None, - identity_reference: Optional["ComputeNodeIdentityReference"] = None, + identity_reference: Optional["_models.ComputeNodeIdentityReference"] = None, **kwargs ): """ @@ -4585,7 +4442,7 @@ def __init__( Batch pool which a compute node will use. :paramtype identity_reference: ~azure.mgmt.batch.models.ComputeNodeIdentityReference """ - super(ResourceFile, self).__init__(**kwargs) + super().__init__(**kwargs) self.auto_storage_container_name = auto_storage_container_name self.storage_container_url = storage_container_url self.http_url = http_url @@ -4595,7 +4452,7 @@ def __init__( self.identity_reference = identity_reference -class ScaleSettings(msrest.serialization.Model): +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 @@ -4607,15 +4464,15 @@ class ScaleSettings(msrest.serialization.Model): """ _attribute_map = { - 'fixed_scale': {'key': 'fixedScale', 'type': 'FixedScaleSettings'}, - 'auto_scale': {'key': 'autoScale', 'type': 'AutoScaleSettings'}, + "fixed_scale": {"key": "fixedScale", "type": "FixedScaleSettings"}, + "auto_scale": {"key": "autoScale", "type": "AutoScaleSettings"}, } def __init__( self, *, - fixed_scale: Optional["FixedScaleSettings"] = None, - auto_scale: Optional["AutoScaleSettings"] = None, + fixed_scale: Optional["_models.FixedScaleSettings"] = None, + auto_scale: Optional["_models.AutoScaleSettings"] = None, **kwargs ): """ @@ -4626,12 +4483,12 @@ def __init__( properties must be specified. :paramtype auto_scale: ~azure.mgmt.batch.models.AutoScaleSettings """ - super(ScaleSettings, self).__init__(**kwargs) + super().__init__(**kwargs) self.fixed_scale = fixed_scale self.auto_scale = auto_scale -class SkuCapability(msrest.serialization.Model): +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. @@ -4643,27 +4500,23 @@ class SkuCapability(msrest.serialization.Model): """ _validation = { - 'name': {'readonly': True}, - 'value': {'readonly': True}, + "name": {"readonly": True}, + "value": {"readonly": True}, } _attribute_map = { - 'name': {'key': 'name', 'type': 'str'}, - 'value': {'key': 'value', 'type': 'str'}, + "name": {"key": "name", "type": "str"}, + "value": {"key": "value", "type": "str"}, } - def __init__( - self, - **kwargs - ): - """ - """ - super(SkuCapability, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.name = None self.value = None -class StartTask(msrest.serialization.Model): +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 @@ -4703,25 +4556,25 @@ class StartTask(msrest.serialization.Model): """ _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'}, + "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["ResourceFile"]] = None, - environment_settings: Optional[List["EnvironmentSetting"]] = None, - user_identity: Optional["UserIdentity"] = 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["TaskContainerSettings"] = None, + container_settings: Optional["_models.TaskContainerSettings"] = None, **kwargs ): """ @@ -4761,7 +4614,7 @@ def __init__( line is executed in the container. :paramtype container_settings: ~azure.mgmt.batch.models.TaskContainerSettings """ - super(StartTask, self).__init__(**kwargs) + super().__init__(**kwargs) self.command_line = command_line self.resource_files = resource_files self.environment_settings = environment_settings @@ -4771,7 +4624,7 @@ def __init__( self.container_settings = container_settings -class SupportedSku(msrest.serialization.Model): +class SupportedSku(_serialization.Model): """Describes a Batch supported SKU. Variables are only populated by the server, and will be ignored when sending a request. @@ -4785,68 +4638,59 @@ class SupportedSku(msrest.serialization.Model): """ _validation = { - 'name': {'readonly': True}, - 'family_name': {'readonly': True}, - 'capabilities': {'readonly': True}, + "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]'}, + "name": {"key": "name", "type": "str"}, + "family_name": {"key": "familyName", "type": "str"}, + "capabilities": {"key": "capabilities", "type": "[SkuCapability]"}, } - def __init__( - self, - **kwargs - ): - """ - """ - super(SupportedSku, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.name = None self.family_name = None self.capabilities = None -class SupportedSkusResult(msrest.serialization.Model): +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: Required. The list of SKUs available for the Batch service in the location. + :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}, + "value": {"required": True}, + "next_link": {"readonly": True}, } _attribute_map = { - 'value': {'key': 'value', 'type': '[SupportedSku]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "value": {"key": "value", "type": "[SupportedSku]"}, + "next_link": {"key": "nextLink", "type": "str"}, } - def __init__( - self, - *, - value: List["SupportedSku"], - **kwargs - ): + def __init__(self, *, value: List["_models.SupportedSku"], **kwargs): """ - :keyword value: Required. The list of SKUs available for the Batch service in the location. + :keyword value: The list of SKUs available for the Batch service in the location. Required. :paramtype value: list[~azure.mgmt.batch.models.SupportedSku] """ - super(SupportedSkusResult, self).__init__(**kwargs) + super().__init__(**kwargs) self.value = value self.next_link = None -class TaskContainerSettings(msrest.serialization.Model): +class TaskContainerSettings(_serialization.Model): """The container settings for a task. All required parameters must be populated in order to send to Azure. @@ -4854,26 +4698,26 @@ class TaskContainerSettings(msrest.serialization.Model): :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: Required. 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. + :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'. Possible values include: "TaskWorkingDirectory", + default is 'taskWorkingDirectory'. Known values are: "TaskWorkingDirectory" and "ContainerImageDefault". :vartype working_directory: str or ~azure.mgmt.batch.models.ContainerWorkingDirectory """ _validation = { - 'image_name': {'required': True}, + "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'}, + "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__( @@ -4881,77 +4725,73 @@ def __init__( *, image_name: str, container_run_options: Optional[str] = None, - registry: Optional["ContainerRegistry"] = None, - working_directory: Optional[Union[str, "ContainerWorkingDirectory"]] = None, + registry: Optional["_models.ContainerRegistry"] = None, + working_directory: Optional[Union[str, "_models.ContainerWorkingDirectory"]] = None, **kwargs ): """ :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: Required. 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. + :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'. Possible values include: "TaskWorkingDirectory", + The default is 'taskWorkingDirectory'. Known values are: "TaskWorkingDirectory" and "ContainerImageDefault". :paramtype working_directory: str or ~azure.mgmt.batch.models.ContainerWorkingDirectory """ - super(TaskContainerSettings, self).__init__(**kwargs) + 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(msrest.serialization.Model): +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: Required. How tasks should be distributed across compute nodes. Possible - values include: "Spread", "Pack". + :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}, + "node_fill_type": {"required": True}, } _attribute_map = { - 'node_fill_type': {'key': 'nodeFillType', 'type': 'str'}, + "node_fill_type": {"key": "nodeFillType", "type": "str"}, } - def __init__( - self, - *, - node_fill_type: Union[str, "ComputeNodeFillType"], - **kwargs - ): + def __init__(self, *, node_fill_type: Union[str, "_models.ComputeNodeFillType"], **kwargs): """ - :keyword node_fill_type: Required. How tasks should be distributed across compute nodes. - Possible values include: "Spread", "Pack". + :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(TaskSchedulingPolicy, self).__init__(**kwargs) + super().__init__(**kwargs) self.node_fill_type = node_fill_type -class UserAccount(msrest.serialization.Model): +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: Required. The name of the user account. + :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: Required. The password for the user account. + :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. Possible values include: "NonAdmin", "Admin". + 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. @@ -4963,16 +4803,16 @@ class UserAccount(msrest.serialization.Model): """ _validation = { - 'name': {'required': True}, - 'password': {'required': True}, + "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'}, + "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__( @@ -4980,19 +4820,20 @@ def __init__( *, name: str, password: str, - elevation_level: Optional[Union[str, "ElevationLevel"]] = None, - linux_user_configuration: Optional["LinuxUserConfiguration"] = None, - windows_user_configuration: Optional["WindowsUserConfiguration"] = None, + elevation_level: Optional[Union[str, "_models.ElevationLevel"]] = None, + linux_user_configuration: Optional["_models.LinuxUserConfiguration"] = None, + windows_user_configuration: Optional["_models.WindowsUserConfiguration"] = None, **kwargs ): """ - :keyword name: Required. The name of the user account. + :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: Required. The password for the user account. + :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. Possible values include: "NonAdmin", "Admin". + 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. @@ -5002,7 +4843,7 @@ def __init__( options. :paramtype windows_user_configuration: ~azure.mgmt.batch.models.WindowsUserConfiguration """ - super(UserAccount, self).__init__(**kwargs) + super().__init__(**kwargs) self.name = name self.password = password self.elevation_level = elevation_level @@ -5010,7 +4851,7 @@ def __init__( self.windows_user_configuration = windows_user_configuration -class UserAssignedIdentities(msrest.serialization.Model): +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. @@ -5022,27 +4863,23 @@ class UserAssignedIdentities(msrest.serialization.Model): """ _validation = { - 'principal_id': {'readonly': True}, - 'client_id': {'readonly': True}, + "principal_id": {"readonly": True}, + "client_id": {"readonly": True}, } _attribute_map = { - 'principal_id': {'key': 'principalId', 'type': 'str'}, - 'client_id': {'key': 'clientId', 'type': 'str'}, + "principal_id": {"key": "principalId", "type": "str"}, + "client_id": {"key": "clientId", "type": "str"}, } - def __init__( - self, - **kwargs - ): - """ - """ - super(UserAssignedIdentities, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.principal_id = None self.client_id = None -class UserIdentity(msrest.serialization.Model): +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 @@ -5054,16 +4891,12 @@ class UserIdentity(msrest.serialization.Model): """ _attribute_map = { - 'user_name': {'key': 'userName', 'type': 'str'}, - 'auto_user': {'key': 'autoUser', 'type': 'AutoUserSpecification'}, + "user_name": {"key": "userName", "type": "str"}, + "auto_user": {"key": "autoUser", "type": "AutoUserSpecification"}, } def __init__( - self, - *, - user_name: Optional[str] = None, - auto_user: Optional["AutoUserSpecification"] = None, - **kwargs + self, *, user_name: Optional[str] = None, auto_user: Optional["_models.AutoUserSpecification"] = None, **kwargs ): """ :keyword user_name: The userName and autoUser properties are mutually exclusive; you must @@ -5073,26 +4906,26 @@ def __init__( specify one but not both. :paramtype auto_user: ~azure.mgmt.batch.models.AutoUserSpecification """ - super(UserIdentity, self).__init__(**kwargs) + super().__init__(**kwargs) self.user_name = user_name self.auto_user = auto_user -class VirtualMachineConfiguration(msrest.serialization.Model): +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: Required. 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 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: Required. 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. + :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. @@ -5103,7 +4936,7 @@ class VirtualMachineConfiguration(msrest.serialization.Model): :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 @@ -5125,49 +4958,49 @@ class VirtualMachineConfiguration(msrest.serialization.Model): """ _validation = { - 'image_reference': {'required': True}, - 'node_agent_sku_id': {'required': True}, + "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'}, + "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: "ImageReference", + image_reference: "_models.ImageReference", node_agent_sku_id: str, - windows_configuration: Optional["WindowsConfiguration"] = None, - data_disks: Optional[List["DataDisk"]] = None, + windows_configuration: Optional["_models.WindowsConfiguration"] = None, + data_disks: Optional[List["_models.DataDisk"]] = None, license_type: Optional[str] = None, - container_configuration: Optional["ContainerConfiguration"] = None, - disk_encryption_configuration: Optional["DiskEncryptionConfiguration"] = None, - node_placement_configuration: Optional["NodePlacementConfiguration"] = None, - extensions: Optional[List["VMExtension"]] = None, - os_disk: Optional["OSDisk"] = 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 ): """ - :keyword image_reference: Required. 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. + :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: Required. 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. + :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. @@ -5178,7 +5011,7 @@ def __init__( :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 @@ -5198,7 +5031,7 @@ def __init__( :keyword os_disk: Contains configuration for ephemeral OSDisk settings. :paramtype os_disk: ~azure.mgmt.batch.models.OSDisk """ - super(VirtualMachineConfiguration, self).__init__(**kwargs) + super().__init__(**kwargs) self.image_reference = image_reference self.node_agent_sku_id = node_agent_sku_id self.windows_configuration = windows_configuration @@ -5211,7 +5044,7 @@ def __init__( self.os_disk = os_disk -class VirtualMachineFamilyCoreQuota(msrest.serialization.Model): +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. @@ -5223,36 +5056,32 @@ class VirtualMachineFamilyCoreQuota(msrest.serialization.Model): """ _validation = { - 'name': {'readonly': True}, - 'core_quota': {'readonly': True}, + "name": {"readonly": True}, + "core_quota": {"readonly": True}, } _attribute_map = { - 'name': {'key': 'name', 'type': 'str'}, - 'core_quota': {'key': 'coreQuota', 'type': 'int'}, + "name": {"key": "name", "type": "str"}, + "core_quota": {"key": "coreQuota", "type": "int"}, } - def __init__( - self, - **kwargs - ): - """ - """ - super(VirtualMachineFamilyCoreQuota, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.name = None self.core_quota = None -class VMExtension(msrest.serialization.Model): +class VMExtension(_serialization.Model): """The configuration for virtual machine extensions. All required parameters must be populated in order to send to Azure. - :ivar name: Required. The name of the virtual machine extension. + :ivar name: The name of the virtual machine extension. Required. :vartype name: str - :ivar publisher: Required. The name of the extension handler publisher. + :ivar publisher: The name of the extension handler publisher. Required. :vartype publisher: str - :ivar type: Required. The type of the extensions. + :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 @@ -5260,31 +5089,31 @@ class VMExtension(msrest.serialization.Model): 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 settings: Any object. - :vartype settings: any + :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: any + :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}, + "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'}, - 'settings': {'key': 'settings', 'type': 'object'}, - 'protected_settings': {'key': 'protectedSettings', 'type': 'object'}, - 'provision_after_extensions': {'key': 'provisionAfterExtensions', 'type': '[str]'}, + "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"}, + "settings": {"key": "settings", "type": "object"}, + "protected_settings": {"key": "protectedSettings", "type": "object"}, + "provision_after_extensions": {"key": "provisionAfterExtensions", "type": "[str]"}, } def __init__( @@ -5295,17 +5124,17 @@ def __init__( type: str, type_handler_version: Optional[str] = None, auto_upgrade_minor_version: Optional[bool] = None, - settings: Optional[Any] = None, - protected_settings: Optional[Any] = None, + settings: Optional[JSON] = None, + protected_settings: Optional[JSON] = None, provision_after_extensions: Optional[List[str]] = None, **kwargs ): """ - :keyword name: Required. The name of the virtual machine extension. + :keyword name: The name of the virtual machine extension. Required. :paramtype name: str - :keyword publisher: Required. The name of the extension handler publisher. + :keyword publisher: The name of the extension handler publisher. Required. :paramtype publisher: str - :keyword type: Required. The type of the extensions. + :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 @@ -5313,16 +5142,16 @@ def __init__( 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 settings: Any object. - :paramtype settings: any + :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: any + :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(VMExtension, self).__init__(**kwargs) + super().__init__(**kwargs) self.name = name self.publisher = publisher self.type = type @@ -5333,7 +5162,7 @@ def __init__( self.provision_after_extensions = provision_after_extensions -class WindowsConfiguration(msrest.serialization.Model): +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. @@ -5341,47 +5170,37 @@ class WindowsConfiguration(msrest.serialization.Model): """ _attribute_map = { - 'enable_automatic_updates': {'key': 'enableAutomaticUpdates', 'type': 'bool'}, + "enable_automatic_updates": {"key": "enableAutomaticUpdates", "type": "bool"}, } - def __init__( - self, - *, - enable_automatic_updates: Optional[bool] = None, - **kwargs - ): + def __init__(self, *, enable_automatic_updates: Optional[bool] = None, **kwargs): """ :keyword enable_automatic_updates: If omitted, the default value is true. :paramtype enable_automatic_updates: bool """ - super(WindowsConfiguration, self).__init__(**kwargs) + super().__init__(**kwargs) self.enable_automatic_updates = enable_automatic_updates -class WindowsUserConfiguration(msrest.serialization.Model): +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. Possible values include: "Batch", "Interactive". + 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'}, + "login_mode": {"key": "loginMode", "type": "str"}, } - def __init__( - self, - *, - login_mode: Optional[Union[str, "LoginMode"]] = None, - **kwargs - ): + def __init__(self, *, login_mode: Optional[Union[str, "_models.LoginMode"]] = None, **kwargs): """ :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. Possible values include: "Batch", "Interactive". + is batch mode. Known values are: "Batch" and "Interactive". :paramtype login_mode: str or ~azure.mgmt.batch.models.LoginMode """ - super(WindowsUserConfiguration, self).__init__(**kwargs) + super().__init__(**kwargs) self.login_mode = login_mode diff --git a/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/models/_patch.py b/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/models/_patch.py new file mode 100644 index 000000000000..f7dd32510333 --- /dev/null +++ b/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/models/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/operations/__init__.py b/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/operations/__init__.py index c4a185c29107..484efa0258a1 100644 --- a/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/operations/__init__.py +++ b/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/operations/__init__.py @@ -16,14 +16,20 @@ from ._private_endpoint_connection_operations import PrivateEndpointConnectionOperations from ._pool_operations import PoolOperations +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__ = [ - 'BatchAccountOperations', - 'ApplicationPackageOperations', - 'ApplicationOperations', - 'LocationOperations', - 'Operations', - 'CertificateOperations', - 'PrivateLinkResourceOperations', - 'PrivateEndpointConnectionOperations', - 'PoolOperations', + "BatchAccountOperations", + "ApplicationPackageOperations", + "ApplicationOperations", + "LocationOperations", + "Operations", + "CertificateOperations", + "PrivateLinkResourceOperations", + "PrivateEndpointConnectionOperations", + "PoolOperations", ] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/operations/_application_operations.py b/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/operations/_application_operations.py index cc56b50b13ee..facd897d10bb 100644 --- a/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/operations/_application_operations.py +++ b/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/operations/_application_operations.py @@ -6,193 +6,189 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, Callable, Dict, Iterable, Optional, TypeVar - -from msrest import Serializer - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +import sys +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') -JSONType = Any + +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_create_request( - resource_group_name: str, - account_name: str, - application_name: str, - subscription_id: str, - *, - json: JSONType = None, - content: Any = None, - **kwargs: Any + resource_group_name: str, account_name: str, application_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: - api_version = kwargs.pop('api_version', "2022-06-01") # type: str - content_type = kwargs.pop('content_type', None) # type: Optional[str] + _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", "2022-10-01")) # type: Literal["2022-10-01"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") - 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 + _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'), + "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 = _format_url_section(_url, **path_format_arguments) # Construct parameters - _query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - _query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] if content_type is not None: - _header_parameters['Content-Type'] = _SERIALIZER.header("content_type", content_type, 'str') - _header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest( - method="PUT", - url=_url, - params=_query_parameters, - headers=_header_parameters, - json=json, - content=content, - **kwargs - ) + 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 + resource_group_name: str, account_name: str, application_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: - api_version = kwargs.pop('api_version', "2022-06-01") # type: str + _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", "2022-10-01")) # type: Literal["2022-10-01"] + accept = _headers.pop("Accept", "application/json") - 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 + _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'), + "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 = _format_url_section(_url, **path_format_arguments) # Construct parameters - _query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - _query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] - _header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest( - method="DELETE", - url=_url, - params=_query_parameters, - headers=_header_parameters, - **kwargs - ) + 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 + resource_group_name: str, account_name: str, application_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: - api_version = kwargs.pop('api_version', "2022-06-01") # type: str + _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", "2022-10-01")) # type: Literal["2022-10-01"] + accept = _headers.pop("Accept", "application/json") - 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 + _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'), + "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 = _format_url_section(_url, **path_format_arguments) # Construct parameters - _query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - _query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] - _header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest( - method="GET", - url=_url, - params=_query_parameters, - headers=_header_parameters, - **kwargs - ) + 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, - *, - json: JSONType = None, - content: Any = None, - **kwargs: Any + resource_group_name: str, account_name: str, application_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: - api_version = kwargs.pop('api_version', "2022-06-01") # type: str - content_type = kwargs.pop('content_type', None) # type: Optional[str] + _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", "2022-10-01")) # type: Literal["2022-10-01"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") - 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 + _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'), + "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 = _format_url_section(_url, **path_format_arguments) # Construct parameters - _query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - _query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] if content_type is not None: - _header_parameters['Content-Type'] = _SERIALIZER.header("content_type", content_type, 'str') - _header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest( - method="PATCH", - url=_url, - params=_query_parameters, - headers=_header_parameters, - json=json, - content=content, - **kwargs - ) + return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs) def build_list_request( @@ -203,96 +199,178 @@ def build_list_request( maxresults: Optional[int] = None, **kwargs: Any ) -> HttpRequest: - api_version = kwargs.pop('api_version', "2022-06-01") # type: str + _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", "2022-10-01")) # type: Literal["2022-10-01"] + accept = _headers.pop("Accept", "application/json") - 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 + _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'), + "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 = _format_url_section(_url, **path_format_arguments) # Construct parameters - _query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] if maxresults is not None: - _query_parameters['maxresults'] = _SERIALIZER.query("maxresults", maxresults, 'int') - _query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["maxresults"] = _SERIALIZER.query("maxresults", maxresults, "int") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] - _header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') - - return HttpRequest( - method="GET", - url=_url, - params=_query_parameters, - headers=_header_parameters, - **kwargs - ) - -class ApplicationOperations(object): - """ApplicationOperations 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: ~azure.mgmt.batch.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. + _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, client, config, serializer, deserializer): - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + 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 + @overload def create( self, resource_group_name: str, account_name: str, application_name: str, - parameters: Optional["_models.Application"] = None, + parameters: Optional[_models.Application] = None, + *, + content_type: str = "application/json", **kwargs: Any - ) -> "_models.Application": + ) -> _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. + :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) + :return: Application or the result of cls(response) :rtype: ~azure.mgmt.batch.models.Application - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Application"] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = kwargs.pop('api_version', "2022-06-01") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + @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. - if parameters is not None: - _json = self._serialize.body(parameters, '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 model 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 = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.Application] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters else: - _json = None + if parameters is not None: + _json = self._serialize.body(parameters, "Application") + else: + _json = None request = build_create_request( resource_group_name=resource_group_name, @@ -302,78 +380,85 @@ def create( api_version=api_version, content_type=content_type, json=_json, - template_url=self.create.metadata['url'], + content=_content, + template_url=self.create.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + 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) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('Application', pipeline_response) + 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}"} # type: ignore - + create.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/applications/{applicationName}"} # type: ignore @distributed_trace def delete( # pylint: disable=inconsistent-return-statements - self, - resource_group_name: str, - account_name: str, - application_name: str, - **kwargs: Any + 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. + :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) + :return: None or the result of cls(response) :rtype: None - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + 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', "2022-06-01") # type: str + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[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'], + template_url=self.delete.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + 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, 204]: @@ -383,70 +468,138 @@ def delete( # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) - delete.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/applications/{applicationName}"} # type: ignore - + delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/applications/{applicationName}"} # type: ignore @distributed_trace def get( - self, - resource_group_name: str, - account_name: str, - application_name: str, - **kwargs: Any - ) -> "_models.Application": + 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. + :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) + :return: Application or the result of cls(response) :rtype: ~azure.mgmt.batch.models.Application - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Application"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + 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', "2022-06-01") # type: str + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.Application] - 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'], + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + 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) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('Application', pipeline_response) + 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}"} # type: ignore + get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/applications/{applicationName}"} # type: ignore + @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( @@ -454,34 +607,54 @@ def update( resource_group_name: str, account_name: str, application_name: str, - parameters: "_models.Application", + parameters: Union[_models.Application, IO], **kwargs: Any - ) -> "_models.Application": + ) -> _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. + :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. - :type parameters: ~azure.mgmt.batch.models.Application + :param parameters: The parameters for the request. Is either a model 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) + :return: Application or the result of cls(response) :rtype: ~azure.mgmt.batch.models.Application - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Application"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - - api_version = kwargs.pop('api_version', "2022-06-01") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] - - _json = self._serialize.body(parameters, 'Application') + 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", self._config.api_version) + ) # type: Literal["2022-10-01"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.Application] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "Application") request = build_update_request( resource_group_name=resource_group_name, @@ -491,88 +664,99 @@ def update( api_version=api_version, content_type=content_type, json=_json, - template_url=self.update.metadata['url'], + content=_content, + template_url=self.update.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + 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) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('Application', pipeline_response) + 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}"} # type: ignore - + update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/applications/{applicationName}"} # type: ignore @distributed_trace def list( - self, - resource_group_name: str, - account_name: str, - maxresults: Optional[int] = None, - **kwargs: Any - ) -> Iterable["_models.ListApplicationsResult"]: + 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. + :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 ListApplicationsResult or the result of - cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.batch.models.ListApplicationsResult] - :raises: ~azure.core.exceptions.HttpResponseError + :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: """ - api_version = kwargs.pop('api_version', "2022-06-01") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.ListApplicationsResult] - cls = kwargs.pop('cls', None) # type: ClsType["_models.ListApplicationsResult"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + 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, - api_version=api_version, maxresults=maxresults, - template_url=self.list.metadata['url'], + 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) + request.url = self._client.format_url(request.url) # type: ignore else: - - request = build_list_request( - resource_group_name=resource_group_name, - account_name=account_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - maxresults=maxresults, - template_url=next_link, + # 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.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request @@ -586,10 +770,8 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -599,8 +781,6 @@ def get_next(next_link=None): return pipeline_response + return ItemPaged(get_next, extract_data) - return ItemPaged( - get_next, extract_data - ) - list.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/applications"} # type: ignore + list.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/applications"} # type: ignore diff --git a/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/operations/_application_package_operations.py b/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/operations/_application_package_operations.py index ab8fda23ca5b..f288764a793b 100644 --- a/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/operations/_application_package_operations.py +++ b/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/operations/_application_package_operations.py @@ -6,73 +6,86 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, Callable, Dict, Iterable, Optional, TypeVar - -from msrest import Serializer - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +import sys +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') -JSONType = Any + +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_activate_request( resource_group_name: str, account_name: str, application_name: str, version_name: str, subscription_id: str, - *, - json: JSONType = None, - content: Any = None, **kwargs: Any ) -> HttpRequest: - api_version = kwargs.pop('api_version', "2022-06-01") # type: str - content_type = kwargs.pop('content_type', None) # type: Optional[str] + _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", "2022-10-01")) # type: Literal["2022-10-01"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") - 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 + _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'), + "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 = _format_url_section(_url, **path_format_arguments) # Construct parameters - _query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - _query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] if content_type is not None: - _header_parameters['Content-Type'] = _SERIALIZER.header("content_type", content_type, 'str') - _header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest( - method="POST", - url=_url, - params=_query_parameters, - headers=_header_parameters, - json=json, - content=content, - **kwargs - ) + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) def build_create_request( @@ -81,46 +94,45 @@ def build_create_request( application_name: str, version_name: str, subscription_id: str, - *, - json: JSONType = None, - content: Any = None, **kwargs: Any ) -> HttpRequest: - api_version = kwargs.pop('api_version', "2022-06-01") # type: str - content_type = kwargs.pop('content_type', None) # type: Optional[str] + _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", "2022-10-01")) # type: Literal["2022-10-01"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") - 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 + _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'), + "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 = _format_url_section(_url, **path_format_arguments) # Construct parameters - _query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - _query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] if content_type is not None: - _header_parameters['Content-Type'] = _SERIALIZER.header("content_type", content_type, 'str') - _header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest( - method="PUT", - url=_url, - params=_query_parameters, - headers=_header_parameters, - json=json, - content=content, - **kwargs - ) + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) def build_delete_request( @@ -131,36 +143,40 @@ def build_delete_request( subscription_id: str, **kwargs: Any ) -> HttpRequest: - api_version = kwargs.pop('api_version', "2022-06-01") # type: str + _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", "2022-10-01")) # type: Literal["2022-10-01"] + accept = _headers.pop("Accept", "application/json") - 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 + _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'), + "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 = _format_url_section(_url, **path_format_arguments) # Construct parameters - _query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - _query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] - _header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest( - method="DELETE", - url=_url, - params=_query_parameters, - headers=_header_parameters, - **kwargs - ) + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) def build_get_request( @@ -171,36 +187,40 @@ def build_get_request( subscription_id: str, **kwargs: Any ) -> HttpRequest: - api_version = kwargs.pop('api_version', "2022-06-01") # type: str + _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", "2022-10-01")) # type: Literal["2022-10-01"] + accept = _headers.pop("Accept", "application/json") - 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 + _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'), + "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 = _format_url_section(_url, **path_format_arguments) # Construct parameters - _query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - _query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] - _header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest( - method="GET", - url=_url, - params=_query_parameters, - headers=_header_parameters, - **kwargs - ) + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_list_request( @@ -212,99 +232,193 @@ def build_list_request( maxresults: Optional[int] = None, **kwargs: Any ) -> HttpRequest: - api_version = kwargs.pop('api_version', "2022-06-01") # type: str + _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", "2022-10-01")) # type: Literal["2022-10-01"] + accept = _headers.pop("Accept", "application/json") - 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 + _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'), + "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 = _format_url_section(_url, **path_format_arguments) # Construct parameters - _query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] if maxresults is not None: - _query_parameters['maxresults'] = _SERIALIZER.query("maxresults", maxresults, 'int') - _query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["maxresults"] = _SERIALIZER.query("maxresults", maxresults, "int") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] - _header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') - - return HttpRequest( - method="GET", - url=_url, - params=_query_parameters, - headers=_header_parameters, - **kwargs - ) - -class ApplicationPackageOperations(object): - """ApplicationPackageOperations 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: ~azure.mgmt.batch.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. + _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, client, config, serializer, deserializer): - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + 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 + @overload def activate( self, resource_group_name: str, account_name: str, application_name: str, version_name: str, - parameters: "_models.ActivateApplicationPackageParameters", + parameters: _models.ActivateApplicationPackageParameters, + *, + content_type: str = "application/json", **kwargs: Any - ) -> "_models.ApplicationPackage": + ) -> _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. + :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. + :param version_name: The version of the application. Required. :type version_name: str - :param parameters: The parameters for the request. + :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) + :return: ApplicationPackage or the result of cls(response) :rtype: ~azure.mgmt.batch.models.ApplicationPackage - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.ApplicationPackage"] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = kwargs.pop('api_version', "2022-06-01") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + @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. - _json = self._serialize.body(parameters, 'ActivateApplicationPackageParameters') + :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 model 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 = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.ApplicationPackage] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "ActivateApplicationPackageParameters") request = build_activate_request( resource_group_name=resource_group_name, @@ -315,75 +429,172 @@ def activate( api_version=api_version, content_type=content_type, json=_json, - template_url=self.activate.metadata['url'], + content=_content, + template_url=self.activate.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + 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) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('ApplicationPackage', pipeline_response) + 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"} # type: ignore + activate.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/applications/{applicationName}/versions/{versionName}/activate"} # type: ignore - - @distributed_trace + @overload def create( self, resource_group_name: str, account_name: str, application_name: str, version_name: str, - parameters: Optional["_models.ApplicationPackage"] = None, + parameters: Optional[_models.ApplicationPackage] = None, + *, + content_type: str = "application/json", **kwargs: Any - ) -> "_models.ApplicationPackage": + ) -> _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. + :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. + :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) + :return: ApplicationPackage or the result of cls(response) :rtype: ~azure.mgmt.batch.models.ApplicationPackage - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.ApplicationPackage"] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = kwargs.pop('api_version', "2022-06-01") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + @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. - if parameters is not None: - _json = self._serialize.body(parameters, 'ApplicationPackage') + :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 model 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 = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.ApplicationPackage] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters else: - _json = None + if parameters is not None: + _json = self._serialize.body(parameters, "ApplicationPackage") + else: + _json = None request = build_create_request( resource_group_name=resource_group_name, @@ -394,65 +605,70 @@ def create( api_version=api_version, content_type=content_type, json=_json, - template_url=self.create.metadata['url'], + content=_content, + template_url=self.create.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + 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) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('ApplicationPackage', pipeline_response) + 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}"} # type: ignore - + create.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/applications/{applicationName}/versions/{versionName}"} # type: ignore @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 + 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. + :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. + :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) + :return: None or the result of cls(response) :rtype: None - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + 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', "2022-06-01") # type: str + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[None] - request = build_delete_request( resource_group_name=resource_group_name, account_name=account_name, @@ -460,16 +676,17 @@ def delete( # pylint: disable=inconsistent-return-statements version_name=version_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.delete.metadata['url'], + template_url=self.delete.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + 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, 204]: @@ -479,42 +696,45 @@ def delete( # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) - delete.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/applications/{applicationName}/versions/{versionName}"} # type: ignore - + delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/applications/{applicationName}/versions/{versionName}"} # type: ignore @distributed_trace def get( - self, - resource_group_name: str, - account_name: str, - application_name: str, - version_name: str, - **kwargs: Any - ) -> "_models.ApplicationPackage": + 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. + :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. + :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) + :return: ApplicationPackage or the result of cls(response) :rtype: ~azure.mgmt.batch.models.ApplicationPackage - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.ApplicationPackage"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + 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', "2022-06-01") # type: str + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.ApplicationPackage] - request = build_get_request( resource_group_name=resource_group_name, account_name=account_name, @@ -522,31 +742,31 @@ def get( version_name=version_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get.metadata['url'], + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + 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) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('ApplicationPackage', pipeline_response) + 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}"} # type: ignore - + get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/applications/{applicationName}/versions/{versionName}"} # type: ignore @distributed_trace def list( @@ -556,59 +776,73 @@ def list( application_name: str, maxresults: Optional[int] = None, **kwargs: Any - ) -> Iterable["_models.ListApplicationPackagesResult"]: + ) -> 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. + :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 ListApplicationPackagesResult or the result of - cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.batch.models.ListApplicationPackagesResult] - :raises: ~azure.core.exceptions.HttpResponseError + :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: """ - api_version = kwargs.pop('api_version', "2022-06-01") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.ListApplicationPackagesResult] - cls = kwargs.pop('cls', None) # type: ClsType["_models.ListApplicationPackagesResult"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + 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, - api_version=api_version, maxresults=maxresults, - template_url=self.list.metadata['url'], + 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) + request.url = self._client.format_url(request.url) # type: ignore else: - - request = build_list_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, - maxresults=maxresults, - template_url=next_link, + # 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.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request @@ -622,10 +856,8 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -635,8 +867,6 @@ def get_next(next_link=None): return pipeline_response + return ItemPaged(get_next, extract_data) - return ItemPaged( - get_next, extract_data - ) - list.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/applications/{applicationName}/versions"} # type: ignore + list.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/applications/{applicationName}/versions"} # type: ignore diff --git a/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/operations/_batch_account_operations.py b/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/operations/_batch_account_operations.py index c184cb9ec99f..b5b29644a481 100644 --- a/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/operations/_batch_account_operations.py +++ b/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/operations/_batch_account_operations.py @@ -6,537 +6,503 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, Callable, Dict, Iterable, Optional, TypeVar, Union - -from msrest import Serializer - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +import sys +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') -JSONType = Any + +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_create_request_initial( - resource_group_name: str, - account_name: str, - subscription_id: str, - *, - json: JSONType = None, - content: Any = None, - **kwargs: Any + +def build_create_request( + resource_group_name: str, account_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: - api_version = kwargs.pop('api_version', "2022-06-01") # type: str - content_type = kwargs.pop('content_type', None) # type: Optional[str] + _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", "2022-10-01")) # type: Literal["2022-10-01"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") - accept = "application/json" # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}") # pylint: disable=line-too-long + _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'), + "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 = _format_url_section(_url, **path_format_arguments) # Construct parameters - _query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - _query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] if content_type is not None: - _header_parameters['Content-Type'] = _SERIALIZER.header("content_type", content_type, 'str') - _header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest( - method="PUT", - url=_url, - params=_query_parameters, - headers=_header_parameters, - json=json, - content=content, - **kwargs - ) + 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, - *, - json: JSONType = None, - content: Any = None, - **kwargs: Any + resource_group_name: str, account_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: - api_version = kwargs.pop('api_version', "2022-06-01") # type: str - content_type = kwargs.pop('content_type', None) # type: Optional[str] + _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", "2022-10-01")) # type: Literal["2022-10-01"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") - accept = "application/json" # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}") # pylint: disable=line-too-long + _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'), + "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 = _format_url_section(_url, **path_format_arguments) # Construct parameters - _query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - _query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] if content_type is not None: - _header_parameters['Content-Type'] = _SERIALIZER.header("content_type", content_type, 'str') - _header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') - - return HttpRequest( - method="PATCH", - url=_url, - params=_query_parameters, - headers=_header_parameters, - json=json, - content=content, - **kwargs - ) - - -def build_delete_request_initial( - resource_group_name: str, - account_name: str, - subscription_id: str, - **kwargs: Any + _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: - api_version = kwargs.pop('api_version', "2022-06-01") # type: str + _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", "2022-10-01")) # type: Literal["2022-10-01"] + accept = _headers.pop("Accept", "application/json") - accept = "application/json" # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}") # pylint: disable=line-too-long + _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'), + "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 = _format_url_section(_url, **path_format_arguments) # Construct parameters - _query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - _query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] - _header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') - - return HttpRequest( - method="DELETE", - url=_url, - params=_query_parameters, - headers=_header_parameters, - **kwargs - ) - - -def build_get_request( - resource_group_name: str, - account_name: str, - subscription_id: str, - **kwargs: Any -) -> HttpRequest: - api_version = kwargs.pop('api_version', "2022-06-01") # type: str + _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 = kwargs.pop("api_version", _params.pop("api-version", "2022-10-01")) # type: Literal["2022-10-01"] + accept = _headers.pop("Accept", "application/json") - accept = "application/json" # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}") # pylint: disable=line-too-long + _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'), + "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 = _format_url_section(_url, **path_format_arguments) # Construct parameters - _query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - _query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] - _header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest( - method="GET", - url=_url, - params=_query_parameters, - headers=_header_parameters, - **kwargs - ) + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_list_request( - subscription_id: str, - **kwargs: Any -) -> HttpRequest: - api_version = kwargs.pop('api_version', "2022-06-01") # type: str +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 = kwargs.pop("api_version", _params.pop("api-version", "2022-10-01")) # type: Literal["2022-10-01"] + accept = _headers.pop("Accept", "application/json") - 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'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - _query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - _query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] - _header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') - - return HttpRequest( - method="GET", - url=_url, - params=_query_parameters, - headers=_header_parameters, - **kwargs - ) - - -def build_list_by_resource_group_request( - resource_group_name: str, - subscription_id: str, - **kwargs: Any -) -> HttpRequest: - api_version = kwargs.pop('api_version', "2022-06-01") # type: str + _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 = kwargs.pop("api_version", _params.pop("api-version", "2022-10-01")) # type: Literal["2022-10-01"] + accept = _headers.pop("Accept", "application/json") - accept = "application/json" # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts") # pylint: disable=line-too-long + _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'), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - _query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - _query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] - _header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest( - method="GET", - url=_url, - params=_query_parameters, - headers=_header_parameters, - **kwargs - ) + 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 + resource_group_name: str, account_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: - api_version = kwargs.pop('api_version', "2022-06-01") # type: str + _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", "2022-10-01")) # type: Literal["2022-10-01"] + accept = _headers.pop("Accept", "application/json") - 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 + _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'), + "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 = _format_url_section(_url, **path_format_arguments) # Construct parameters - _query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - _query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] - _header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest( - method="POST", - url=_url, - params=_query_parameters, - headers=_header_parameters, - **kwargs - ) + 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, - *, - json: JSONType = None, - content: Any = None, - **kwargs: Any + resource_group_name: str, account_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: - api_version = kwargs.pop('api_version', "2022-06-01") # type: str - content_type = kwargs.pop('content_type', None) # type: Optional[str] + _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", "2022-10-01")) # type: Literal["2022-10-01"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") - 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 + _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'), + "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 = _format_url_section(_url, **path_format_arguments) # Construct parameters - _query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - _query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] if content_type is not None: - _header_parameters['Content-Type'] = _SERIALIZER.header("content_type", content_type, 'str') - _header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest( - method="POST", - url=_url, - params=_query_parameters, - headers=_header_parameters, - json=json, - content=content, - **kwargs - ) + 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 + resource_group_name: str, account_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: - api_version = kwargs.pop('api_version', "2022-06-01") # type: str + _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", "2022-10-01")) # type: Literal["2022-10-01"] + accept = _headers.pop("Accept", "application/json") - 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 + _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'), + "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 = _format_url_section(_url, **path_format_arguments) # Construct parameters - _query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - _query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] - _header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest( - method="POST", - url=_url, - params=_query_parameters, - headers=_header_parameters, - **kwargs - ) + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) def build_list_detectors_request( - resource_group_name: str, - subscription_id: str, - account_name: str, - **kwargs: Any + resource_group_name: str, account_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: - api_version = kwargs.pop('api_version', "2022-06-01") # type: str + _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", "2022-10-01")) # type: Literal["2022-10-01"] + accept = _headers.pop("Accept", "application/json") - 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 + _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]+$'), + "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 = _format_url_section(_url, **path_format_arguments) # Construct parameters - _query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - _query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] - _header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest( - method="GET", - url=_url, - params=_query_parameters, - headers=_header_parameters, - **kwargs - ) + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_get_detector_request( - resource_group_name: str, - subscription_id: str, - account_name: str, - detector_id: str, - **kwargs: Any + resource_group_name: str, account_name: str, detector_id: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: - api_version = kwargs.pop('api_version', "2022-06-01") # type: str + _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", "2022-10-01")) # type: Literal["2022-10-01"] + accept = _headers.pop("Accept", "application/json") - 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 + _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'), + "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 = _format_url_section(_url, **path_format_arguments) # Construct parameters - _query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - _query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] - _header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest( - method="GET", - url=_url, - params=_query_parameters, - headers=_header_parameters, - **kwargs - ) + 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 + resource_group_name: str, account_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: - api_version = kwargs.pop('api_version', "2022-06-01") # type: str + _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", "2022-10-01")) # type: Literal["2022-10-01"] + accept = _headers.pop("Accept", "application/json") - 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 + _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'), + "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 = _format_url_section(_url, **path_format_arguments) # Construct parameters - _query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - _query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] - _header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') - - return HttpRequest( - method="GET", - url=_url, - params=_query_parameters, - headers=_header_parameters, - **kwargs - ) - -class BatchAccountOperations(object): - """BatchAccountOperations 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: ~azure.mgmt.batch.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. + _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, client, config, serializer, deserializer): - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + 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: "_models.BatchAccountCreateParameters", + parameters: Union[_models.BatchAccountCreateParameters, IO], **kwargs: Any - ) -> Optional["_models.BatchAccount"]: - cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.BatchAccount"]] + ) -> Optional[_models.BatchAccount]: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - - api_version = kwargs.pop('api_version', "2022-06-01") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] - - _json = self._serialize.body(parameters, 'BatchAccountCreateParameters') - - request = build_create_request_initial( + 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", self._config.api_version) + ) # type: Literal["2022-10-01"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.BatchAccount]] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, 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, - template_url=self._create_initial.metadata['url'], + 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) + request.url = self._client.format_url(request.url) # type: ignore - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + 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]: @@ -546,42 +512,127 @@ def _create_initial( deserialized = None response_headers = {} if response.status_code == 200: - deserialized = self._deserialize('BatchAccount', pipeline_response) + 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')) - + 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}"} # type: ignore + _create_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}"} # type: ignore + @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: "_models.BatchAccountCreateParameters", + parameters: Union[_models.BatchAccountCreateParameters, IO], **kwargs: Any - ) -> LROPoller["_models.BatchAccount"]: + ) -> 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/. + http://accountname.region.batch.azure.com/. Required. :type account_name: str - :param parameters: Additional parameters for account creation. - :type parameters: ~azure.mgmt.batch.models.BatchAccountCreateParameters + :param parameters: Additional parameters for account creation. Is either a model 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 @@ -593,82 +644,164 @@ def begin_create( :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 + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2022-06-01") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] - polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType["_models.BatchAccount"] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + _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", self._config.api_version) + ) # type: Literal["2022-10-01"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.BatchAccount] + 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_initial( + raw_result = self._create_initial( # type: ignore 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, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - response = pipeline_response.http_response - deserialized = self._deserialize('BatchAccount', pipeline_response) + deserialized = self._deserialize("BatchAccount", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - - if polling is True: polling_method = ARMPolling(lro_delay, lro_options={'final-state-via': 'location'}, **kwargs) - elif polling is False: polling_method = NoPolling() - else: polling_method = polling + 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 + deserialization_callback=get_long_running_output, ) return LROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_create.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}"} # type: ignore + begin_create.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}"} # type: ignore - @distributed_trace + @overload def update( self, resource_group_name: str, account_name: str, - parameters: "_models.BatchAccountUpdateParameters", + parameters: _models.BatchAccountUpdateParameters, + *, + content_type: str = "application/json", **kwargs: Any - ) -> "_models.BatchAccount": + ) -> _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. + :param account_name: The name of the Batch account. Required. :type account_name: str - :param parameters: Additional parameters for account update. + :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 model 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) + :return: BatchAccount or the result of cls(response) :rtype: ~azure.mgmt.batch.models.BatchAccount - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.BatchAccount"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) - api_version = kwargs.pop('api_version', "2022-06-01") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - _json = self._serialize.body(parameters, 'BatchAccountUpdateParameters') + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.BatchAccount] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "BatchAccountUpdateParameters") request = build_update_request( resource_group_name=resource_group_name, @@ -677,62 +810,68 @@ def update( api_version=api_version, content_type=content_type, json=_json, - template_url=self.update.metadata['url'], + content=_content, + template_url=self.update.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + 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) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('BatchAccount', pipeline_response) + 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}"} # type: ignore - + update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}"} # type: ignore def _delete_initial( # pylint: disable=inconsistent-return-statements - self, - resource_group_name: str, - account_name: str, - **kwargs: Any + self, resource_group_name: str, account_name: str, **kwargs: Any ) -> None: - cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + 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', "2022-06-01") # type: str + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[None] - - request = build_delete_request_initial( + 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'], + template_url=self._delete_initial.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + 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, 204]: @@ -741,28 +880,22 @@ def _delete_initial( # pylint: disable=inconsistent-return-statements 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')) - + 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}"} # type: ignore - + _delete_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}"} # type: ignore @distributed_trace - def begin_delete( # pylint: disable=inconsistent-return-statements - self, - resource_group_name: str, - account_name: str, - **kwargs: Any - ) -> LROPoller[None]: + 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. + :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. @@ -774,143 +907,167 @@ def begin_delete( # pylint: disable=inconsistent-return-statements 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 + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2022-06-01") # type: str - 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] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[None] + 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._delete_initial( + 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, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) - def get_long_running_output(pipeline_response): + 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 = ARMPolling(lro_delay, lro_options={'final-state-via': 'location'}, **kwargs) - elif polling is False: polling_method = NoPolling() - else: polling_method = polling + 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 + deserialization_callback=get_long_running_output, ) return LROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_delete.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}"} # type: ignore + begin_delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}"} # type: ignore @distributed_trace - def get( - self, - resource_group_name: str, - account_name: str, - **kwargs: Any - ) -> "_models.BatchAccount": + 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. + :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) + :return: BatchAccount or the result of cls(response) :rtype: ~azure.mgmt.batch.models.BatchAccount - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.BatchAccount"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + 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', "2022-06-01") # type: str + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.BatchAccount] - 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'], + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + 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) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('BatchAccount', pipeline_response) + 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}"} # type: ignore - + get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}"} # type: ignore @distributed_trace - def list( - self, - **kwargs: Any - ) -> Iterable["_models.BatchAccountListResult"]: + 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 BatchAccountListResult or the result of - cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.batch.models.BatchAccountListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :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: """ - api_version = kwargs.pop('api_version', "2022-06-01") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.BatchAccountListResult] - cls = kwargs.pop('cls', None) # type: ClsType["_models.BatchAccountListResult"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + 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'], + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore else: - - request = build_list_request( - subscription_id=self._config.subscription_id, - api_version=api_version, - template_url=next_link, + # 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.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request @@ -924,10 +1081,8 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -937,57 +1092,67 @@ def get_next(next_link=None): return pipeline_response + return ItemPaged(get_next, extract_data) - return ItemPaged( - get_next, extract_data - ) - list.metadata = {'url': "/subscriptions/{subscriptionId}/providers/Microsoft.Batch/batchAccounts"} # type: ignore + list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Batch/batchAccounts"} # type: ignore @distributed_trace - def list_by_resource_group( - self, - resource_group_name: str, - **kwargs: Any - ) -> Iterable["_models.BatchAccountListResult"]: + 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 BatchAccountListResult or the result of - cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.batch.models.BatchAccountListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :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: """ - api_version = kwargs.pop('api_version', "2022-06-01") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.BatchAccountListResult] - cls = kwargs.pop('cls', None) # type: ClsType["_models.BatchAccountListResult"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + 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'], + 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) + request.url = self._client.format_url(request.url) # type: ignore else: - - 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=next_link, + # 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.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request @@ -1001,10 +1166,8 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -1014,55 +1177,59 @@ def get_next(next_link=None): return pipeline_response + return ItemPaged(get_next, extract_data) - return ItemPaged( - get_next, extract_data - ) - list_by_resource_group.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts"} # type: ignore + list_by_resource_group.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts"} # type: ignore @distributed_trace def synchronize_auto_storage_keys( # pylint: disable=inconsistent-return-statements - self, - resource_group_name: str, - account_name: str, - **kwargs: Any + 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. + :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) + :return: None or the result of cls(response) :rtype: None - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) - api_version = kwargs.pop('api_version', "2022-06-01") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[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'], + 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) + request.url = self._client.format_url(request.url) # type: ignore - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + 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 [204]: @@ -1072,17 +1239,82 @@ def synchronize_auto_storage_keys( # pylint: disable=inconsistent-return-statem if cls: return cls(pipeline_response, None, {}) - synchronize_auto_storage_keys.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/syncAutoStorageKeys"} # type: ignore + synchronize_auto_storage_keys.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/syncAutoStorageKeys"} # type: ignore + + @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: "_models.BatchAccountRegenerateKeyParameters", + parameters: Union[_models.BatchAccountRegenerateKeyParameters, IO], **kwargs: Any - ) -> "_models.BatchAccountKeys": + ) -> _models.BatchAccountKeys: """Regenerates the specified account key for the Batch account. This operation applies only to Batch accounts with allowedAuthenticationModes containing @@ -1091,26 +1323,45 @@ def regenerate_key( 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. + :param account_name: The name of the Batch account. Required. :type account_name: str - :param parameters: The type of key to regenerate. - :type parameters: ~azure.mgmt.batch.models.BatchAccountRegenerateKeyParameters + :param parameters: The type of key to regenerate. Is either a model 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) + :return: BatchAccountKeys or the result of cls(response) :rtype: ~azure.mgmt.batch.models.BatchAccountKeys - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.BatchAccountKeys"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + 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', "2022-06-01") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.BatchAccountKeys] - _json = self._serialize.body(parameters, 'BatchAccountRegenerateKeyParameters') + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "BatchAccountRegenerateKeyParameters") request = build_regenerate_key_request( resource_group_name=resource_group_name, @@ -1119,39 +1370,35 @@ def regenerate_key( api_version=api_version, content_type=content_type, json=_json, - template_url=self.regenerate_key.metadata['url'], + 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) + request.url = self._client.format_url(request.url) # type: ignore - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + 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) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('BatchAccountKeys', pipeline_response) + 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"} # type: ignore - + regenerate_key.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/regenerateKeys"} # type: ignore @distributed_trace - def get_keys( - self, - resource_group_name: str, - account_name: str, - **kwargs: Any - ) -> "_models.BatchAccountKeys": + 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 @@ -1160,103 +1407,124 @@ def get_keys( 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. + :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) + :return: BatchAccountKeys or the result of cls(response) :rtype: ~azure.mgmt.batch.models.BatchAccountKeys - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.BatchAccountKeys"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + 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', "2022-06-01") # type: str + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.BatchAccountKeys] - 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'], + template_url=self.get_keys.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + 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) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('BatchAccountKeys', pipeline_response) + 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"} # type: ignore - + get_keys.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/listKeys"} # type: ignore @distributed_trace def list_detectors( - self, - resource_group_name: str, - account_name: str, - **kwargs: Any - ) -> Iterable["_models.DetectorListResult"]: + 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. + :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 DetectorListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.batch.models.DetectorListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :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: """ - api_version = kwargs.pop('api_version', "2022-06-01") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.DetectorListResult] - cls = kwargs.pop('cls', None) # type: ClsType["_models.DetectorListResult"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + 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, - subscription_id=self._config.subscription_id, account_name=account_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_detectors.metadata['url'], + template_url=self.list_detectors.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore else: - - request = build_list_detectors_request( - resource_group_name=resource_group_name, - subscription_id=self._config.subscription_id, - account_name=account_name, - api_version=api_version, - template_url=next_link, + # 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.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request @@ -1270,10 +1538,8 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -1283,81 +1549,80 @@ def get_next(next_link=None): return pipeline_response + return ItemPaged(get_next, extract_data) - return ItemPaged( - get_next, extract_data - ) - list_detectors.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/detectors"} # type: ignore + list_detectors.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/detectors"} # type: ignore @distributed_trace def get_detector( - self, - resource_group_name: str, - account_name: str, - detector_id: str, - **kwargs: Any - ) -> "_models.DetectorResponse": + 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. + :param account_name: The name of the Batch account. Required. :type account_name: str - :param detector_id: The name of the detector. + :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) + :return: DetectorResponse or the result of cls(response) :rtype: ~azure.mgmt.batch.models.DetectorResponse - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.DetectorResponse"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) - api_version = kwargs.pop('api_version', "2022-06-01") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.DetectorResponse] - request = build_get_detector_request( resource_group_name=resource_group_name, - subscription_id=self._config.subscription_id, 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'], + template_url=self.get_detector.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + 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) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('DetectorResponse', pipeline_response) + 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}"} # type: ignore - + get_detector.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/detectors/{detectorId}"} # type: ignore @distributed_trace def list_outbound_network_dependencies_endpoints( - self, - resource_group_name: str, - account_name: str, - **kwargs: Any - ) -> Iterable["_models.OutboundEnvironmentEndpointCollection"]: + 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 @@ -1366,47 +1631,62 @@ def list_outbound_network_dependencies_endpoints( 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. + :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 OutboundEnvironmentEndpointCollection or the - result of cls(response) - :rtype: - ~azure.core.paging.ItemPaged[~azure.mgmt.batch.models.OutboundEnvironmentEndpointCollection] - :raises: ~azure.core.exceptions.HttpResponseError + :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: """ - api_version = kwargs.pop('api_version', "2022-06-01") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.OutboundEnvironmentEndpointCollection] - cls = kwargs.pop('cls', None) # type: ClsType["_models.OutboundEnvironmentEndpointCollection"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + 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'], + 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) + request.url = self._client.format_url(request.url) # type: ignore else: - - 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=next_link, + # 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.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request @@ -1420,10 +1700,8 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -1433,8 +1711,6 @@ def get_next(next_link=None): return pipeline_response + return ItemPaged(get_next, extract_data) - return ItemPaged( - get_next, extract_data - ) - list_outbound_network_dependencies_endpoints.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/outboundNetworkDependenciesEndpoints"} # type: ignore + list_outbound_network_dependencies_endpoints.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/outboundNetworkDependenciesEndpoints"} # type: ignore diff --git a/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/operations/_certificate_operations.py b/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/operations/_certificate_operations.py index 8791ce8f2bfa..e9a35a907db2 100644 --- a/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/operations/_certificate_operations.py +++ b/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/operations/_certificate_operations.py @@ -6,29 +6,43 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, Callable, Dict, Iterable, Optional, TypeVar, Union - -from msrest import Serializer - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +import sys +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') -JSONType = Any + +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_batch_account_request( resource_group_name: str, account_name: str, @@ -39,40 +53,40 @@ def build_list_by_batch_account_request( filter: Optional[str] = None, **kwargs: Any ) -> HttpRequest: - api_version = kwargs.pop('api_version', "2022-06-01") # type: str + _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", "2022-10-01")) # type: Literal["2022-10-01"] + accept = _headers.pop("Accept", "application/json") - 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 + _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'), + "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 = _format_url_section(_url, **path_format_arguments) # Construct parameters - _query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] if maxresults is not None: - _query_parameters['maxresults'] = _SERIALIZER.query("maxresults", maxresults, 'int') + _params["maxresults"] = _SERIALIZER.query("maxresults", maxresults, "int") if select is not None: - _query_parameters['$select'] = _SERIALIZER.query("select", select, 'str') + _params["$select"] = _SERIALIZER.query("select", select, "str") if filter is not None: - _query_parameters['$filter'] = _SERIALIZER.query("filter", filter, 'str') - _query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] - _header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest( - method="GET", - url=_url, - params=_query_parameters, - headers=_header_parameters, - **kwargs - ) + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_create_request( @@ -81,50 +95,48 @@ def build_create_request( certificate_name: str, subscription_id: str, *, - json: JSONType = None, - content: Any = None, if_match: Optional[str] = None, if_none_match: Optional[str] = None, **kwargs: Any ) -> HttpRequest: - api_version = kwargs.pop('api_version', "2022-06-01") # type: str - content_type = kwargs.pop('content_type', None) # type: Optional[str] + _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", "2022-10-01")) # type: Literal["2022-10-01"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") - 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 + _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'), + "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 = _format_url_section(_url, **path_format_arguments) # Construct parameters - _query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - _query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] if if_match is not None: - _header_parameters['If-Match'] = _SERIALIZER.header("if_match", if_match, 'str') + _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") if if_none_match is not None: - _header_parameters['If-None-Match'] = _SERIALIZER.header("if_none_match", if_none_match, 'str') + _headers["If-None-Match"] = _SERIALIZER.header("if_none_match", if_none_match, "str") if content_type is not None: - _header_parameters['Content-Type'] = _SERIALIZER.header("content_type", content_type, 'str') - _header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest( - method="PUT", - url=_url, - params=_query_parameters, - headers=_header_parameters, - json=json, - content=content, - **kwargs - ) + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) def build_update_request( @@ -133,183 +145,173 @@ def build_update_request( certificate_name: str, subscription_id: str, *, - json: JSONType = None, - content: Any = None, if_match: Optional[str] = None, **kwargs: Any ) -> HttpRequest: - api_version = kwargs.pop('api_version', "2022-06-01") # type: str - content_type = kwargs.pop('content_type', None) # type: Optional[str] + _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", "2022-10-01")) # type: Literal["2022-10-01"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") - 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 + _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'), + "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 = _format_url_section(_url, **path_format_arguments) # Construct parameters - _query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - _query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] if if_match is not None: - _header_parameters['If-Match'] = _SERIALIZER.header("if_match", if_match, 'str') + _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") if content_type is not None: - _header_parameters['Content-Type'] = _SERIALIZER.header("content_type", content_type, 'str') - _header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest( - method="PATCH", - url=_url, - params=_query_parameters, - headers=_header_parameters, - json=json, - content=content, - **kwargs - ) + return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs) -def build_delete_request_initial( - resource_group_name: str, - account_name: str, - certificate_name: str, - subscription_id: str, - **kwargs: Any +def build_delete_request( + resource_group_name: str, account_name: str, certificate_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: - api_version = kwargs.pop('api_version', "2022-06-01") # type: str + _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", "2022-10-01")) # type: Literal["2022-10-01"] + accept = _headers.pop("Accept", "application/json") - 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 + _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'), + "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 = _format_url_section(_url, **path_format_arguments) # Construct parameters - _query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - _query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] - _header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest( - method="DELETE", - url=_url, - params=_query_parameters, - headers=_header_parameters, - **kwargs - ) + 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 + resource_group_name: str, account_name: str, certificate_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: - api_version = kwargs.pop('api_version', "2022-06-01") # type: str + _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", "2022-10-01")) # type: Literal["2022-10-01"] + accept = _headers.pop("Accept", "application/json") - 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 + _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'), + "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 = _format_url_section(_url, **path_format_arguments) # Construct parameters - _query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - _query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] - _header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest( - method="GET", - url=_url, - params=_query_parameters, - headers=_header_parameters, - **kwargs - ) + 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 + resource_group_name: str, account_name: str, certificate_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: - api_version = kwargs.pop('api_version', "2022-06-01") # type: str + _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", "2022-10-01")) # type: Literal["2022-10-01"] + accept = _headers.pop("Accept", "application/json") - 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 + _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'), + "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 = _format_url_section(_url, **path_format_arguments) # Construct parameters - _query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - _query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] - _header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') - - return HttpRequest( - method="POST", - url=_url, - params=_query_parameters, - headers=_header_parameters, - **kwargs - ) - -class CertificateOperations(object): - """CertificateOperations 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: ~azure.mgmt.batch.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. + _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, client, config, serializer, deserializer): - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + 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( @@ -320,12 +322,17 @@ def list_by_batch_account( select: Optional[str] = None, filter: Optional[str] = None, **kwargs: Any - ) -> Iterable["_models.ListCertificatesResult"]: + ) -> 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 + `_ 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. + :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. @@ -339,48 +346,59 @@ def list_by_batch_account( 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 ListCertificatesResult or the result of - cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.batch.models.ListCertificatesResult] - :raises: ~azure.core.exceptions.HttpResponseError + :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: """ - api_version = kwargs.pop('api_version', "2022-06-01") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.ListCertificatesResult] - cls = kwargs.pop('cls', None) # type: ClsType["_models.ListCertificatesResult"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + 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, - api_version=api_version, maxresults=maxresults, select=select, filter=filter, - template_url=self.list_by_batch_account.metadata['url'], + 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) + request.url = self._client.format_url(request.url) # type: ignore else: - - request = build_list_by_batch_account_request( - resource_group_name=resource_group_name, - account_name=account_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - maxresults=maxresults, - select=select, - filter=filter, - template_url=next_link, + # 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.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request @@ -394,10 +412,8 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -407,34 +423,39 @@ def get_next(next_link=None): return pipeline_response + return ItemPaged(get_next, extract_data) - return ItemPaged( - get_next, extract_data - ) - list_by_batch_account.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/certificates"} # type: ignore + list_by_batch_account.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/certificates"} # type: ignore - @distributed_trace + @overload def create( self, resource_group_name: str, account_name: str, certificate_name: str, - parameters: "_models.CertificateCreateOrUpdateParameters", + parameters: _models.CertificateCreateOrUpdateParameters, if_match: Optional[str] = None, if_none_match: Optional[str] = None, + *, + content_type: str = "application/json", **kwargs: Any - ) -> "_models.Certificate": + ) -> _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 + `_ 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. + :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. + example SHA1-a3d1c5. Required. :type certificate_name: str - :param parameters: Additional parameters for certificate creation. + :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 @@ -443,42 +464,152 @@ def create( :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 + `_ 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) + :return: Certificate or the result of cls(response) :rtype: ~azure.mgmt.batch.models.Certificate - :raises: ~azure.core.exceptions.HttpResponseError + :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 + `_ 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 model 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: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Certificate"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + 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', "2022-06-01") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.Certificate] - _json = self._serialize.body(parameters, 'CertificateCreateOrUpdateParameters') + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, 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, - if_match=if_match, - if_none_match=if_none_match, - template_url=self.create.metadata['url'], + content=_content, + template_url=self.create.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + 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]: @@ -486,17 +617,98 @@ def create( raise HttpResponseError(response=response, error_format=ARMErrorFormat) response_headers = {} - response_headers['ETag']=self._deserialize('str', response.headers.get('ETag')) + response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) - deserialized = self._deserialize('Certificate', pipeline_response) + 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}"} # type: ignore + create.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/certificates/{certificateName}"} # type: ignore + + @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 + `_ 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 + `_ 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( @@ -504,60 +716,84 @@ def update( resource_group_name: str, account_name: str, certificate_name: str, - parameters: "_models.CertificateCreateOrUpdateParameters", + parameters: Union[_models.CertificateCreateOrUpdateParameters, IO], if_match: Optional[str] = None, **kwargs: Any - ) -> "_models.Certificate": + ) -> _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 + `_ 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. + :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. + example SHA1-a3d1c5. Required. :type certificate_name: str - :param parameters: Certificate entity to update. - :type parameters: ~azure.mgmt.batch.models.CertificateCreateOrUpdateParameters + :param parameters: Certificate entity to update. Is either a model 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) + :return: Certificate or the result of cls(response) :rtype: ~azure.mgmt.batch.models.Certificate - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Certificate"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) - api_version = kwargs.pop('api_version', "2022-06-01") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - _json = self._serialize.body(parameters, 'CertificateCreateOrUpdateParameters') + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.Certificate] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, 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, - if_match=if_match, - template_url=self.update.metadata['url'], + content=_content, + template_url=self.update.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + 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]: @@ -565,50 +801,53 @@ def update( raise HttpResponseError(response=response, error_format=ARMErrorFormat) response_headers = {} - response_headers['ETag']=self._deserialize('str', response.headers.get('ETag')) + response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) - deserialized = self._deserialize('Certificate', pipeline_response) + 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}"} # type: ignore - + update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/certificates/{certificateName}"} # type: ignore def _delete_initial( # pylint: disable=inconsistent-return-statements - self, - resource_group_name: str, - account_name: str, - certificate_name: str, - **kwargs: Any + self, resource_group_name: str, account_name: str, certificate_name: str, **kwargs: Any ) -> None: - cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + 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', "2022-06-01") # type: str + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[None] - - request = build_delete_request_initial( + 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'], + template_url=self._delete_initial.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + 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, 204]: @@ -617,33 +856,32 @@ def _delete_initial( # pylint: disable=inconsistent-return-statements 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')) - + 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}"} # type: ignore - + _delete_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/certificates/{certificateName}"} # type: ignore @distributed_trace - def begin_delete( # pylint: disable=inconsistent-return-statements - self, - resource_group_name: str, - account_name: str, - certificate_name: str, - **kwargs: Any + 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 + `_ 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. + :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. + 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. @@ -655,94 +893,111 @@ def begin_delete( # pylint: disable=inconsistent-return-statements 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 + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2022-06-01") # type: str - 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] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[None] + 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._delete_initial( + 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, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) - def get_long_running_output(pipeline_response): + 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 = ARMPolling(lro_delay, lro_options={'final-state-via': 'location'}, **kwargs) - elif polling is False: polling_method = NoPolling() - else: polling_method = polling + 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 + deserialization_callback=get_long_running_output, ) return LROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_delete.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/certificates/{certificateName}"} # type: ignore + begin_delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/certificates/{certificateName}"} # type: ignore @distributed_trace def get( - self, - resource_group_name: str, - account_name: str, - certificate_name: str, - **kwargs: Any - ) -> "_models.Certificate": + 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 + `_ 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. + :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. + 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) + :return: Certificate or the result of cls(response) :rtype: ~azure.mgmt.batch.models.Certificate - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Certificate"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) - api_version = kwargs.pop('api_version', "2022-06-01") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.Certificate] - 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'], + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + 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]: @@ -750,26 +1005,21 @@ def get( raise HttpResponseError(response=response, error_format=ARMErrorFormat) response_headers = {} - response_headers['ETag']=self._deserialize('str', response.headers.get('ETag')) + response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) - deserialized = self._deserialize('Certificate', pipeline_response) + 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}"} # type: ignore - + get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/certificates/{certificateName}"} # type: ignore @distributed_trace def cancel_deletion( - self, - resource_group_name: str, - account_name: str, - certificate_name: str, - **kwargs: Any - ) -> "_models.Certificate": + 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 @@ -779,44 +1029,57 @@ def cancel_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 + `_ 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. + :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. + 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) + :return: Certificate or the result of cls(response) :rtype: ~azure.mgmt.batch.models.Certificate - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Certificate"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) - api_version = kwargs.pop('api_version', "2022-06-01") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.Certificate] - 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'], + template_url=self.cancel_deletion.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + 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]: @@ -824,14 +1087,13 @@ def cancel_deletion( raise HttpResponseError(response=response, error_format=ARMErrorFormat) response_headers = {} - response_headers['ETag']=self._deserialize('str', response.headers.get('ETag')) + response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) - deserialized = self._deserialize('Certificate', pipeline_response) + 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"} # type: ignore - + cancel_deletion.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/certificates/{certificateName}/cancelDelete"} # type: ignore diff --git a/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/operations/_location_operations.py b/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/operations/_location_operations.py index 09cd4e75ad51..e3696c9e4f84 100644 --- a/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/operations/_location_operations.py +++ b/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/operations/_location_operations.py @@ -6,59 +6,66 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, Callable, Dict, Iterable, Optional, TypeVar - -from msrest import Serializer - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +import sys +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') -JSONType = Any + +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_quotas_request( - location_name: str, - subscription_id: str, - **kwargs: Any -) -> HttpRequest: - api_version = kwargs.pop('api_version', "2022-06-01") # type: str - accept = "application/json" +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 = kwargs.pop("api_version", _params.pop("api-version", "2022-10-01")) # type: Literal["2022-10-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 + _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'), + "locationName": _SERIALIZER.url("location_name", location_name, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - _query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - _query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] - _header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest( - method="GET", - url=_url, - params=_query_parameters, - headers=_header_parameters, - **kwargs - ) + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_list_supported_virtual_machine_skus_request( @@ -69,37 +76,35 @@ def build_list_supported_virtual_machine_skus_request( filter: Optional[str] = None, **kwargs: Any ) -> HttpRequest: - api_version = kwargs.pop('api_version', "2022-06-01") # type: str + _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", "2022-10-01")) # type: Literal["2022-10-01"] + accept = _headers.pop("Accept", "application/json") - accept = "application/json" # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Batch/locations/{locationName}/virtualMachineSkus") # pylint: disable=line-too-long + _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'), + "locationName": _SERIALIZER.url("location_name", location_name, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - _query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] if maxresults is not None: - _query_parameters['maxresults'] = _SERIALIZER.query("maxresults", maxresults, 'int') + _params["maxresults"] = _SERIALIZER.query("maxresults", maxresults, "int") if filter is not None: - _query_parameters['$filter'] = _SERIALIZER.query("filter", filter, 'str') - _query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] - _header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest( - method="GET", - url=_url, - params=_query_parameters, - headers=_header_parameters, - **kwargs - ) + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_list_supported_cloud_service_skus_request( @@ -110,167 +115,151 @@ def build_list_supported_cloud_service_skus_request( filter: Optional[str] = None, **kwargs: Any ) -> HttpRequest: - api_version = kwargs.pop('api_version', "2022-06-01") # type: str + _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", "2022-10-01")) # type: Literal["2022-10-01"] + accept = _headers.pop("Accept", "application/json") - accept = "application/json" # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Batch/locations/{locationName}/cloudServiceSkus") # pylint: disable=line-too-long + _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'), + "locationName": _SERIALIZER.url("location_name", location_name, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - _query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] if maxresults is not None: - _query_parameters['maxresults'] = _SERIALIZER.query("maxresults", maxresults, 'int') + _params["maxresults"] = _SERIALIZER.query("maxresults", maxresults, "int") if filter is not None: - _query_parameters['$filter'] = _SERIALIZER.query("filter", filter, 'str') - _query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] - _header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest( - method="GET", - url=_url, - params=_query_parameters, - headers=_header_parameters, - **kwargs - ) + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_check_name_availability_request( - location_name: str, - subscription_id: str, - *, - json: JSONType = None, - content: Any = None, - **kwargs: Any -) -> HttpRequest: - api_version = kwargs.pop('api_version', "2022-06-01") # type: str - content_type = kwargs.pop('content_type', None) # type: Optional[str] +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 = kwargs.pop("api_version", _params.pop("api-version", "2022-10-01")) # type: Literal["2022-10-01"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") - accept = "application/json" # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Batch/locations/{locationName}/checkNameAvailability") # pylint: disable=line-too-long + _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'), + "locationName": _SERIALIZER.url("location_name", location_name, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - _query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - _query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] if content_type is not None: - _header_parameters['Content-Type'] = _SERIALIZER.header("content_type", content_type, 'str') - _header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') - - return HttpRequest( - method="POST", - url=_url, - params=_query_parameters, - headers=_header_parameters, - json=json, - content=content, - **kwargs - ) - -class LocationOperations(object): - """LocationOperations 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: ~azure.mgmt.batch.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. + _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, client, config, serializer, deserializer): - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + 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": + 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. + :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) + :return: BatchLocationQuota or the result of cls(response) :rtype: ~azure.mgmt.batch.models.BatchLocationQuota - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.BatchLocationQuota"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + 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', "2022-06-01") # type: str + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.BatchLocationQuota] - 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'], + template_url=self.get_quotas.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + 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) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('BatchLocationQuota', pipeline_response) + 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"} # type: ignore - + get_quotas.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Batch/locations/{locationName}/quotas"} # type: ignore @distributed_trace def list_supported_virtual_machine_skus( - self, - location_name: str, - maxresults: Optional[int] = None, - filter: Optional[str] = None, - **kwargs: Any - ) -> Iterable["_models.SupportedSkusResult"]: + 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. + :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. @@ -279,43 +268,57 @@ def list_supported_virtual_machine_skus( 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 SupportedSkusResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.batch.models.SupportedSkusResult] - :raises: ~azure.core.exceptions.HttpResponseError + :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: """ - api_version = kwargs.pop('api_version', "2022-06-01") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.SupportedSkusResult] - cls = kwargs.pop('cls', None) # type: ClsType["_models.SupportedSkusResult"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + 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, - api_version=api_version, maxresults=maxresults, filter=filter, - template_url=self.list_supported_virtual_machine_skus.metadata['url'], + 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) + request.url = self._client.format_url(request.url) # type: ignore else: - - request = build_list_supported_virtual_machine_skus_request( - location_name=location_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - maxresults=maxresults, - filter=filter, - template_url=next_link, + # 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.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request @@ -329,10 +332,8 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -342,23 +343,17 @@ def get_next(next_link=None): return pipeline_response + return ItemPaged(get_next, extract_data) - return ItemPaged( - get_next, extract_data - ) - list_supported_virtual_machine_skus.metadata = {'url': "/subscriptions/{subscriptionId}/providers/Microsoft.Batch/locations/{locationName}/virtualMachineSkus"} # type: ignore + list_supported_virtual_machine_skus.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Batch/locations/{locationName}/virtualMachineSkus"} # type: ignore @distributed_trace def list_supported_cloud_service_skus( - self, - location_name: str, - maxresults: Optional[int] = None, - filter: Optional[str] = None, - **kwargs: Any - ) -> Iterable["_models.SupportedSkusResult"]: + 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. + :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. @@ -367,43 +362,57 @@ def list_supported_cloud_service_skus( 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 SupportedSkusResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.batch.models.SupportedSkusResult] - :raises: ~azure.core.exceptions.HttpResponseError + :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: """ - api_version = kwargs.pop('api_version', "2022-06-01") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.SupportedSkusResult] - cls = kwargs.pop('cls', None) # type: ClsType["_models.SupportedSkusResult"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + 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, - api_version=api_version, maxresults=maxresults, filter=filter, - template_url=self.list_supported_cloud_service_skus.metadata['url'], + 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) + request.url = self._client.format_url(request.url) # type: ignore else: - - request = build_list_supported_cloud_service_skus_request( - location_name=location_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - maxresults=maxresults, - filter=filter, - template_url=next_link, + # 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.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request @@ -417,10 +426,8 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -430,40 +437,96 @@ def get_next(next_link=None): return pipeline_response + return ItemPaged(get_next, extract_data) - return ItemPaged( - get_next, extract_data - ) - list_supported_cloud_service_skus.metadata = {'url': "/subscriptions/{subscriptionId}/providers/Microsoft.Batch/locations/{locationName}/cloudServiceSkus"} # type: ignore + list_supported_cloud_service_skus.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Batch/locations/{locationName}/cloudServiceSkus"} # type: ignore - @distributed_trace + @overload def check_name_availability( self, location_name: str, - parameters: "_models.CheckNameAvailabilityParameters", + parameters: _models.CheckNameAvailabilityParameters, + *, + content_type: str = "application/json", **kwargs: Any - ) -> "_models.CheckNameAvailabilityResult": + ) -> _models.CheckNameAvailabilityResult: """Checks whether the Batch account name is available in the specified region. - :param location_name: The desired region for the name check. + :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. + :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) + :return: CheckNameAvailabilityResult or the result of cls(response) :rtype: ~azure.mgmt.batch.models.CheckNameAvailabilityResult - :raises: ~azure.core.exceptions.HttpResponseError + :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 model + 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: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.CheckNameAvailabilityResult"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + 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', "2022-06-01") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.CheckNameAvailabilityResult] - _json = self._serialize.body(parameters, 'CheckNameAvailabilityParameters') + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "CheckNameAvailabilityParameters") request = build_check_name_availability_request( location_name=location_name, @@ -471,28 +534,29 @@ def check_name_availability( api_version=api_version, content_type=content_type, json=_json, - template_url=self.check_name_availability.metadata['url'], + 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) + request.url = self._client.format_url(request.url) # type: ignore - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + 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) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('CheckNameAvailabilityResult', pipeline_response) + 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"} # type: ignore - + check_name_availability.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Batch/locations/{locationName}/checkNameAvailability"} # type: ignore diff --git a/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/operations/_operations.py b/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/operations/_operations.py index 59de7fee57a0..7899f67bbf7d 100644 --- a/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/operations/_operations.py +++ b/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/operations/_operations.py @@ -6,110 +6,131 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +import sys from typing import Any, Callable, Dict, Iterable, Optional, TypeVar - -from msrest import Serializer - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +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') + +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: - api_version = kwargs.pop('api_version', "2022-06-01") # type: str - accept = "application/json" +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", "2022-10-01")) # type: Literal["2022-10-01"] + accept = _headers.pop("Accept", "application/json") + # Construct URL _url = kwargs.pop("template_url", "/providers/Microsoft.Batch/operations") # Construct parameters - _query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - _query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] - _header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') - - return HttpRequest( - method="GET", - url=_url, - params=_query_parameters, - headers=_header_parameters, - **kwargs - ) - -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: ~azure.mgmt.batch.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. + _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, client, config, serializer, deserializer): - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + 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.OperationListResult"]: + 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 OperationListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.batch.models.OperationListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :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: """ - api_version = kwargs.pop('api_version', "2022-06-01") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.OperationListResult] - cls = kwargs.pop('cls', None) # type: ClsType["_models.OperationListResult"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + 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'], + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore else: - - request = build_list_request( - api_version=api_version, - template_url=next_link, + # 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.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request @@ -123,10 +144,8 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -136,8 +155,6 @@ def get_next(next_link=None): return pipeline_response + return ItemPaged(get_next, extract_data) - return ItemPaged( - get_next, extract_data - ) - list.metadata = {'url': "/providers/Microsoft.Batch/operations"} # type: ignore + list.metadata = {"url": "/providers/Microsoft.Batch/operations"} # type: ignore diff --git a/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/operations/_patch.py b/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/operations/_patch.py new file mode 100644 index 000000000000..f7dd32510333 --- /dev/null +++ b/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/operations/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/operations/_pool_operations.py b/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/operations/_pool_operations.py index d41200a0f9a8..a782ac571131 100644 --- a/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/operations/_pool_operations.py +++ b/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/operations/_pool_operations.py @@ -6,29 +6,43 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, Callable, Dict, Iterable, Optional, TypeVar, Union - -from msrest import Serializer - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +import sys +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') -JSONType = Any + +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_batch_account_request( resource_group_name: str, account_name: str, @@ -39,40 +53,40 @@ def build_list_by_batch_account_request( filter: Optional[str] = None, **kwargs: Any ) -> HttpRequest: - api_version = kwargs.pop('api_version', "2022-06-01") # type: str + _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", "2022-10-01")) # type: Literal["2022-10-01"] + accept = _headers.pop("Accept", "application/json") - 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 + _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'), + "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 = _format_url_section(_url, **path_format_arguments) # Construct parameters - _query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] if maxresults is not None: - _query_parameters['maxresults'] = _SERIALIZER.query("maxresults", maxresults, 'int') + _params["maxresults"] = _SERIALIZER.query("maxresults", maxresults, "int") if select is not None: - _query_parameters['$select'] = _SERIALIZER.query("select", select, 'str') + _params["$select"] = _SERIALIZER.query("select", select, "str") if filter is not None: - _query_parameters['$filter'] = _SERIALIZER.query("filter", filter, 'str') - _query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] - _header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest( - method="GET", - url=_url, - params=_query_parameters, - headers=_header_parameters, - **kwargs - ) + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_create_request( @@ -81,50 +95,48 @@ def build_create_request( pool_name: str, subscription_id: str, *, - json: JSONType = None, - content: Any = None, if_match: Optional[str] = None, if_none_match: Optional[str] = None, **kwargs: Any ) -> HttpRequest: - api_version = kwargs.pop('api_version', "2022-06-01") # type: str - content_type = kwargs.pop('content_type', None) # type: Optional[str] + _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", "2022-10-01")) # type: Literal["2022-10-01"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") - 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 + _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'), + "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 = _format_url_section(_url, **path_format_arguments) # Construct parameters - _query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - _query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] if if_match is not None: - _header_parameters['If-Match'] = _SERIALIZER.header("if_match", if_match, 'str') + _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") if if_none_match is not None: - _header_parameters['If-None-Match'] = _SERIALIZER.header("if_none_match", if_none_match, 'str') + _headers["If-None-Match"] = _SERIALIZER.header("if_none_match", if_none_match, "str") if content_type is not None: - _header_parameters['Content-Type'] = _SERIALIZER.header("content_type", content_type, 'str') - _header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest( - method="PUT", - url=_url, - params=_query_parameters, - headers=_header_parameters, - json=json, - content=content, - **kwargs - ) + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) def build_update_request( @@ -133,221 +145,209 @@ def build_update_request( pool_name: str, subscription_id: str, *, - json: JSONType = None, - content: Any = None, if_match: Optional[str] = None, **kwargs: Any ) -> HttpRequest: - api_version = kwargs.pop('api_version', "2022-06-01") # type: str - content_type = kwargs.pop('content_type', None) # type: Optional[str] + _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", "2022-10-01")) # type: Literal["2022-10-01"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") - 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 + _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'), + "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 = _format_url_section(_url, **path_format_arguments) # Construct parameters - _query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - _query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] if if_match is not None: - _header_parameters['If-Match'] = _SERIALIZER.header("if_match", if_match, 'str') + _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") if content_type is not None: - _header_parameters['Content-Type'] = _SERIALIZER.header("content_type", content_type, 'str') - _header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest( - method="PATCH", - url=_url, - params=_query_parameters, - headers=_header_parameters, - json=json, - content=content, - **kwargs - ) + return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs) -def build_delete_request_initial( - resource_group_name: str, - account_name: str, - pool_name: str, - subscription_id: str, - **kwargs: Any +def build_delete_request( + resource_group_name: str, account_name: str, pool_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: - api_version = kwargs.pop('api_version', "2022-06-01") # type: str + _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", "2022-10-01")) # type: Literal["2022-10-01"] + accept = _headers.pop("Accept", "application/json") - 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 + _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'), + "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 = _format_url_section(_url, **path_format_arguments) # Construct parameters - _query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - _query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] - _header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest( - method="DELETE", - url=_url, - params=_query_parameters, - headers=_header_parameters, - **kwargs - ) + 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 + resource_group_name: str, account_name: str, pool_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: - api_version = kwargs.pop('api_version', "2022-06-01") # type: str + _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", "2022-10-01")) # type: Literal["2022-10-01"] + accept = _headers.pop("Accept", "application/json") - 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 + _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'), + "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 = _format_url_section(_url, **path_format_arguments) # Construct parameters - _query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - _query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] - _header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest( - method="GET", - url=_url, - params=_query_parameters, - headers=_header_parameters, - **kwargs - ) + 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 + resource_group_name: str, account_name: str, pool_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: - api_version = kwargs.pop('api_version', "2022-06-01") # type: str + _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", "2022-10-01")) # type: Literal["2022-10-01"] + accept = _headers.pop("Accept", "application/json") - 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 + _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'), + "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 = _format_url_section(_url, **path_format_arguments) # Construct parameters - _query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - _query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] - _header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest( - method="POST", - url=_url, - params=_query_parameters, - headers=_header_parameters, - **kwargs - ) + 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 + resource_group_name: str, account_name: str, pool_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: - api_version = kwargs.pop('api_version', "2022-06-01") # type: str + _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", "2022-10-01")) # type: Literal["2022-10-01"] + accept = _headers.pop("Accept", "application/json") - 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 + _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'), + "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 = _format_url_section(_url, **path_format_arguments) # Construct parameters - _query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - _query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] - _header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') - - return HttpRequest( - method="POST", - url=_url, - params=_query_parameters, - headers=_header_parameters, - **kwargs - ) - -class PoolOperations(object): - """PoolOperations 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: ~azure.mgmt.batch.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. + _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, client, config, serializer, deserializer): - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + 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( @@ -358,12 +358,13 @@ def list_by_batch_account( select: Optional[str] = None, filter: Optional[str] = None, **kwargs: Any - ) -> Iterable["_models.ListPoolsResult"]: + ) -> 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. + :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. @@ -387,47 +388,59 @@ def list_by_batch_account( 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 ListPoolsResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.batch.models.ListPoolsResult] - :raises: ~azure.core.exceptions.HttpResponseError + :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: """ - api_version = kwargs.pop('api_version', "2022-06-01") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.ListPoolsResult] - cls = kwargs.pop('cls', None) # type: ClsType["_models.ListPoolsResult"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + 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, - api_version=api_version, maxresults=maxresults, select=select, filter=filter, - template_url=self.list_by_batch_account.metadata['url'], + 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) + request.url = self._client.format_url(request.url) # type: ignore else: - - request = build_list_by_batch_account_request( - resource_group_name=resource_group_name, - account_name=account_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - maxresults=maxresults, - select=select, - filter=filter, - template_url=next_link, + # 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.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request @@ -441,10 +454,8 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -454,32 +465,33 @@ def get_next(next_link=None): return pipeline_response + return ItemPaged(get_next, extract_data) - return ItemPaged( - get_next, extract_data - ) - list_by_batch_account.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/pools"} # type: ignore + list_by_batch_account.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/pools"} # type: ignore - @distributed_trace + @overload def create( self, resource_group_name: str, account_name: str, pool_name: str, - parameters: "_models.Pool", + parameters: _models.Pool, if_match: Optional[str] = None, if_none_match: Optional[str] = None, + *, + content_type: str = "application/json", **kwargs: Any - ) -> "_models.Pool": + ) -> _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. + :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. + :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. + :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 @@ -488,42 +500,140 @@ def create( :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) + :return: Pool or the result of cls(response) :rtype: ~azure.mgmt.batch.models.Pool - :raises: ~azure.core.exceptions.HttpResponseError + :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 model 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: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Pool"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + 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', "2022-06-01") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.Pool] - _json = self._serialize.body(parameters, 'Pool') + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, 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, - if_match=if_match, - if_none_match=if_none_match, - template_url=self.create.metadata['url'], + content=_content, + template_url=self.create.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + 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]: @@ -531,17 +641,88 @@ def create( raise HttpResponseError(response=response, error_format=ARMErrorFormat) response_headers = {} - response_headers['ETag']=self._deserialize('str', response.headers.get('ETag')) + response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) - deserialized = self._deserialize('Pool', pipeline_response) + 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}"} # type: ignore + create.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/pools/{poolName}"} # type: ignore + @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( @@ -549,59 +730,80 @@ def update( resource_group_name: str, account_name: str, pool_name: str, - parameters: "_models.Pool", + parameters: Union[_models.Pool, IO], if_match: Optional[str] = None, **kwargs: Any - ) -> "_models.Pool": + ) -> _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. + :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. + :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. - :type parameters: ~azure.mgmt.batch.models.Pool + updated, any property not supplied will be unchanged. Is either a model 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) + :return: Pool or the result of cls(response) :rtype: ~azure.mgmt.batch.models.Pool - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Pool"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + 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', "2022-06-01") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.Pool] - _json = self._serialize.body(parameters, 'Pool') + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, 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, - if_match=if_match, - template_url=self.update.metadata['url'], + content=_content, + template_url=self.update.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + 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]: @@ -609,50 +811,53 @@ def update( raise HttpResponseError(response=response, error_format=ARMErrorFormat) response_headers = {} - response_headers['ETag']=self._deserialize('str', response.headers.get('ETag')) + response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) - deserialized = self._deserialize('Pool', pipeline_response) + 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}"} # type: ignore - + update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/pools/{poolName}"} # type: ignore def _delete_initial( # pylint: disable=inconsistent-return-statements - self, - resource_group_name: str, - account_name: str, - pool_name: str, - **kwargs: Any + self, resource_group_name: str, account_name: str, pool_name: str, **kwargs: Any ) -> None: - cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + 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', "2022-06-01") # type: str + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[None] - - request = build_delete_request_initial( + 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'], + template_url=self._delete_initial.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + 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, 204]: @@ -661,31 +866,26 @@ def _delete_initial( # pylint: disable=inconsistent-return-statements 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')) - + 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}"} # type: ignore - + _delete_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/pools/{poolName}"} # type: ignore @distributed_trace - def begin_delete( # pylint: disable=inconsistent-return-statements - self, - resource_group_name: str, - account_name: str, - pool_name: str, - **kwargs: Any + 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. + :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. + :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. @@ -697,92 +897,103 @@ def begin_delete( # pylint: disable=inconsistent-return-statements 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 + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2022-06-01") # type: str - 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] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[None] + 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._delete_initial( + 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, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) - def get_long_running_output(pipeline_response): + 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 = ARMPolling(lro_delay, lro_options={'final-state-via': 'location'}, **kwargs) - elif polling is False: polling_method = NoPolling() - else: polling_method = polling + 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 + deserialization_callback=get_long_running_output, ) return LROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_delete.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/pools/{poolName}"} # type: ignore + begin_delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/pools/{poolName}"} # type: ignore @distributed_trace - def get( - self, - resource_group_name: str, - account_name: str, - pool_name: str, - **kwargs: Any - ) -> "_models.Pool": + 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. + :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. + :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) + :return: Pool or the result of cls(response) :rtype: ~azure.mgmt.batch.models.Pool - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Pool"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + 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', "2022-06-01") # type: str + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.Pool] - 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'], + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + 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]: @@ -790,64 +1001,68 @@ def get( raise HttpResponseError(response=response, error_format=ARMErrorFormat) response_headers = {} - response_headers['ETag']=self._deserialize('str', response.headers.get('ETag')) + response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) - deserialized = self._deserialize('Pool', pipeline_response) + 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}"} # type: ignore - + get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/pools/{poolName}"} # type: ignore @distributed_trace def disable_auto_scale( - self, - resource_group_name: str, - account_name: str, - pool_name: str, - **kwargs: Any - ) -> "_models.Pool": + 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. + :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. + :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) + :return: Pool or the result of cls(response) :rtype: ~azure.mgmt.batch.models.Pool - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Pool"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + 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', "2022-06-01") # type: str + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.Pool] - 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'], + template_url=self.disable_auto_scale.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + 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]: @@ -855,26 +1070,19 @@ def disable_auto_scale( raise HttpResponseError(response=response, error_format=ARMErrorFormat) response_headers = {} - response_headers['ETag']=self._deserialize('str', response.headers.get('ETag')) + response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) - deserialized = self._deserialize('Pool', pipeline_response) + 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"} # type: ignore - + disable_auto_scale.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/pools/{poolName}/disableAutoScale"} # type: ignore @distributed_trace - def stop_resize( - self, - resource_group_name: str, - account_name: str, - pool_name: str, - **kwargs: Any - ) -> "_models.Pool": + 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 @@ -885,41 +1093,50 @@ def stop_resize( 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. + :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. + :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) + :return: Pool or the result of cls(response) :rtype: ~azure.mgmt.batch.models.Pool - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Pool"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) - api_version = kwargs.pop('api_version', "2022-06-01") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.Pool] - 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'], + template_url=self.stop_resize.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + 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]: @@ -927,14 +1144,13 @@ def stop_resize( raise HttpResponseError(response=response, error_format=ARMErrorFormat) response_headers = {} - response_headers['ETag']=self._deserialize('str', response.headers.get('ETag')) + response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) - deserialized = self._deserialize('Pool', pipeline_response) + 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"} # type: ignore - + stop_resize.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/pools/{poolName}/stopResize"} # type: ignore diff --git a/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/operations/_private_endpoint_connection_operations.py b/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/operations/_private_endpoint_connection_operations.py index a6200ff466b5..6cdc7d7a117c 100644 --- a/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/operations/_private_endpoint_connection_operations.py +++ b/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/operations/_private_endpoint_connection_operations.py @@ -6,272 +6,311 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, Callable, Dict, Iterable, Optional, TypeVar, Union - -from msrest import Serializer - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +import sys +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') -JSONType = Any + +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_batch_account_request( - subscription_id: str, resource_group_name: str, account_name: str, + subscription_id: str, *, maxresults: Optional[int] = None, **kwargs: Any ) -> HttpRequest: - api_version = kwargs.pop('api_version', "2022-06-01") # type: str + _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", "2022-10-01")) # type: Literal["2022-10-01"] + accept = _headers.pop("Accept", "application/json") - 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 + _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]+$'), + "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 = _format_url_section(_url, **path_format_arguments) # Construct parameters - _query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - _query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if maxresults is not None: - _query_parameters['maxresults'] = _SERIALIZER.query("maxresults", maxresults, 'int') + _params["maxresults"] = _SERIALIZER.query("maxresults", maxresults, "int") # Construct headers - _header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] - _header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest( - method="GET", - url=_url, - params=_query_parameters, - headers=_header_parameters, - **kwargs - ) + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_get_request( - subscription_id: str, resource_group_name: str, account_name: str, private_endpoint_connection_name: str, + subscription_id: str, **kwargs: Any ) -> HttpRequest: - api_version = kwargs.pop('api_version', "2022-06-01") # type: str + _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", "2022-10-01")) # type: Literal["2022-10-01"] + accept = _headers.pop("Accept", "application/json") - 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 + _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-]*$'), + "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 = _format_url_section(_url, **path_format_arguments) # Construct parameters - _query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - _query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] - _header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest( - method="GET", - url=_url, - params=_query_parameters, - headers=_header_parameters, - **kwargs - ) + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_update_request_initial( - subscription_id: str, +def build_update_request( resource_group_name: str, account_name: str, private_endpoint_connection_name: str, + subscription_id: str, *, - json: JSONType = None, - content: Any = None, if_match: Optional[str] = None, **kwargs: Any ) -> HttpRequest: - api_version = kwargs.pop('api_version', "2022-06-01") # type: str - content_type = kwargs.pop('content_type', None) # type: Optional[str] + _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", "2022-10-01")) # type: Literal["2022-10-01"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") - 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 + _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-]*$'), + "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 = _format_url_section(_url, **path_format_arguments) # Construct parameters - _query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - _query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] if if_match is not None: - _header_parameters['If-Match'] = _SERIALIZER.header("if_match", if_match, 'str') + _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") if content_type is not None: - _header_parameters['Content-Type'] = _SERIALIZER.header("content_type", content_type, 'str') - _header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest( - method="PATCH", - url=_url, - params=_query_parameters, - headers=_header_parameters, - json=json, - content=content, - **kwargs - ) + return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs) -def build_delete_request_initial( - subscription_id: str, +def build_delete_request( resource_group_name: str, account_name: str, private_endpoint_connection_name: str, + subscription_id: str, **kwargs: Any ) -> HttpRequest: - api_version = kwargs.pop('api_version', "2022-06-01") # type: str + _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", "2022-10-01")) # type: Literal["2022-10-01"] + accept = _headers.pop("Accept", "application/json") - 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 + _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-]*$'), + "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 = _format_url_section(_url, **path_format_arguments) # Construct parameters - _query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - _query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] - _header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') - - return HttpRequest( - method="DELETE", - url=_url, - params=_query_parameters, - headers=_header_parameters, - **kwargs - ) - -class PrivateEndpointConnectionOperations(object): - """PrivateEndpointConnectionOperations 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: ~azure.mgmt.batch.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. + _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, client, config, serializer, deserializer): - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + 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.ListPrivateEndpointConnectionsResult"]: + 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. + :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 ListPrivateEndpointConnectionsResult or the result - of cls(response) - :rtype: - ~azure.core.paging.ItemPaged[~azure.mgmt.batch.models.ListPrivateEndpointConnectionsResult] - :raises: ~azure.core.exceptions.HttpResponseError + :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: """ - api_version = kwargs.pop('api_version', "2022-06-01") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.ListPrivateEndpointConnectionsResult] - cls = kwargs.pop('cls', None) # type: ClsType["_models.ListPrivateEndpointConnectionsResult"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + 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( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, account_name=account_name, - api_version=api_version, + subscription_id=self._config.subscription_id, maxresults=maxresults, - template_url=self.list_by_batch_account.metadata['url'], + 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) + request.url = self._client.format_url(request.url) # type: ignore else: - - request = build_list_by_batch_account_request( - subscription_id=self._config.subscription_id, - resource_group_name=resource_group_name, - account_name=account_name, - api_version=api_version, - maxresults=maxresults, - template_url=next_link, + # 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.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request @@ -285,10 +324,8 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -298,137 +335,245 @@ def get_next(next_link=None): return pipeline_response + return ItemPaged(get_next, extract_data) - return ItemPaged( - get_next, extract_data - ) - list_by_batch_account.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/privateEndpointConnections"} # type: ignore + list_by_batch_account.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/privateEndpointConnections"} # type: ignore @distributed_trace def get( - self, - resource_group_name: str, - account_name: str, - private_endpoint_connection_name: str, - **kwargs: Any - ) -> "_models.PrivateEndpointConnection": + 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. + :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. + 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) + :return: PrivateEndpointConnection or the result of cls(response) :rtype: ~azure.mgmt.batch.models.PrivateEndpointConnection - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.PrivateEndpointConnection"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + 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', "2022-06-01") # type: str + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.PrivateEndpointConnection] - request = build_get_request( - subscription_id=self._config.subscription_id, 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'], + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + 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) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('PrivateEndpointConnection', pipeline_response) + 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}"} # type: ignore - + get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/privateEndpointConnections/{privateEndpointConnectionName}"} # type: ignore def _update_initial( self, resource_group_name: str, account_name: str, private_endpoint_connection_name: str, - parameters: "_models.PrivateEndpointConnection", + parameters: Union[_models.PrivateEndpointConnection, IO], if_match: Optional[str] = None, **kwargs: Any - ) -> Optional["_models.PrivateEndpointConnection"]: - cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.PrivateEndpointConnection"]] + ) -> Optional[_models.PrivateEndpointConnection]: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - - api_version = kwargs.pop('api_version', "2022-06-01") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] - - _json = self._serialize.body(parameters, 'PrivateEndpointConnection') - - request = build_update_request_initial( - subscription_id=self._config.subscription_id, + 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", self._config.api_version) + ) # type: Literal["2022-10-01"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.PrivateEndpointConnection]] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, 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, - if_match=if_match, - template_url=self._update_initial.metadata['url'], + 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) + request.url = self._client.format_url(request.url) # type: ignore - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + 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, 204]: + 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) + 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')) - + 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}"} # type: ignore + _update_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/privateEndpointConnections/{privateEndpointConnectionName}"} # type: ignore + + @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( @@ -436,26 +581,31 @@ def begin_update( resource_group_name: str, account_name: str, private_endpoint_connection_name: str, - parameters: "_models.PrivateEndpointConnection", + parameters: Union[_models.PrivateEndpointConnection, IO], if_match: Optional[str] = None, **kwargs: Any - ) -> LROPoller["_models.PrivateEndpointConnection"]: + ) -> 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. + :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. + 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. - :type parameters: ~azure.mgmt.batch.models.PrivateEndpointConnection + are supplied will be updated, any property not supplied will be unchanged. Is either a model + 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 @@ -467,19 +617,21 @@ def begin_update( :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 + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2022-06-01") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] - polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType["_models.PrivateEndpointConnection"] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + _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", self._config.api_version) + ) # type: Literal["2022-10-01"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.PrivateEndpointConnection] + 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( + raw_result = self._update_initial( # type: ignore resource_group_name=resource_group_name, account_name=account_name, private_endpoint_connection_name=private_endpoint_connection_name, @@ -487,65 +639,74 @@ def begin_update( if_match=if_match, api_version=api_version, content_type=content_type, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - response = pipeline_response.http_response - deserialized = self._deserialize('PrivateEndpointConnection', pipeline_response) + deserialized = self._deserialize("PrivateEndpointConnection", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - - if polling is True: polling_method = ARMPolling(lro_delay, lro_options={'final-state-via': 'azure-async-operation'}, **kwargs) - elif polling is False: polling_method = NoPolling() - else: polling_method = polling + 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 + deserialization_callback=get_long_running_output, ) return LROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_update.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/privateEndpointConnections/{privateEndpointConnectionName}"} # type: ignore + begin_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/privateEndpointConnections/{privateEndpointConnectionName}"} # type: ignore def _delete_initial( # pylint: disable=inconsistent-return-statements - self, - resource_group_name: str, - account_name: str, - private_endpoint_connection_name: str, - **kwargs: Any + self, resource_group_name: str, account_name: str, private_endpoint_connection_name: str, **kwargs: Any ) -> None: - cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) - api_version = kwargs.pop('api_version', "2022-06-01") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - request = build_delete_request_initial( - subscription_id=self._config.subscription_id, + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[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'], + template_url=self._delete_initial.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + 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 [202, 204]: @@ -554,32 +715,27 @@ def _delete_initial( # pylint: disable=inconsistent-return-statements 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')) - + 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}"} # type: ignore - + _delete_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/privateEndpointConnections/{privateEndpointConnectionName}"} # type: ignore @distributed_trace - def begin_delete( # pylint: disable=inconsistent-return-statements - self, - resource_group_name: str, - account_name: str, - private_endpoint_connection_name: str, - **kwargs: Any + 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. + :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. + 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. @@ -591,42 +747,50 @@ def begin_delete( # pylint: disable=inconsistent-return-statements 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 + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2022-06-01") # type: str - 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] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[None] + 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._delete_initial( + 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, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) - def get_long_running_output(pipeline_response): + 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 = ARMPolling(lro_delay, lro_options={'final-state-via': 'azure-async-operation'}, **kwargs) - elif polling is False: polling_method = NoPolling() - else: polling_method = polling + 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 + deserialization_callback=get_long_running_output, ) return LROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_delete.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/privateEndpointConnections/{privateEndpointConnectionName}"} # type: ignore + begin_delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/privateEndpointConnections/{privateEndpointConnectionName}"} # type: ignore diff --git a/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/operations/_private_link_resource_operations.py b/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/operations/_private_link_resource_operations.py index 51e8c9d7d567..9afc6d083a89 100644 --- a/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/operations/_private_link_resource_operations.py +++ b/sdk/batch/azure-mgmt-batch/azure/mgmt/batch/operations/_private_link_resource_operations.py @@ -6,181 +6,207 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +import sys from typing import Any, Callable, Dict, Iterable, Optional, TypeVar - -from msrest import Serializer - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +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') + +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_batch_account_request( - subscription_id: str, resource_group_name: str, account_name: str, + subscription_id: str, *, maxresults: Optional[int] = None, **kwargs: Any ) -> HttpRequest: - api_version = kwargs.pop('api_version', "2022-06-01") # type: str + _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", "2022-10-01")) # type: Literal["2022-10-01"] + accept = _headers.pop("Accept", "application/json") - 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 + _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]+$'), + "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 = _format_url_section(_url, **path_format_arguments) # Construct parameters - _query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - _query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if maxresults is not None: - _query_parameters['maxresults'] = _SERIALIZER.query("maxresults", maxresults, 'int') + _params["maxresults"] = _SERIALIZER.query("maxresults", maxresults, "int") # Construct headers - _header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] - _header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest( - method="GET", - url=_url, - params=_query_parameters, - headers=_header_parameters, - **kwargs - ) + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_get_request( - subscription_id: str, - resource_group_name: str, - account_name: str, - private_link_resource_name: str, - **kwargs: Any + resource_group_name: str, account_name: str, private_link_resource_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: - api_version = kwargs.pop('api_version', "2022-06-01") # type: str + _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", "2022-10-01")) # type: Literal["2022-10-01"] + accept = _headers.pop("Accept", "application/json") - 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 + _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-]*$'), + "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 = _format_url_section(_url, **path_format_arguments) # Construct parameters - _query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - _query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] - _header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') - - return HttpRequest( - method="GET", - url=_url, - params=_query_parameters, - headers=_header_parameters, - **kwargs - ) - -class PrivateLinkResourceOperations(object): - """PrivateLinkResourceOperations 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: ~azure.mgmt.batch.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. + _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, client, config, serializer, deserializer): - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + 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.ListPrivateLinkResourcesResult"]: + 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. + :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 ListPrivateLinkResourcesResult or the result of - cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.batch.models.ListPrivateLinkResourcesResult] - :raises: ~azure.core.exceptions.HttpResponseError + :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: """ - api_version = kwargs.pop('api_version', "2022-06-01") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.ListPrivateLinkResourcesResult] - cls = kwargs.pop('cls', None) # type: ClsType["_models.ListPrivateLinkResourcesResult"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + 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( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, account_name=account_name, - api_version=api_version, + subscription_id=self._config.subscription_id, maxresults=maxresults, - template_url=self.list_by_batch_account.metadata['url'], + 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) + request.url = self._client.format_url(request.url) # type: ignore else: - - request = build_list_by_batch_account_request( - subscription_id=self._config.subscription_id, - resource_group_name=resource_group_name, - account_name=account_name, - api_version=api_version, - maxresults=maxresults, - template_url=next_link, + # 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.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request @@ -194,10 +220,8 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -207,71 +231,73 @@ def get_next(next_link=None): return pipeline_response + return ItemPaged(get_next, extract_data) - return ItemPaged( - get_next, extract_data - ) - list_by_batch_account.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/privateLinkResources"} # type: ignore + list_by_batch_account.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/privateLinkResources"} # type: ignore @distributed_trace def get( - self, - resource_group_name: str, - account_name: str, - private_link_resource_name: str, - **kwargs: Any - ) -> "_models.PrivateLinkResource": + 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. + :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. + 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) + :return: PrivateLinkResource or the result of cls(response) :rtype: ~azure.mgmt.batch.models.PrivateLinkResource - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.PrivateLinkResource"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + 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', "2022-06-01") # type: str + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.PrivateLinkResource] - request = build_get_request( - subscription_id=self._config.subscription_id, 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'], + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + 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) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('PrivateLinkResource', pipeline_response) + 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}"} # type: ignore - + get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/privateLinkResources/{privateLinkResourceName}"} # type: ignore diff --git a/sdk/batch/azure-mgmt-batch/generated_samples/application_create.py b/sdk/batch/azure-mgmt-batch/generated_samples/application_create.py new file mode 100644 index 000000000000..294834370486 --- /dev/null +++ b/sdk/batch/azure-mgmt-batch/generated_samples/application_create.py @@ -0,0 +1,42 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.batch import BatchManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-batch +# USAGE + python application_create.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = BatchManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subid", + ) + + response = client.application.create( + resource_group_name="default-azurebatch-japaneast", + account_name="sampleacct", + application_name="app1", + ) + print(response) + + +# x-ms-original-file: specification/batch/resource-manager/Microsoft.Batch/stable/2022-10-01/examples/ApplicationCreate.json +if __name__ == "__main__": + main() diff --git a/sdk/batch/azure-mgmt-batch/generated_samples/application_delete.py b/sdk/batch/azure-mgmt-batch/generated_samples/application_delete.py new file mode 100644 index 000000000000..f4fb5b1aaaa6 --- /dev/null +++ b/sdk/batch/azure-mgmt-batch/generated_samples/application_delete.py @@ -0,0 +1,42 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.batch import BatchManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-batch +# USAGE + python application_delete.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = BatchManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subid", + ) + + response = client.application.delete( + resource_group_name="default-azurebatch-japaneast", + account_name="sampleacct", + application_name="app1", + ) + print(response) + + +# x-ms-original-file: specification/batch/resource-manager/Microsoft.Batch/stable/2022-10-01/examples/ApplicationDelete.json +if __name__ == "__main__": + main() diff --git a/sdk/batch/azure-mgmt-batch/generated_samples/application_get.py b/sdk/batch/azure-mgmt-batch/generated_samples/application_get.py new file mode 100644 index 000000000000..64633eae50f2 --- /dev/null +++ b/sdk/batch/azure-mgmt-batch/generated_samples/application_get.py @@ -0,0 +1,42 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.batch import BatchManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-batch +# USAGE + python application_get.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = BatchManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subid", + ) + + response = client.application.get( + resource_group_name="default-azurebatch-japaneast", + account_name="sampleacct", + application_name="app1", + ) + print(response) + + +# x-ms-original-file: specification/batch/resource-manager/Microsoft.Batch/stable/2022-10-01/examples/ApplicationGet.json +if __name__ == "__main__": + main() diff --git a/sdk/batch/azure-mgmt-batch/generated_samples/application_list.py b/sdk/batch/azure-mgmt-batch/generated_samples/application_list.py new file mode 100644 index 000000000000..a39d9180279d --- /dev/null +++ b/sdk/batch/azure-mgmt-batch/generated_samples/application_list.py @@ -0,0 +1,42 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.batch import BatchManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-batch +# USAGE + python application_list.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = BatchManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subid", + ) + + response = client.application.list( + resource_group_name="default-azurebatch-japaneast", + account_name="sampleacct", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/batch/resource-manager/Microsoft.Batch/stable/2022-10-01/examples/ApplicationList.json +if __name__ == "__main__": + main() diff --git a/sdk/batch/azure-mgmt-batch/generated_samples/application_package_activate.py b/sdk/batch/azure-mgmt-batch/generated_samples/application_package_activate.py new file mode 100644 index 000000000000..7f11774894f8 --- /dev/null +++ b/sdk/batch/azure-mgmt-batch/generated_samples/application_package_activate.py @@ -0,0 +1,44 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.batch import BatchManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-batch +# USAGE + python application_package_activate.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = BatchManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subid", + ) + + response = client.application_package.activate( + resource_group_name="default-azurebatch-japaneast", + account_name="sampleacct", + application_name="app1", + version_name="1", + parameters={"format": "zip"}, + ) + print(response) + + +# x-ms-original-file: specification/batch/resource-manager/Microsoft.Batch/stable/2022-10-01/examples/ApplicationPackageActivate.json +if __name__ == "__main__": + main() diff --git a/sdk/batch/azure-mgmt-batch/generated_samples/application_package_create.py b/sdk/batch/azure-mgmt-batch/generated_samples/application_package_create.py new file mode 100644 index 000000000000..e62847ab9e24 --- /dev/null +++ b/sdk/batch/azure-mgmt-batch/generated_samples/application_package_create.py @@ -0,0 +1,43 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.batch import BatchManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-batch +# USAGE + python application_package_create.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = BatchManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subid", + ) + + response = client.application_package.create( + resource_group_name="default-azurebatch-japaneast", + account_name="sampleacct", + application_name="app1", + version_name="1", + ) + print(response) + + +# x-ms-original-file: specification/batch/resource-manager/Microsoft.Batch/stable/2022-10-01/examples/ApplicationPackageCreate.json +if __name__ == "__main__": + main() diff --git a/sdk/batch/azure-mgmt-batch/generated_samples/application_package_delete.py b/sdk/batch/azure-mgmt-batch/generated_samples/application_package_delete.py new file mode 100644 index 000000000000..d63ef7692563 --- /dev/null +++ b/sdk/batch/azure-mgmt-batch/generated_samples/application_package_delete.py @@ -0,0 +1,43 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.batch import BatchManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-batch +# USAGE + python application_package_delete.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = BatchManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subid", + ) + + response = client.application_package.delete( + resource_group_name="default-azurebatch-japaneast", + account_name="sampleacct", + application_name="app1", + version_name="1", + ) + print(response) + + +# x-ms-original-file: specification/batch/resource-manager/Microsoft.Batch/stable/2022-10-01/examples/ApplicationPackageDelete.json +if __name__ == "__main__": + main() diff --git a/sdk/batch/azure-mgmt-batch/generated_samples/application_package_get.py b/sdk/batch/azure-mgmt-batch/generated_samples/application_package_get.py new file mode 100644 index 000000000000..4233b79bdd16 --- /dev/null +++ b/sdk/batch/azure-mgmt-batch/generated_samples/application_package_get.py @@ -0,0 +1,43 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.batch import BatchManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-batch +# USAGE + python application_package_get.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = BatchManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subid", + ) + + response = client.application_package.get( + resource_group_name="default-azurebatch-japaneast", + account_name="sampleacct", + application_name="app1", + version_name="1", + ) + print(response) + + +# x-ms-original-file: specification/batch/resource-manager/Microsoft.Batch/stable/2022-10-01/examples/ApplicationPackageGet.json +if __name__ == "__main__": + main() diff --git a/sdk/batch/azure-mgmt-batch/generated_samples/application_package_list.py b/sdk/batch/azure-mgmt-batch/generated_samples/application_package_list.py new file mode 100644 index 000000000000..a6eccc9cc105 --- /dev/null +++ b/sdk/batch/azure-mgmt-batch/generated_samples/application_package_list.py @@ -0,0 +1,43 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.batch import BatchManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-batch +# USAGE + python application_package_list.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = BatchManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subid", + ) + + response = client.application_package.list( + resource_group_name="default-azurebatch-japaneast", + account_name="sampleacct", + application_name="app1", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/batch/resource-manager/Microsoft.Batch/stable/2022-10-01/examples/ApplicationPackageList.json +if __name__ == "__main__": + main() diff --git a/sdk/batch/azure-mgmt-batch/generated_samples/application_update.py b/sdk/batch/azure-mgmt-batch/generated_samples/application_update.py new file mode 100644 index 000000000000..b94e75507148 --- /dev/null +++ b/sdk/batch/azure-mgmt-batch/generated_samples/application_update.py @@ -0,0 +1,43 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.batch import BatchManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-batch +# USAGE + python application_update.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = BatchManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subid", + ) + + response = client.application.update( + resource_group_name="default-azurebatch-japaneast", + account_name="sampleacct", + application_name="app1", + parameters={"properties": {"allowUpdates": True, "defaultVersion": "2", "displayName": "myAppName"}}, + ) + print(response) + + +# x-ms-original-file: specification/batch/resource-manager/Microsoft.Batch/stable/2022-10-01/examples/ApplicationUpdate.json +if __name__ == "__main__": + main() diff --git a/sdk/batch/azure-mgmt-batch/generated_samples/batch_account_create_byos.py b/sdk/batch/azure-mgmt-batch/generated_samples/batch_account_create_byos.py new file mode 100644 index 000000000000..90996ef13902 --- /dev/null +++ b/sdk/batch/azure-mgmt-batch/generated_samples/batch_account_create_byos.py @@ -0,0 +1,54 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.batch import BatchManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-batch +# USAGE + python batch_account_create_byos.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = BatchManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subid", + ) + + response = client.batch_account.begin_create( + resource_group_name="default-azurebatch-japaneast", + account_name="sampleacct", + parameters={ + "location": "japaneast", + "properties": { + "autoStorage": { + "storageAccountId": "/subscriptions/subid/resourceGroups/default-azurebatch-japaneast/providers/Microsoft.Storage/storageAccounts/samplestorage" + }, + "keyVaultReference": { + "id": "/subscriptions/subid/resourceGroups/default-azurebatch-japaneast/providers/Microsoft.KeyVault/vaults/sample", + "url": "http://sample.vault.azure.net/", + }, + "poolAllocationMode": "UserSubscription", + }, + }, + ).result() + print(response) + + +# x-ms-original-file: specification/batch/resource-manager/Microsoft.Batch/stable/2022-10-01/examples/BatchAccountCreate_BYOS.json +if __name__ == "__main__": + main() diff --git a/sdk/batch/azure-mgmt-batch/generated_samples/batch_account_create_default.py b/sdk/batch/azure-mgmt-batch/generated_samples/batch_account_create_default.py new file mode 100644 index 000000000000..eb6780bb1d4a --- /dev/null +++ b/sdk/batch/azure-mgmt-batch/generated_samples/batch_account_create_default.py @@ -0,0 +1,49 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.batch import BatchManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-batch +# USAGE + python batch_account_create_default.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = BatchManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subid", + ) + + response = client.batch_account.begin_create( + resource_group_name="default-azurebatch-japaneast", + account_name="sampleacct", + parameters={ + "location": "japaneast", + "properties": { + "autoStorage": { + "storageAccountId": "/subscriptions/subid/resourceGroups/default-azurebatch-japaneast/providers/Microsoft.Storage/storageAccounts/samplestorage" + } + }, + }, + ).result() + print(response) + + +# x-ms-original-file: specification/batch/resource-manager/Microsoft.Batch/stable/2022-10-01/examples/BatchAccountCreate_Default.json +if __name__ == "__main__": + main() diff --git a/sdk/batch/azure-mgmt-batch/generated_samples/batch_account_create_system_assigned_identity.py b/sdk/batch/azure-mgmt-batch/generated_samples/batch_account_create_system_assigned_identity.py new file mode 100644 index 000000000000..f4f973d6256c --- /dev/null +++ b/sdk/batch/azure-mgmt-batch/generated_samples/batch_account_create_system_assigned_identity.py @@ -0,0 +1,50 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.batch import BatchManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-batch +# USAGE + python batch_account_create_system_assigned_identity.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = BatchManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subid", + ) + + response = client.batch_account.begin_create( + resource_group_name="default-azurebatch-japaneast", + account_name="sampleacct", + parameters={ + "identity": {"type": "SystemAssigned"}, + "location": "japaneast", + "properties": { + "autoStorage": { + "storageAccountId": "/subscriptions/subid/resourceGroups/default-azurebatch-japaneast/providers/Microsoft.Storage/storageAccounts/samplestorage" + } + }, + }, + ).result() + print(response) + + +# x-ms-original-file: specification/batch/resource-manager/Microsoft.Batch/stable/2022-10-01/examples/BatchAccountCreate_SystemAssignedIdentity.json +if __name__ == "__main__": + main() diff --git a/sdk/batch/azure-mgmt-batch/generated_samples/batch_account_create_user_assigned_identity.py b/sdk/batch/azure-mgmt-batch/generated_samples/batch_account_create_user_assigned_identity.py new file mode 100644 index 000000000000..d1691f0242f4 --- /dev/null +++ b/sdk/batch/azure-mgmt-batch/generated_samples/batch_account_create_user_assigned_identity.py @@ -0,0 +1,55 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.batch import BatchManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-batch +# USAGE + python batch_account_create_user_assigned_identity.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = BatchManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subid", + ) + + response = client.batch_account.begin_create( + resource_group_name="default-azurebatch-japaneast", + account_name="sampleacct", + parameters={ + "identity": { + "type": "UserAssigned", + "userAssignedIdentities": { + "/subscriptions/subid/resourceGroups/default-azurebatch-japaneast/providers/Microsoft.ManagedIdentity/userAssignedIdentities/id1": {} + }, + }, + "location": "japaneast", + "properties": { + "autoStorage": { + "storageAccountId": "/subscriptions/subid/resourceGroups/default-azurebatch-japaneast/providers/Microsoft.Storage/storageAccounts/samplestorage" + } + }, + }, + ).result() + print(response) + + +# x-ms-original-file: specification/batch/resource-manager/Microsoft.Batch/stable/2022-10-01/examples/BatchAccountCreate_UserAssignedIdentity.json +if __name__ == "__main__": + main() diff --git a/sdk/batch/azure-mgmt-batch/generated_samples/batch_account_delete.py b/sdk/batch/azure-mgmt-batch/generated_samples/batch_account_delete.py new file mode 100644 index 000000000000..0b1b4326de51 --- /dev/null +++ b/sdk/batch/azure-mgmt-batch/generated_samples/batch_account_delete.py @@ -0,0 +1,41 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.batch import BatchManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-batch +# USAGE + python batch_account_delete.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = BatchManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subid", + ) + + response = client.batch_account.begin_delete( + resource_group_name="default-azurebatch-japaneast", + account_name="sampleacct", + ).result() + print(response) + + +# x-ms-original-file: specification/batch/resource-manager/Microsoft.Batch/stable/2022-10-01/examples/BatchAccountDelete.json +if __name__ == "__main__": + main() diff --git a/sdk/batch/azure-mgmt-batch/generated_samples/batch_account_get.py b/sdk/batch/azure-mgmt-batch/generated_samples/batch_account_get.py new file mode 100644 index 000000000000..8253ffdb287d --- /dev/null +++ b/sdk/batch/azure-mgmt-batch/generated_samples/batch_account_get.py @@ -0,0 +1,41 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.batch import BatchManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-batch +# USAGE + python batch_account_get.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = BatchManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subid", + ) + + response = client.batch_account.get( + resource_group_name="default-azurebatch-japaneast", + account_name="sampleacct", + ) + print(response) + + +# x-ms-original-file: specification/batch/resource-manager/Microsoft.Batch/stable/2022-10-01/examples/BatchAccountGet.json +if __name__ == "__main__": + main() diff --git a/sdk/batch/azure-mgmt-batch/generated_samples/batch_account_get_keys.py b/sdk/batch/azure-mgmt-batch/generated_samples/batch_account_get_keys.py new file mode 100644 index 000000000000..36a0782c4573 --- /dev/null +++ b/sdk/batch/azure-mgmt-batch/generated_samples/batch_account_get_keys.py @@ -0,0 +1,41 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.batch import BatchManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-batch +# USAGE + python batch_account_get_keys.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = BatchManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subid", + ) + + response = client.batch_account.get_keys( + resource_group_name="default-azurebatch-japaneast", + account_name="sampleacct", + ) + print(response) + + +# x-ms-original-file: specification/batch/resource-manager/Microsoft.Batch/stable/2022-10-01/examples/BatchAccountGetKeys.json +if __name__ == "__main__": + main() diff --git a/sdk/batch/azure-mgmt-batch/generated_samples/batch_account_list.py b/sdk/batch/azure-mgmt-batch/generated_samples/batch_account_list.py new file mode 100644 index 000000000000..cc3851f44234 --- /dev/null +++ b/sdk/batch/azure-mgmt-batch/generated_samples/batch_account_list.py @@ -0,0 +1,39 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.batch import BatchManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-batch +# USAGE + python batch_account_list.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = BatchManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subid", + ) + + response = client.batch_account.list() + for item in response: + print(item) + + +# x-ms-original-file: specification/batch/resource-manager/Microsoft.Batch/stable/2022-10-01/examples/BatchAccountList.json +if __name__ == "__main__": + main() diff --git a/sdk/batch/azure-mgmt-batch/generated_samples/batch_account_list_by_resource_group.py b/sdk/batch/azure-mgmt-batch/generated_samples/batch_account_list_by_resource_group.py new file mode 100644 index 000000000000..376d4ef819f1 --- /dev/null +++ b/sdk/batch/azure-mgmt-batch/generated_samples/batch_account_list_by_resource_group.py @@ -0,0 +1,41 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.batch import BatchManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-batch +# USAGE + python batch_account_list_by_resource_group.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = BatchManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subid", + ) + + response = client.batch_account.list_by_resource_group( + resource_group_name="default-azurebatch-japaneast", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/batch/resource-manager/Microsoft.Batch/stable/2022-10-01/examples/BatchAccountListByResourceGroup.json +if __name__ == "__main__": + main() diff --git a/sdk/batch/azure-mgmt-batch/generated_samples/batch_account_regenerate_key.py b/sdk/batch/azure-mgmt-batch/generated_samples/batch_account_regenerate_key.py new file mode 100644 index 000000000000..b7cd5dc6c0c8 --- /dev/null +++ b/sdk/batch/azure-mgmt-batch/generated_samples/batch_account_regenerate_key.py @@ -0,0 +1,42 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.batch import BatchManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-batch +# USAGE + python batch_account_regenerate_key.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = BatchManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subid", + ) + + response = client.batch_account.regenerate_key( + resource_group_name="default-azurebatch-japaneast", + account_name="sampleacct", + parameters={"keyName": "Primary"}, + ) + print(response) + + +# x-ms-original-file: specification/batch/resource-manager/Microsoft.Batch/stable/2022-10-01/examples/BatchAccountRegenerateKey.json +if __name__ == "__main__": + main() diff --git a/sdk/batch/azure-mgmt-batch/generated_samples/batch_account_synchronize_auto_storage_keys.py b/sdk/batch/azure-mgmt-batch/generated_samples/batch_account_synchronize_auto_storage_keys.py new file mode 100644 index 000000000000..f22ead4ecff7 --- /dev/null +++ b/sdk/batch/azure-mgmt-batch/generated_samples/batch_account_synchronize_auto_storage_keys.py @@ -0,0 +1,41 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.batch import BatchManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-batch +# USAGE + python batch_account_synchronize_auto_storage_keys.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = BatchManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subid", + ) + + response = client.batch_account.synchronize_auto_storage_keys( + resource_group_name="default-azurebatch-japaneast", + account_name="sampleacct", + ) + print(response) + + +# x-ms-original-file: specification/batch/resource-manager/Microsoft.Batch/stable/2022-10-01/examples/BatchAccountSynchronizeAutoStorageKeys.json +if __name__ == "__main__": + main() diff --git a/sdk/batch/azure-mgmt-batch/generated_samples/batch_account_update.py b/sdk/batch/azure-mgmt-batch/generated_samples/batch_account_update.py new file mode 100644 index 000000000000..9b2505e9a3b3 --- /dev/null +++ b/sdk/batch/azure-mgmt-batch/generated_samples/batch_account_update.py @@ -0,0 +1,48 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.batch import BatchManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-batch +# USAGE + python batch_account_update.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = BatchManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subid", + ) + + response = client.batch_account.update( + resource_group_name="default-azurebatch-japaneast", + account_name="sampleacct", + parameters={ + "properties": { + "autoStorage": { + "storageAccountId": "/subscriptions/subid/resourceGroups/default-azurebatch-japaneast/providers/Microsoft.Storage/storageAccounts/samplestorage" + } + } + }, + ) + print(response) + + +# x-ms-original-file: specification/batch/resource-manager/Microsoft.Batch/stable/2022-10-01/examples/BatchAccountUpdate.json +if __name__ == "__main__": + main() diff --git a/sdk/batch/azure-mgmt-batch/generated_samples/certificate_cancel_deletion.py b/sdk/batch/azure-mgmt-batch/generated_samples/certificate_cancel_deletion.py new file mode 100644 index 000000000000..7e09bf40633e --- /dev/null +++ b/sdk/batch/azure-mgmt-batch/generated_samples/certificate_cancel_deletion.py @@ -0,0 +1,42 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.batch import BatchManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-batch +# USAGE + python certificate_cancel_deletion.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = BatchManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subid", + ) + + response = client.certificate.cancel_deletion( + resource_group_name="default-azurebatch-japaneast", + account_name="sampleacct", + certificate_name="sha1-0a0e4f50d51beadeac1d35afc5116098e7902e6e", + ) + print(response) + + +# x-ms-original-file: specification/batch/resource-manager/Microsoft.Batch/stable/2022-10-01/examples/CertificateCancelDeletion.json +if __name__ == "__main__": + main() diff --git a/sdk/batch/azure-mgmt-batch/generated_samples/certificate_delete.py b/sdk/batch/azure-mgmt-batch/generated_samples/certificate_delete.py new file mode 100644 index 000000000000..ab1a9ccc3076 --- /dev/null +++ b/sdk/batch/azure-mgmt-batch/generated_samples/certificate_delete.py @@ -0,0 +1,42 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.batch import BatchManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-batch +# USAGE + python certificate_delete.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = BatchManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subid", + ) + + response = client.certificate.begin_delete( + resource_group_name="default-azurebatch-japaneast", + account_name="sampleacct", + certificate_name="sha1-0a0e4f50d51beadeac1d35afc5116098e7902e6e", + ).result() + print(response) + + +# x-ms-original-file: specification/batch/resource-manager/Microsoft.Batch/stable/2022-10-01/examples/CertificateDelete.json +if __name__ == "__main__": + main() diff --git a/sdk/batch/azure-mgmt-batch/generated_samples/create_certificate__full.py b/sdk/batch/azure-mgmt-batch/generated_samples/create_certificate__full.py new file mode 100644 index 000000000000..f303f0d70693 --- /dev/null +++ b/sdk/batch/azure-mgmt-batch/generated_samples/create_certificate__full.py @@ -0,0 +1,51 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.batch import BatchManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-batch +# USAGE + python create_certificate__full.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = BatchManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subid", + ) + + response = client.certificate.create( + resource_group_name="default-azurebatch-japaneast", + account_name="sampleacct", + certificate_name="sha1-0a0e4f50d51beadeac1d35afc5116098e7902e6e", + parameters={ + "properties": { + "data": "MIIJsgIBAzCCCW4GCSqGSIb3DQE...", + "format": "Pfx", + "password": "", + "thumbprint": "0a0e4f50d51beadeac1d35afc5116098e7902e6e", + "thumbprintAlgorithm": "sha1", + } + }, + ) + print(response) + + +# x-ms-original-file: specification/batch/resource-manager/Microsoft.Batch/stable/2022-10-01/examples/CertificateCreate_Full.json +if __name__ == "__main__": + main() diff --git a/sdk/batch/azure-mgmt-batch/generated_samples/create_certificate__minimal_cer.py b/sdk/batch/azure-mgmt-batch/generated_samples/create_certificate__minimal_cer.py new file mode 100644 index 000000000000..27c80b59cf1f --- /dev/null +++ b/sdk/batch/azure-mgmt-batch/generated_samples/create_certificate__minimal_cer.py @@ -0,0 +1,43 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.batch import BatchManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-batch +# USAGE + python create_certificate__minimal_cer.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = BatchManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subid", + ) + + response = client.certificate.create( + resource_group_name="default-azurebatch-japaneast", + account_name="sampleacct", + certificate_name="sha1-0a0e4f50d51beadeac1d35afc5116098e7902e6e", + parameters={"properties": {"data": "MIICrjCCAZagAwI...", "format": "Cer"}}, + ) + print(response) + + +# x-ms-original-file: specification/batch/resource-manager/Microsoft.Batch/stable/2022-10-01/examples/CertificateCreate_MinimalCer.json +if __name__ == "__main__": + main() diff --git a/sdk/batch/azure-mgmt-batch/generated_samples/create_certificate__minimal_pfx.py b/sdk/batch/azure-mgmt-batch/generated_samples/create_certificate__minimal_pfx.py new file mode 100644 index 000000000000..f3c0e79fcee2 --- /dev/null +++ b/sdk/batch/azure-mgmt-batch/generated_samples/create_certificate__minimal_pfx.py @@ -0,0 +1,43 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.batch import BatchManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-batch +# USAGE + python create_certificate__minimal_pfx.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = BatchManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subid", + ) + + response = client.certificate.create( + resource_group_name="default-azurebatch-japaneast", + account_name="sampleacct", + certificate_name="sha1-0a0e4f50d51beadeac1d35afc5116098e7902e6e", + parameters={"properties": {"data": "MIIJsgIBAzCCCW4GCSqGSIb3DQE...", "password": ""}}, + ) + print(response) + + +# x-ms-original-file: specification/batch/resource-manager/Microsoft.Batch/stable/2022-10-01/examples/CertificateCreate_Minimal.json +if __name__ == "__main__": + main() diff --git a/sdk/batch/azure-mgmt-batch/generated_samples/create_pool__custom_image.py b/sdk/batch/azure-mgmt-batch/generated_samples/create_pool__custom_image.py new file mode 100644 index 000000000000..890b668749d8 --- /dev/null +++ b/sdk/batch/azure-mgmt-batch/generated_samples/create_pool__custom_image.py @@ -0,0 +1,55 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.batch import BatchManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-batch +# USAGE + python create_pool__custom_image.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = BatchManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subid", + ) + + response = client.pool.create( + resource_group_name="default-azurebatch-japaneast", + account_name="sampleacct", + pool_name="testpool", + parameters={ + "properties": { + "deploymentConfiguration": { + "virtualMachineConfiguration": { + "imageReference": { + "id": "/subscriptions/subid/resourceGroups/networking-group/providers/Microsoft.Compute/galleries/testgallery/images/testimagedef/versions/0.0.1" + }, + "nodeAgentSkuId": "batch.node.ubuntu 18.04", + } + }, + "vmSize": "STANDARD_D4", + } + }, + ) + print(response) + + +# x-ms-original-file: specification/batch/resource-manager/Microsoft.Batch/stable/2022-10-01/examples/PoolCreate_SharedImageGallery.json +if __name__ == "__main__": + main() diff --git a/sdk/batch/azure-mgmt-batch/generated_samples/create_pool__full_cloud_service_configuration.py b/sdk/batch/azure-mgmt-batch/generated_samples/create_pool__full_cloud_service_configuration.py new file mode 100644 index 000000000000..c9494f71a76a --- /dev/null +++ b/sdk/batch/azure-mgmt-batch/generated_samples/create_pool__full_cloud_service_configuration.py @@ -0,0 +1,110 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.batch import BatchManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-batch +# USAGE + python create_pool__full_cloud_service_configuration.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = BatchManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subid", + ) + + response = client.pool.create( + resource_group_name="default-azurebatch-japaneast", + account_name="sampleacct", + pool_name="testpool", + parameters={ + "properties": { + "applicationLicenses": ["app-license0", "app-license1"], + "applicationPackages": [ + { + "id": "/subscriptions/subid/resourceGroups/default-azurebatch-japaneast/providers/Microsoft.Batch/batchAccounts/sampleacct/pools/testpool/applications/app_1234", + "version": "asdf", + } + ], + "certificates": [ + { + "id": "/subscriptions/subid/resourceGroups/default-azurebatch-japaneast/providers/Microsoft.Batch/batchAccounts/sampleacct/pools/testpool/certificates/sha1-1234567", + "storeLocation": "LocalMachine", + "storeName": "MY", + "visibility": ["RemoteUser"], + } + ], + "deploymentConfiguration": { + "cloudServiceConfiguration": {"osFamily": "4", "osVersion": "WA-GUEST-OS-4.45_201708-01"} + }, + "displayName": "my-pool-name", + "interNodeCommunication": "Enabled", + "metadata": [{"name": "metadata-1", "value": "value-1"}, {"name": "metadata-2", "value": "value-2"}], + "networkConfiguration": { + "publicIPAddressConfiguration": { + "ipAddressIds": [ + "/subscriptions/subid1/resourceGroups/rg13/providers/Microsoft.Network/publicIPAddresses/ip135", + "/subscriptions/subid2/resourceGroups/rg24/providers/Microsoft.Network/publicIPAddresses/ip268", + ], + "provision": "UserManaged", + }, + "subnetId": "/subscriptions/subid/resourceGroups/rg1234/providers/Microsoft.Network/virtualNetworks/network1234/subnets/subnet123", + }, + "scaleSettings": { + "fixedScale": { + "nodeDeallocationOption": "TaskCompletion", + "resizeTimeout": "PT8M", + "targetDedicatedNodes": 6, + "targetLowPriorityNodes": 28, + } + }, + "startTask": { + "commandLine": "cmd /c SET", + "environmentSettings": [{"name": "MYSET", "value": "1234"}], + "maxTaskRetryCount": 6, + "resourceFiles": [ + { + "fileMode": "777", + "filePath": "c:\\temp\\gohere", + "httpUrl": "https://testaccount.blob.core.windows.net/example-blob-file", + } + ], + "userIdentity": {"autoUser": {"elevationLevel": "Admin", "scope": "Pool"}}, + "waitForSuccess": True, + }, + "taskSchedulingPolicy": {"nodeFillType": "Pack"}, + "taskSlotsPerNode": 13, + "userAccounts": [ + { + "elevationLevel": "Admin", + "linuxUserConfiguration": {"gid": 4567, "sshPrivateKey": "sshprivatekeyvalue", "uid": 1234}, + "name": "username1", + "password": "", + } + ], + "vmSize": "STANDARD_D4", + } + }, + ) + print(response) + + +# x-ms-original-file: specification/batch/resource-manager/Microsoft.Batch/stable/2022-10-01/examples/PoolCreate_CloudServiceConfiguration.json +if __name__ == "__main__": + main() diff --git a/sdk/batch/azure-mgmt-batch/generated_samples/create_pool__full_virtual_machine_configuration.py b/sdk/batch/azure-mgmt-batch/generated_samples/create_pool__full_virtual_machine_configuration.py new file mode 100644 index 000000000000..320b3cd18fc7 --- /dev/null +++ b/sdk/batch/azure-mgmt-batch/generated_samples/create_pool__full_virtual_machine_configuration.py @@ -0,0 +1,95 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.batch import BatchManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-batch +# USAGE + python create_pool__full_virtual_machine_configuration.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = BatchManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subid", + ) + + response = client.pool.create( + resource_group_name="default-azurebatch-japaneast", + account_name="sampleacct", + pool_name="testpool", + parameters={ + "properties": { + "deploymentConfiguration": { + "virtualMachineConfiguration": { + "dataDisks": [ + {"caching": "ReadWrite", "diskSizeGB": 30, "lun": 0, "storageAccountType": "Premium_LRS"}, + {"caching": "None", "diskSizeGB": 200, "lun": 1, "storageAccountType": "Standard_LRS"}, + ], + "diskEncryptionConfiguration": {"targets": ["OsDisk", "TemporaryDisk"]}, + "imageReference": { + "offer": "WindowsServer", + "publisher": "MicrosoftWindowsServer", + "sku": "2016-Datacenter-SmallDisk", + "version": "latest", + }, + "licenseType": "Windows_Server", + "nodeAgentSkuId": "batch.node.windows amd64", + "nodePlacementConfiguration": {"policy": "Zonal"}, + "osDisk": {"ephemeralOSDiskSettings": {"placement": "CacheDisk"}}, + "windowsConfiguration": {"enableAutomaticUpdates": False}, + } + }, + "networkConfiguration": { + "endpointConfiguration": { + "inboundNatPools": [ + { + "backendPort": 12001, + "frontendPortRangeEnd": 15100, + "frontendPortRangeStart": 15000, + "name": "testnat", + "networkSecurityGroupRules": [ + { + "access": "Allow", + "priority": 150, + "sourceAddressPrefix": "192.100.12.45", + "sourcePortRanges": ["1", "2"], + }, + { + "access": "Deny", + "priority": 3500, + "sourceAddressPrefix": "*", + "sourcePortRanges": ["*"], + }, + ], + "protocol": "TCP", + } + ] + } + }, + "scaleSettings": {"autoScale": {"evaluationInterval": "PT5M", "formula": "$TargetDedicatedNodes=1"}}, + "vmSize": "STANDARD_D4", + } + }, + ) + print(response) + + +# x-ms-original-file: specification/batch/resource-manager/Microsoft.Batch/stable/2022-10-01/examples/PoolCreate_VirtualMachineConfiguration.json +if __name__ == "__main__": + main() diff --git a/sdk/batch/azure-mgmt-batch/generated_samples/create_pool__minimal_cloud_service_configuration.py b/sdk/batch/azure-mgmt-batch/generated_samples/create_pool__minimal_cloud_service_configuration.py new file mode 100644 index 000000000000..91390e466a2d --- /dev/null +++ b/sdk/batch/azure-mgmt-batch/generated_samples/create_pool__minimal_cloud_service_configuration.py @@ -0,0 +1,49 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.batch import BatchManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-batch +# USAGE + python create_pool__minimal_cloud_service_configuration.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = BatchManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subid", + ) + + response = client.pool.create( + resource_group_name="default-azurebatch-japaneast", + account_name="sampleacct", + pool_name="testpool", + parameters={ + "properties": { + "deploymentConfiguration": {"cloudServiceConfiguration": {"osFamily": "5"}}, + "scaleSettings": {"fixedScale": {"targetDedicatedNodes": 3}}, + "vmSize": "STANDARD_D4", + } + }, + ) + print(response) + + +# x-ms-original-file: specification/batch/resource-manager/Microsoft.Batch/stable/2022-10-01/examples/PoolCreate_MinimalCloudServiceConfiguration.json +if __name__ == "__main__": + main() diff --git a/sdk/batch/azure-mgmt-batch/generated_samples/create_pool__minimal_virtual_machine_configuration.py b/sdk/batch/azure-mgmt-batch/generated_samples/create_pool__minimal_virtual_machine_configuration.py new file mode 100644 index 000000000000..6962ecdf29dd --- /dev/null +++ b/sdk/batch/azure-mgmt-batch/generated_samples/create_pool__minimal_virtual_machine_configuration.py @@ -0,0 +1,59 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.batch import BatchManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-batch +# USAGE + python create_pool__minimal_virtual_machine_configuration.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = BatchManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subid", + ) + + response = client.pool.create( + resource_group_name="default-azurebatch-japaneast", + account_name="sampleacct", + pool_name="testpool", + parameters={ + "properties": { + "deploymentConfiguration": { + "virtualMachineConfiguration": { + "imageReference": { + "offer": "UbuntuServer", + "publisher": "Canonical", + "sku": "18.04-LTS", + "version": "latest", + }, + "nodeAgentSkuId": "batch.node.ubuntu 18.04", + } + }, + "scaleSettings": {"autoScale": {"evaluationInterval": "PT5M", "formula": "$TargetDedicatedNodes=1"}}, + "vmSize": "STANDARD_D4", + } + }, + ) + print(response) + + +# x-ms-original-file: specification/batch/resource-manager/Microsoft.Batch/stable/2022-10-01/examples/PoolCreate_MinimalVirtualMachineConfiguration.json +if __name__ == "__main__": + main() diff --git a/sdk/batch/azure-mgmt-batch/generated_samples/create_pool__no_public_ip.py b/sdk/batch/azure-mgmt-batch/generated_samples/create_pool__no_public_ip.py new file mode 100644 index 000000000000..2b2fc073a4aa --- /dev/null +++ b/sdk/batch/azure-mgmt-batch/generated_samples/create_pool__no_public_ip.py @@ -0,0 +1,59 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.batch import BatchManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-batch +# USAGE + python create_pool__no_public_ip.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = BatchManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subid", + ) + + response = client.pool.create( + resource_group_name="default-azurebatch-japaneast", + account_name="sampleacct", + pool_name="testpool", + parameters={ + "properties": { + "deploymentConfiguration": { + "virtualMachineConfiguration": { + "imageReference": { + "id": "/subscriptions/subid/resourceGroups/networking-group/providers/Microsoft.Compute/galleries/testgallery/images/testimagedef/versions/0.0.1" + }, + "nodeAgentSkuId": "batch.node.ubuntu 18.04", + } + }, + "networkConfiguration": { + "publicIPAddressConfiguration": {"provision": "NoPublicIPAddresses"}, + "subnetId": "/subscriptions/subid/resourceGroups/rg1234/providers/Microsoft.Network/virtualNetworks/network1234/subnets/subnet123", + }, + "vmSize": "STANDARD_D4", + } + }, + ) + print(response) + + +# x-ms-original-file: specification/batch/resource-manager/Microsoft.Batch/stable/2022-10-01/examples/PoolCreate_NoPublicIPAddresses.json +if __name__ == "__main__": + main() diff --git a/sdk/batch/azure-mgmt-batch/generated_samples/create_pool__public_ips.py b/sdk/batch/azure-mgmt-batch/generated_samples/create_pool__public_ips.py new file mode 100644 index 000000000000..4bd64b7807ac --- /dev/null +++ b/sdk/batch/azure-mgmt-batch/generated_samples/create_pool__public_ips.py @@ -0,0 +1,64 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.batch import BatchManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-batch +# USAGE + python create_pool__public_ips.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = BatchManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subid", + ) + + response = client.pool.create( + resource_group_name="default-azurebatch-japaneast", + account_name="sampleacct", + pool_name="testpool", + parameters={ + "properties": { + "deploymentConfiguration": { + "virtualMachineConfiguration": { + "imageReference": { + "id": "/subscriptions/subid/resourceGroups/networking-group/providers/Microsoft.Compute/galleries/testgallery/images/testimagedef/versions/0.0.1" + }, + "nodeAgentSkuId": "batch.node.ubuntu 18.04", + } + }, + "networkConfiguration": { + "publicIPAddressConfiguration": { + "ipAddressIds": [ + "/subscriptions/subid1/resourceGroups/rg13/providers/Microsoft.Network/publicIPAddresses/ip135" + ], + "provision": "UserManaged", + }, + "subnetId": "/subscriptions/subid/resourceGroups/rg1234/providers/Microsoft.Network/virtualNetworks/network1234/subnets/subnet123", + }, + "vmSize": "STANDARD_D4", + } + }, + ) + print(response) + + +# x-ms-original-file: specification/batch/resource-manager/Microsoft.Batch/stable/2022-10-01/examples/PoolCreate_PublicIPs.json +if __name__ == "__main__": + main() diff --git a/sdk/batch/azure-mgmt-batch/generated_samples/create_pool__user_assigned_identities.py b/sdk/batch/azure-mgmt-batch/generated_samples/create_pool__user_assigned_identities.py new file mode 100644 index 000000000000..39ea3f23d694 --- /dev/null +++ b/sdk/batch/azure-mgmt-batch/generated_samples/create_pool__user_assigned_identities.py @@ -0,0 +1,66 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.batch import BatchManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-batch +# USAGE + python create_pool__user_assigned_identities.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = BatchManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subid", + ) + + response = client.pool.create( + resource_group_name="default-azurebatch-japaneast", + account_name="sampleacct", + pool_name="testpool", + parameters={ + "identity": { + "type": "UserAssigned", + "userAssignedIdentities": { + "/subscriptions/subid/resourceGroups/default-azurebatch-japaneast/providers/Microsoft.ManagedIdentity/userAssignedIdentities/id1": {}, + "/subscriptions/subid/resourceGroups/default-azurebatch-japaneast/providers/Microsoft.ManagedIdentity/userAssignedIdentities/id2": {}, + }, + }, + "properties": { + "deploymentConfiguration": { + "virtualMachineConfiguration": { + "imageReference": { + "offer": "UbuntuServer", + "publisher": "Canonical", + "sku": "18.04-LTS", + "version": "latest", + }, + "nodeAgentSkuId": "batch.node.ubuntu 18.04", + } + }, + "scaleSettings": {"autoScale": {"evaluationInterval": "PT5M", "formula": "$TargetDedicatedNodes=1"}}, + "vmSize": "STANDARD_D4", + }, + }, + ) + print(response) + + +# x-ms-original-file: specification/batch/resource-manager/Microsoft.Batch/stable/2022-10-01/examples/PoolCreate_UserAssignedIdentities.json +if __name__ == "__main__": + main() diff --git a/sdk/batch/azure-mgmt-batch/generated_samples/create_pool__virtual_machine_configuration_extensions.py b/sdk/batch/azure-mgmt-batch/generated_samples/create_pool__virtual_machine_configuration_extensions.py new file mode 100644 index 000000000000..2c2ea4876475 --- /dev/null +++ b/sdk/batch/azure-mgmt-batch/generated_samples/create_pool__virtual_machine_configuration_extensions.py @@ -0,0 +1,70 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.batch import BatchManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-batch +# USAGE + python create_pool__virtual_machine_configuration_extensions.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = BatchManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subid", + ) + + response = client.pool.create( + resource_group_name="default-azurebatch-japaneast", + account_name="sampleacct", + pool_name="testpool", + parameters={ + "properties": { + "deploymentConfiguration": { + "virtualMachineConfiguration": { + "extensions": [ + { + "autoUpgradeMinorVersion": True, + "name": "batchextension1", + "protectedSettings": {"protectedSettingsKey": "protectedSettingsValue"}, + "publisher": "Microsoft.Azure.Security.Monitoring", + "settings": {"settingsKey": "settingsValue"}, + "type": "SecurityMonitoringForLinux", + "typeHandlerVersion": "1.0", + } + ], + "imageReference": { + "offer": "0001-com-ubuntu-server-focal", + "publisher": "Canonical", + "sku": "20_04-lts", + }, + "nodeAgentSkuId": "batch.node.ubuntu 20.04", + } + }, + "scaleSettings": {"autoScale": {"evaluationInterval": "PT5M", "formula": "$TargetDedicatedNodes=1"}}, + "targetNodeCommunicationMode": "Default", + "vmSize": "STANDARD_D4", + } + }, + ) + print(response) + + +# x-ms-original-file: specification/batch/resource-manager/Microsoft.Batch/stable/2022-10-01/examples/PoolCreate_VirtualMachineConfiguration_Extensions.json +if __name__ == "__main__": + main() diff --git a/sdk/batch/azure-mgmt-batch/generated_samples/delete_pool.py b/sdk/batch/azure-mgmt-batch/generated_samples/delete_pool.py new file mode 100644 index 000000000000..74cdf9c42212 --- /dev/null +++ b/sdk/batch/azure-mgmt-batch/generated_samples/delete_pool.py @@ -0,0 +1,42 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.batch import BatchManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-batch +# USAGE + python delete_pool.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = BatchManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subid", + ) + + response = client.pool.begin_delete( + resource_group_name="default-azurebatch-japaneast", + account_name="sampleacct", + pool_name="testpool", + ).result() + print(response) + + +# x-ms-original-file: specification/batch/resource-manager/Microsoft.Batch/stable/2022-10-01/examples/PoolDelete.json +if __name__ == "__main__": + main() diff --git a/sdk/batch/azure-mgmt-batch/generated_samples/disable_auto_scale.py b/sdk/batch/azure-mgmt-batch/generated_samples/disable_auto_scale.py new file mode 100644 index 000000000000..bce6cc84006e --- /dev/null +++ b/sdk/batch/azure-mgmt-batch/generated_samples/disable_auto_scale.py @@ -0,0 +1,42 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.batch import BatchManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-batch +# USAGE + python disable_auto_scale.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = BatchManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subid", + ) + + response = client.pool.disable_auto_scale( + resource_group_name="default-azurebatch-japaneast", + account_name="sampleacct", + pool_name="testpool", + ) + print(response) + + +# x-ms-original-file: specification/batch/resource-manager/Microsoft.Batch/stable/2022-10-01/examples/PoolDisableAutoScale.json +if __name__ == "__main__": + main() diff --git a/sdk/batch/azure-mgmt-batch/generated_samples/get_certificate.py b/sdk/batch/azure-mgmt-batch/generated_samples/get_certificate.py new file mode 100644 index 000000000000..8b31a1fb6a12 --- /dev/null +++ b/sdk/batch/azure-mgmt-batch/generated_samples/get_certificate.py @@ -0,0 +1,42 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.batch import BatchManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-batch +# USAGE + python get_certificate.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = BatchManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subid", + ) + + response = client.certificate.get( + resource_group_name="default-azurebatch-japaneast", + account_name="sampleacct", + certificate_name="sha1-0a0e4f50d51beadeac1d35afc5116098e7902e6e", + ) + print(response) + + +# x-ms-original-file: specification/batch/resource-manager/Microsoft.Batch/stable/2022-10-01/examples/CertificateGet.json +if __name__ == "__main__": + main() diff --git a/sdk/batch/azure-mgmt-batch/generated_samples/get_certificate_with_deletion_error.py b/sdk/batch/azure-mgmt-batch/generated_samples/get_certificate_with_deletion_error.py new file mode 100644 index 000000000000..56a7152613da --- /dev/null +++ b/sdk/batch/azure-mgmt-batch/generated_samples/get_certificate_with_deletion_error.py @@ -0,0 +1,42 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.batch import BatchManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-batch +# USAGE + python get_certificate_with_deletion_error.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = BatchManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subid", + ) + + response = client.certificate.get( + resource_group_name="default-azurebatch-japaneast", + account_name="sampleacct", + certificate_name="sha1-0a0e4f50d51beadeac1d35afc5116098e7902e6e", + ) + print(response) + + +# x-ms-original-file: specification/batch/resource-manager/Microsoft.Batch/stable/2022-10-01/examples/CertificateGetWithDeletionError.json +if __name__ == "__main__": + main() diff --git a/sdk/batch/azure-mgmt-batch/generated_samples/get_detector.py b/sdk/batch/azure-mgmt-batch/generated_samples/get_detector.py new file mode 100644 index 000000000000..d36ed40c280a --- /dev/null +++ b/sdk/batch/azure-mgmt-batch/generated_samples/get_detector.py @@ -0,0 +1,42 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.batch import BatchManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-batch +# USAGE + python get_detector.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = BatchManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subid", + ) + + response = client.batch_account.get_detector( + resource_group_name="default-azurebatch-japaneast", + account_name="sampleacct", + detector_id="poolsAndNodes", + ) + print(response) + + +# x-ms-original-file: specification/batch/resource-manager/Microsoft.Batch/stable/2022-10-01/examples/DetectorGet.json +if __name__ == "__main__": + main() diff --git a/sdk/batch/azure-mgmt-batch/generated_samples/get_pool.py b/sdk/batch/azure-mgmt-batch/generated_samples/get_pool.py new file mode 100644 index 000000000000..8916cab7de10 --- /dev/null +++ b/sdk/batch/azure-mgmt-batch/generated_samples/get_pool.py @@ -0,0 +1,42 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.batch import BatchManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-batch +# USAGE + python get_pool.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = BatchManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subid", + ) + + response = client.pool.get( + resource_group_name="default-azurebatch-japaneast", + account_name="sampleacct", + pool_name="testpool", + ) + print(response) + + +# x-ms-original-file: specification/batch/resource-manager/Microsoft.Batch/stable/2022-10-01/examples/PoolGet.json +if __name__ == "__main__": + main() diff --git a/sdk/batch/azure-mgmt-batch/generated_samples/get_pool__virtual_machine_configuration_extensions.py b/sdk/batch/azure-mgmt-batch/generated_samples/get_pool__virtual_machine_configuration_extensions.py new file mode 100644 index 000000000000..2e07cc4845a5 --- /dev/null +++ b/sdk/batch/azure-mgmt-batch/generated_samples/get_pool__virtual_machine_configuration_extensions.py @@ -0,0 +1,42 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.batch import BatchManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-batch +# USAGE + python get_pool__virtual_machine_configuration_extensions.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = BatchManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subid", + ) + + response = client.pool.get( + resource_group_name="default-azurebatch-japaneast", + account_name="sampleacct", + pool_name="testpool", + ) + print(response) + + +# x-ms-original-file: specification/batch/resource-manager/Microsoft.Batch/stable/2022-10-01/examples/PoolGet_VirtualMachineConfiguration_Extensions.json +if __name__ == "__main__": + main() diff --git a/sdk/batch/azure-mgmt-batch/generated_samples/get_private_endpoint_connection.py b/sdk/batch/azure-mgmt-batch/generated_samples/get_private_endpoint_connection.py new file mode 100644 index 000000000000..51c563d97c00 --- /dev/null +++ b/sdk/batch/azure-mgmt-batch/generated_samples/get_private_endpoint_connection.py @@ -0,0 +1,42 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.batch import BatchManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-batch +# USAGE + python get_private_endpoint_connection.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = BatchManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subid", + ) + + response = client.private_endpoint_connection.get( + resource_group_name="default-azurebatch-japaneast", + account_name="sampleacct", + private_endpoint_connection_name="testprivateEndpointConnection5testprivateEndpointConnection5.24d6b4b5-e65c-4330-bbe9-3a290d62f8e0", + ) + print(response) + + +# x-ms-original-file: specification/batch/resource-manager/Microsoft.Batch/stable/2022-10-01/examples/PrivateEndpointConnectionGet.json +if __name__ == "__main__": + main() diff --git a/sdk/batch/azure-mgmt-batch/generated_samples/get_private_link_resource.py b/sdk/batch/azure-mgmt-batch/generated_samples/get_private_link_resource.py new file mode 100644 index 000000000000..c5a50a8ff94f --- /dev/null +++ b/sdk/batch/azure-mgmt-batch/generated_samples/get_private_link_resource.py @@ -0,0 +1,42 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.batch import BatchManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-batch +# USAGE + python get_private_link_resource.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = BatchManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subid", + ) + + response = client.private_link_resource.get( + resource_group_name="default-azurebatch-japaneast", + account_name="sampleacct", + private_link_resource_name="batchAccount", + ) + print(response) + + +# x-ms-original-file: specification/batch/resource-manager/Microsoft.Batch/stable/2022-10-01/examples/PrivateLinkResourceGet.json +if __name__ == "__main__": + main() diff --git a/sdk/batch/azure-mgmt-batch/generated_samples/list_certificates.py b/sdk/batch/azure-mgmt-batch/generated_samples/list_certificates.py new file mode 100644 index 000000000000..26d98b006073 --- /dev/null +++ b/sdk/batch/azure-mgmt-batch/generated_samples/list_certificates.py @@ -0,0 +1,42 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.batch import BatchManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-batch +# USAGE + python list_certificates.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = BatchManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subid", + ) + + response = client.certificate.list_by_batch_account( + resource_group_name="default-azurebatch-japaneast", + account_name="sampleacct", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/batch/resource-manager/Microsoft.Batch/stable/2022-10-01/examples/CertificateList.json +if __name__ == "__main__": + main() diff --git a/sdk/batch/azure-mgmt-batch/generated_samples/list_certificates__filter_and_select.py b/sdk/batch/azure-mgmt-batch/generated_samples/list_certificates__filter_and_select.py new file mode 100644 index 000000000000..269cb679a109 --- /dev/null +++ b/sdk/batch/azure-mgmt-batch/generated_samples/list_certificates__filter_and_select.py @@ -0,0 +1,42 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.batch import BatchManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-batch +# USAGE + python list_certificates__filter_and_select.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = BatchManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subid", + ) + + response = client.certificate.list_by_batch_account( + resource_group_name="default-azurebatch-japaneast", + account_name="sampleacct", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/batch/resource-manager/Microsoft.Batch/stable/2022-10-01/examples/CertificateListWithFilter.json +if __name__ == "__main__": + main() diff --git a/sdk/batch/azure-mgmt-batch/generated_samples/list_detectors.py b/sdk/batch/azure-mgmt-batch/generated_samples/list_detectors.py new file mode 100644 index 000000000000..8a23dae29646 --- /dev/null +++ b/sdk/batch/azure-mgmt-batch/generated_samples/list_detectors.py @@ -0,0 +1,42 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.batch import BatchManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-batch +# USAGE + python list_detectors.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = BatchManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subid", + ) + + response = client.batch_account.list_detectors( + resource_group_name="default-azurebatch-japaneast", + account_name="sampleacct", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/batch/resource-manager/Microsoft.Batch/stable/2022-10-01/examples/DetectorList.json +if __name__ == "__main__": + main() diff --git a/sdk/batch/azure-mgmt-batch/generated_samples/list_outbound_network_dependencies.py b/sdk/batch/azure-mgmt-batch/generated_samples/list_outbound_network_dependencies.py new file mode 100644 index 000000000000..a70131587aa1 --- /dev/null +++ b/sdk/batch/azure-mgmt-batch/generated_samples/list_outbound_network_dependencies.py @@ -0,0 +1,42 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.batch import BatchManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-batch +# USAGE + python list_outbound_network_dependencies.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = BatchManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subid", + ) + + response = client.batch_account.list_outbound_network_dependencies_endpoints( + resource_group_name="default-azurebatch-japaneast", + account_name="sampleacct", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/batch/resource-manager/Microsoft.Batch/stable/2022-10-01/examples/BatchAccountListOutboundNetworkDependenciesEndpoints.json +if __name__ == "__main__": + main() diff --git a/sdk/batch/azure-mgmt-batch/generated_samples/list_pool.py b/sdk/batch/azure-mgmt-batch/generated_samples/list_pool.py new file mode 100644 index 000000000000..64cfccf46176 --- /dev/null +++ b/sdk/batch/azure-mgmt-batch/generated_samples/list_pool.py @@ -0,0 +1,42 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.batch import BatchManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-batch +# USAGE + python list_pool.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = BatchManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subid", + ) + + response = client.pool.list_by_batch_account( + resource_group_name="default-azurebatch-japaneast", + account_name="sampleacct", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/batch/resource-manager/Microsoft.Batch/stable/2022-10-01/examples/PoolList.json +if __name__ == "__main__": + main() diff --git a/sdk/batch/azure-mgmt-batch/generated_samples/list_pool_with_filter.py b/sdk/batch/azure-mgmt-batch/generated_samples/list_pool_with_filter.py new file mode 100644 index 000000000000..dee4c3472184 --- /dev/null +++ b/sdk/batch/azure-mgmt-batch/generated_samples/list_pool_with_filter.py @@ -0,0 +1,42 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.batch import BatchManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-batch +# USAGE + python list_pool_with_filter.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = BatchManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subid", + ) + + response = client.pool.list_by_batch_account( + resource_group_name="default-azurebatch-japaneast", + account_name="sampleacct", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/batch/resource-manager/Microsoft.Batch/stable/2022-10-01/examples/PoolListWithFilter.json +if __name__ == "__main__": + main() diff --git a/sdk/batch/azure-mgmt-batch/generated_samples/list_private_endpoint_connections.py b/sdk/batch/azure-mgmt-batch/generated_samples/list_private_endpoint_connections.py new file mode 100644 index 000000000000..d189b5856f81 --- /dev/null +++ b/sdk/batch/azure-mgmt-batch/generated_samples/list_private_endpoint_connections.py @@ -0,0 +1,42 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.batch import BatchManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-batch +# USAGE + python list_private_endpoint_connections.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = BatchManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subid", + ) + + response = client.private_endpoint_connection.list_by_batch_account( + resource_group_name="default-azurebatch-japaneast", + account_name="sampleacct", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/batch/resource-manager/Microsoft.Batch/stable/2022-10-01/examples/PrivateEndpointConnectionsList.json +if __name__ == "__main__": + main() diff --git a/sdk/batch/azure-mgmt-batch/generated_samples/list_private_link_resource.py b/sdk/batch/azure-mgmt-batch/generated_samples/list_private_link_resource.py new file mode 100644 index 000000000000..052a8a3b0679 --- /dev/null +++ b/sdk/batch/azure-mgmt-batch/generated_samples/list_private_link_resource.py @@ -0,0 +1,42 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.batch import BatchManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-batch +# USAGE + python list_private_link_resource.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = BatchManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subid", + ) + + response = client.private_link_resource.list_by_batch_account( + resource_group_name="default-azurebatch-japaneast", + account_name="sampleacct", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/batch/resource-manager/Microsoft.Batch/stable/2022-10-01/examples/PrivateLinkResourcesList.json +if __name__ == "__main__": + main() diff --git a/sdk/batch/azure-mgmt-batch/generated_samples/location_check_name_availability_already_exists.py b/sdk/batch/azure-mgmt-batch/generated_samples/location_check_name_availability_already_exists.py new file mode 100644 index 000000000000..e1faa5d7db30 --- /dev/null +++ b/sdk/batch/azure-mgmt-batch/generated_samples/location_check_name_availability_already_exists.py @@ -0,0 +1,41 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.batch import BatchManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-batch +# USAGE + python location_check_name_availability_already_exists.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = BatchManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subid", + ) + + response = client.location.check_name_availability( + location_name="japaneast", + parameters={"name": "existingaccountname", "type": "Microsoft.Batch/batchAccounts"}, + ) + print(response) + + +# x-ms-original-file: specification/batch/resource-manager/Microsoft.Batch/stable/2022-10-01/examples/LocationCheckNameAvailability_AlreadyExists.json +if __name__ == "__main__": + main() diff --git a/sdk/batch/azure-mgmt-batch/generated_samples/location_check_name_availability_available.py b/sdk/batch/azure-mgmt-batch/generated_samples/location_check_name_availability_available.py new file mode 100644 index 000000000000..da0487e406fe --- /dev/null +++ b/sdk/batch/azure-mgmt-batch/generated_samples/location_check_name_availability_available.py @@ -0,0 +1,41 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.batch import BatchManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-batch +# USAGE + python location_check_name_availability_available.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = BatchManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subid", + ) + + response = client.location.check_name_availability( + location_name="japaneast", + parameters={"name": "newaccountname", "type": "Microsoft.Batch/batchAccounts"}, + ) + print(response) + + +# x-ms-original-file: specification/batch/resource-manager/Microsoft.Batch/stable/2022-10-01/examples/LocationCheckNameAvailability_Available.json +if __name__ == "__main__": + main() diff --git a/sdk/batch/azure-mgmt-batch/generated_samples/location_get_quotas.py b/sdk/batch/azure-mgmt-batch/generated_samples/location_get_quotas.py new file mode 100644 index 000000000000..25a2cd47e5be --- /dev/null +++ b/sdk/batch/azure-mgmt-batch/generated_samples/location_get_quotas.py @@ -0,0 +1,40 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.batch import BatchManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-batch +# USAGE + python location_get_quotas.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = BatchManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subid", + ) + + response = client.location.get_quotas( + location_name="japaneast", + ) + print(response) + + +# x-ms-original-file: specification/batch/resource-manager/Microsoft.Batch/stable/2022-10-01/examples/LocationGetQuotas.json +if __name__ == "__main__": + main() diff --git a/sdk/batch/azure-mgmt-batch/generated_samples/location_list_cloud_service_skus.py b/sdk/batch/azure-mgmt-batch/generated_samples/location_list_cloud_service_skus.py new file mode 100644 index 000000000000..ebdd1afa0ff5 --- /dev/null +++ b/sdk/batch/azure-mgmt-batch/generated_samples/location_list_cloud_service_skus.py @@ -0,0 +1,41 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.batch import BatchManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-batch +# USAGE + python location_list_cloud_service_skus.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = BatchManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subid", + ) + + response = client.location.list_supported_cloud_service_skus( + location_name="japaneast", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/batch/resource-manager/Microsoft.Batch/stable/2022-10-01/examples/LocationListCloudServiceSkus.json +if __name__ == "__main__": + main() diff --git a/sdk/batch/azure-mgmt-batch/generated_samples/location_list_virtual_machine_skus.py b/sdk/batch/azure-mgmt-batch/generated_samples/location_list_virtual_machine_skus.py new file mode 100644 index 000000000000..b766e122317b --- /dev/null +++ b/sdk/batch/azure-mgmt-batch/generated_samples/location_list_virtual_machine_skus.py @@ -0,0 +1,41 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.batch import BatchManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-batch +# USAGE + python location_list_virtual_machine_skus.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = BatchManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subid", + ) + + response = client.location.list_supported_virtual_machine_skus( + location_name="japaneast", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/batch/resource-manager/Microsoft.Batch/stable/2022-10-01/examples/LocationListVirtualMachineSkus.json +if __name__ == "__main__": + main() diff --git a/sdk/batch/azure-mgmt-batch/generated_samples/operations_list.py b/sdk/batch/azure-mgmt-batch/generated_samples/operations_list.py new file mode 100644 index 000000000000..199b758ae833 --- /dev/null +++ b/sdk/batch/azure-mgmt-batch/generated_samples/operations_list.py @@ -0,0 +1,39 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.batch import BatchManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-batch +# USAGE + python operations_list.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = BatchManagementClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.operations.list() + for item in response: + print(item) + + +# x-ms-original-file: specification/batch/resource-manager/Microsoft.Batch/stable/2022-10-01/examples/OperationsList.json +if __name__ == "__main__": + main() diff --git a/sdk/batch/azure-mgmt-batch/generated_samples/private_batch_account_create.py b/sdk/batch/azure-mgmt-batch/generated_samples/private_batch_account_create.py new file mode 100644 index 000000000000..4fda4ddc1b4c --- /dev/null +++ b/sdk/batch/azure-mgmt-batch/generated_samples/private_batch_account_create.py @@ -0,0 +1,54 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.batch import BatchManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-batch +# USAGE + python private_batch_account_create.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = BatchManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subid", + ) + + response = client.batch_account.begin_create( + resource_group_name="default-azurebatch-japaneast", + account_name="sampleacct", + parameters={ + "location": "japaneast", + "properties": { + "autoStorage": { + "storageAccountId": "/subscriptions/subid/resourceGroups/default-azurebatch-japaneast/providers/Microsoft.Storage/storageAccounts/samplestorage" + }, + "keyVaultReference": { + "id": "/subscriptions/subid/resourceGroups/default-azurebatch-japaneast/providers/Microsoft.KeyVault/vaults/sample", + "url": "http://sample.vault.azure.net/", + }, + "publicNetworkAccess": "Disabled", + }, + }, + ).result() + print(response) + + +# x-ms-original-file: specification/batch/resource-manager/Microsoft.Batch/stable/2022-10-01/examples/PrivateBatchAccountCreate.json +if __name__ == "__main__": + main() diff --git a/sdk/batch/azure-mgmt-batch/generated_samples/private_batch_account_get.py b/sdk/batch/azure-mgmt-batch/generated_samples/private_batch_account_get.py new file mode 100644 index 000000000000..fe9aae74896f --- /dev/null +++ b/sdk/batch/azure-mgmt-batch/generated_samples/private_batch_account_get.py @@ -0,0 +1,41 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.batch import BatchManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-batch +# USAGE + python private_batch_account_get.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = BatchManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subid", + ) + + response = client.batch_account.get( + resource_group_name="default-azurebatch-japaneast", + account_name="sampleacct", + ) + print(response) + + +# x-ms-original-file: specification/batch/resource-manager/Microsoft.Batch/stable/2022-10-01/examples/PrivateBatchAccountGet.json +if __name__ == "__main__": + main() diff --git a/sdk/batch/azure-mgmt-batch/generated_samples/private_endpoint_connection_delete.py b/sdk/batch/azure-mgmt-batch/generated_samples/private_endpoint_connection_delete.py new file mode 100644 index 000000000000..7338238e45b6 --- /dev/null +++ b/sdk/batch/azure-mgmt-batch/generated_samples/private_endpoint_connection_delete.py @@ -0,0 +1,42 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.batch import BatchManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-batch +# USAGE + python private_endpoint_connection_delete.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = BatchManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subid", + ) + + response = client.private_endpoint_connection.begin_delete( + resource_group_name="default-azurebatch-japaneast", + account_name="sampleacct", + private_endpoint_connection_name="testprivateEndpointConnection5testprivateEndpointConnection5.24d6b4b5-e65c-4330-bbe9-3a290d62f8e0", + ).result() + print(response) + + +# x-ms-original-file: specification/batch/resource-manager/Microsoft.Batch/stable/2022-10-01/examples/PrivateEndpointConnectionDelete.json +if __name__ == "__main__": + main() diff --git a/sdk/batch/azure-mgmt-batch/generated_samples/stop_pool_resize.py b/sdk/batch/azure-mgmt-batch/generated_samples/stop_pool_resize.py new file mode 100644 index 000000000000..199050954ac7 --- /dev/null +++ b/sdk/batch/azure-mgmt-batch/generated_samples/stop_pool_resize.py @@ -0,0 +1,42 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.batch import BatchManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-batch +# USAGE + python stop_pool_resize.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = BatchManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subid", + ) + + response = client.pool.stop_resize( + resource_group_name="default-azurebatch-japaneast", + account_name="sampleacct", + pool_name="testpool", + ) + print(response) + + +# x-ms-original-file: specification/batch/resource-manager/Microsoft.Batch/stable/2022-10-01/examples/PoolStopResize.json +if __name__ == "__main__": + main() diff --git a/sdk/batch/azure-mgmt-batch/generated_samples/update_certificate.py b/sdk/batch/azure-mgmt-batch/generated_samples/update_certificate.py new file mode 100644 index 000000000000..539895a85323 --- /dev/null +++ b/sdk/batch/azure-mgmt-batch/generated_samples/update_certificate.py @@ -0,0 +1,43 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.batch import BatchManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-batch +# USAGE + python update_certificate.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = BatchManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subid", + ) + + response = client.certificate.update( + resource_group_name="default-azurebatch-japaneast", + account_name="sampleacct", + certificate_name="sha1-0a0e4f50d51beadeac1d35afc5116098e7902e6e", + parameters={"properties": {"data": "MIIJsgIBAzCCCW4GCSqGSIb3DQE...", "password": ""}}, + ) + print(response) + + +# x-ms-original-file: specification/batch/resource-manager/Microsoft.Batch/stable/2022-10-01/examples/CertificateUpdate.json +if __name__ == "__main__": + main() diff --git a/sdk/batch/azure-mgmt-batch/generated_samples/update_pool__enable_autoscale.py b/sdk/batch/azure-mgmt-batch/generated_samples/update_pool__enable_autoscale.py new file mode 100644 index 000000000000..ec6de6d64b8d --- /dev/null +++ b/sdk/batch/azure-mgmt-batch/generated_samples/update_pool__enable_autoscale.py @@ -0,0 +1,43 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.batch import BatchManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-batch +# USAGE + python update_pool__enable_autoscale.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = BatchManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subid", + ) + + response = client.pool.update( + resource_group_name="default-azurebatch-japaneast", + account_name="sampleacct", + pool_name="testpool", + parameters={"properties": {"scaleSettings": {"autoScale": {"formula": "$TargetDedicatedNodes=34"}}}}, + ) + print(response) + + +# x-ms-original-file: specification/batch/resource-manager/Microsoft.Batch/stable/2022-10-01/examples/PoolUpdate_EnableAutoScale.json +if __name__ == "__main__": + main() diff --git a/sdk/batch/azure-mgmt-batch/generated_samples/update_pool__other_properties.py b/sdk/batch/azure-mgmt-batch/generated_samples/update_pool__other_properties.py new file mode 100644 index 000000000000..3dade8a42359 --- /dev/null +++ b/sdk/batch/azure-mgmt-batch/generated_samples/update_pool__other_properties.py @@ -0,0 +1,64 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.batch import BatchManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-batch +# USAGE + python update_pool__other_properties.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = BatchManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subid", + ) + + response = client.pool.update( + resource_group_name="default-azurebatch-japaneast", + account_name="sampleacct", + pool_name="testpool", + parameters={ + "properties": { + "applicationPackages": [ + { + "id": "/subscriptions/subid/resourceGroups/default-azurebatch-japaneast/providers/Microsoft.Batch/batchAccounts/sampleacct/pools/testpool/applications/app_1234" + }, + { + "id": "/subscriptions/subid/resourceGroups/default-azurebatch-japaneast/providers/Microsoft.Batch/batchAccounts/sampleacct/pools/testpool/applications/app_5678", + "version": "1.0", + }, + ], + "certificates": [ + { + "id": "/subscriptions/subid/resourceGroups/default-azurebatch-japaneast/providers/Microsoft.Batch/batchAccounts/sampleacct/pools/testpool/certificates/sha1-1234567", + "storeLocation": "LocalMachine", + "storeName": "MY", + } + ], + "metadata": [{"name": "key1", "value": "value1"}], + "targetNodeCommunicationMode": "Simplified", + } + }, + ) + print(response) + + +# x-ms-original-file: specification/batch/resource-manager/Microsoft.Batch/stable/2022-10-01/examples/PoolUpdate_OtherProperties.json +if __name__ == "__main__": + main() diff --git a/sdk/batch/azure-mgmt-batch/generated_samples/update_pool__remove_start_task.py b/sdk/batch/azure-mgmt-batch/generated_samples/update_pool__remove_start_task.py new file mode 100644 index 000000000000..5fc6eafaf689 --- /dev/null +++ b/sdk/batch/azure-mgmt-batch/generated_samples/update_pool__remove_start_task.py @@ -0,0 +1,43 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.batch import BatchManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-batch +# USAGE + python update_pool__remove_start_task.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = BatchManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subid", + ) + + response = client.pool.update( + resource_group_name="default-azurebatch-japaneast", + account_name="sampleacct", + pool_name="testpool", + parameters={"properties": {"startTask": {}}}, + ) + print(response) + + +# x-ms-original-file: specification/batch/resource-manager/Microsoft.Batch/stable/2022-10-01/examples/PoolUpdate_RemoveStartTask.json +if __name__ == "__main__": + main() diff --git a/sdk/batch/azure-mgmt-batch/generated_samples/update_pool__resize_pool.py b/sdk/batch/azure-mgmt-batch/generated_samples/update_pool__resize_pool.py new file mode 100644 index 000000000000..491b78d9a48d --- /dev/null +++ b/sdk/batch/azure-mgmt-batch/generated_samples/update_pool__resize_pool.py @@ -0,0 +1,54 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.batch import BatchManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-batch +# USAGE + python update_pool__resize_pool.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = BatchManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subid", + ) + + response = client.pool.update( + resource_group_name="default-azurebatch-japaneast", + account_name="sampleacct", + pool_name="testpool", + parameters={ + "properties": { + "scaleSettings": { + "fixedScale": { + "nodeDeallocationOption": "TaskCompletion", + "resizeTimeout": "PT8M", + "targetDedicatedNodes": 5, + "targetLowPriorityNodes": 0, + } + } + } + }, + ) + print(response) + + +# x-ms-original-file: specification/batch/resource-manager/Microsoft.Batch/stable/2022-10-01/examples/PoolUpdate_ResizePool.json +if __name__ == "__main__": + main() diff --git a/sdk/batch/azure-mgmt-batch/generated_samples/update_private_endpoint_connection.py b/sdk/batch/azure-mgmt-batch/generated_samples/update_private_endpoint_connection.py new file mode 100644 index 000000000000..69a42217711f --- /dev/null +++ b/sdk/batch/azure-mgmt-batch/generated_samples/update_private_endpoint_connection.py @@ -0,0 +1,50 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.batch import BatchManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-batch +# USAGE + python update_private_endpoint_connection.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = BatchManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subid", + ) + + response = client.private_endpoint_connection.begin_update( + resource_group_name="default-azurebatch-japaneast", + account_name="sampleacct", + private_endpoint_connection_name="testprivateEndpointConnection5.24d6b4b5-e65c-4330-bbe9-3a290d62f8e0", + parameters={ + "properties": { + "privateLinkServiceConnectionState": { + "description": "Approved by xyz.abc@company.com", + "status": "Approved", + } + } + }, + ).result() + print(response) + + +# x-ms-original-file: specification/batch/resource-manager/Microsoft.Batch/stable/2022-10-01/examples/PrivateEndpointConnectionUpdate.json +if __name__ == "__main__": + main()