From a66fd1ccbc96253e96aadf9e3a049b9727f3c9ad Mon Sep 17 00:00:00 2001 From: SDKAuto Date: Fri, 10 Feb 2023 07:49:44 +0000 Subject: [PATCH] CodeGen from PR 22548 in Azure/azure-rest-api-specs Merge b02d2165210d99978f6a8bd99f7f512a92a155f9 into 18e0a756cd948b08cec7d4264f2dbbbfa53246ac --- sdk/network/azure-mgmt-dns/_meta.json | 11 +- .../azure-mgmt-dns/azure/mgmt/dns/__init__.py | 4 + .../azure/mgmt/dns/_configuration.py | 22 +- .../azure/mgmt/dns/_dns_management_client.py | 28 +- .../azure/mgmt/dns/_serialization.py | 1998 +++++++++++++++++ .../azure/mgmt/dns/aio/_configuration.py | 10 +- .../mgmt/dns/aio/_dns_management_client.py | 16 +- .../azure/mgmt/dns/v2016_04_01/__init__.py | 15 +- .../mgmt/dns/v2016_04_01/_configuration.py | 67 +- .../dns/v2016_04_01/_dns_management_client.py | 102 +- .../azure/mgmt/dns/v2016_04_01/_metadata.json | 63 +- .../azure/mgmt/dns/v2016_04_01/_patch.py | 20 + .../azure/mgmt/dns/v2016_04_01/_vendor.py | 30 + .../azure/mgmt/dns/v2016_04_01/_version.py | 2 +- .../mgmt/dns/v2016_04_01/aio/__init__.py | 15 +- .../dns/v2016_04_01/aio/_configuration.py | 61 +- .../v2016_04_01/aio/_dns_management_client.py | 81 +- .../azure/mgmt/dns/v2016_04_01/aio/_patch.py | 20 + .../v2016_04_01/aio/operations/__init__.py | 10 +- .../dns/v2016_04_01/aio/operations/_patch.py | 20 + .../aio/operations/_record_sets_operations.py | 850 ++++--- .../aio/operations/_zones_operations.py | 658 +++--- .../mgmt/dns/v2016_04_01/models/__init__.py | 120 +- .../models/_dns_management_client_enums.py | 39 +- .../mgmt/dns/v2016_04_01/models/_models.py | 623 ----- .../dns/v2016_04_01/models/_models_py3.py | 808 ++++--- .../mgmt/dns/v2016_04_01/models/_patch.py | 20 + .../dns/v2016_04_01/operations/__init__.py | 10 +- .../mgmt/dns/v2016_04_01/operations/_patch.py | 20 + .../operations/_record_sets_operations.py | 1188 +++++++--- .../operations/_zones_operations.py | 844 ++++--- .../mgmt/dns/v2018_03_01_preview/__init__.py | 15 +- .../dns/v2018_03_01_preview/_configuration.py | 67 +- .../_dns_management_client.py | 102 +- .../dns/v2018_03_01_preview/_metadata.json | 63 +- .../mgmt/dns/v2018_03_01_preview/_patch.py | 20 + .../mgmt/dns/v2018_03_01_preview/_vendor.py | 30 + .../mgmt/dns/v2018_03_01_preview/_version.py | 2 +- .../dns/v2018_03_01_preview/aio/__init__.py | 15 +- .../v2018_03_01_preview/aio/_configuration.py | 61 +- .../aio/_dns_management_client.py | 81 +- .../dns/v2018_03_01_preview/aio/_patch.py | 20 + .../aio/operations/__init__.py | 10 +- .../aio/operations/_patch.py | 20 + .../aio/operations/_record_sets_operations.py | 969 +++++--- .../aio/operations/_zones_operations.py | 830 ++++--- .../v2018_03_01_preview/models/__init__.py | 117 +- .../models/_dns_management_client_enums.py | 29 +- .../dns/v2018_03_01_preview/models/_models.py | 659 ------ .../v2018_03_01_preview/models/_models_py3.py | 798 ++++--- .../dns/v2018_03_01_preview/models/_patch.py | 20 + .../operations/__init__.py | 10 +- .../v2018_03_01_preview/operations/_patch.py | 20 + .../operations/_record_sets_operations.py | 1369 ++++++++--- .../operations/_zones_operations.py | 1074 ++++++--- .../azure/mgmt/dns/v2018_05_01/__init__.py | 15 +- .../mgmt/dns/v2018_05_01/_configuration.py | 68 +- .../dns/v2018_05_01/_dns_management_client.py | 110 +- .../azure/mgmt/dns/v2018_05_01/_metadata.json | 63 +- .../azure/mgmt/dns/v2018_05_01/_patch.py | 20 + .../azure/mgmt/dns/v2018_05_01/_vendor.py | 30 + .../azure/mgmt/dns/v2018_05_01/_version.py | 2 +- .../mgmt/dns/v2018_05_01/aio/__init__.py | 15 +- .../dns/v2018_05_01/aio/_configuration.py | 62 +- .../v2018_05_01/aio/_dns_management_client.py | 89 +- .../azure/mgmt/dns/v2018_05_01/aio/_patch.py | 20 + .../v2018_05_01/aio/operations/__init__.py | 12 +- .../_dns_resource_reference_operations.py | 183 +- .../dns/v2018_05_01/aio/operations/_patch.py | 20 + .../aio/operations/_record_sets_operations.py | 959 +++++--- .../aio/operations/_zones_operations.py | 821 ++++--- .../mgmt/dns/v2018_05_01/models/__init__.py | 127 +- .../models/_dns_management_client_enums.py | 29 +- .../mgmt/dns/v2018_05_01/models/_models.py | 694 ------ .../dns/v2018_05_01/models/_models_py3.py | 863 +++---- .../mgmt/dns/v2018_05_01/models/_patch.py | 20 + .../dns/v2018_05_01/operations/__init__.py | 12 +- .../_dns_resource_reference_operations.py | 218 +- .../mgmt/dns/v2018_05_01/operations/_patch.py | 20 + .../operations/_record_sets_operations.py | 1334 ++++++++--- .../operations/_zones_operations.py | 1045 ++++++--- .../create_or_update_aaaa_recordset.py | 46 + .../create_or_update_arecordset.py | 46 + .../create_or_update_arecordset_alias.py | 52 + .../create_or_update_caa_recordset.py | 50 + .../create_or_update_cname_recordset.py | 46 + .../create_or_update_mx_recordset.py | 50 + .../create_or_update_ns_recordset.py | 46 + .../create_or_update_ptr_recordset.py | 46 + .../create_or_update_soa_recordset.py | 58 + .../create_or_update_srv_recordset.py | 50 + .../create_or_update_txt_recordset.py | 50 + .../create_or_update_zone.py | 42 + .../delete_aaaa_recordset.py | 43 + .../generated_samples/delete_arecordset.py | 43 + .../generated_samples/delete_caa_recordset.py | 43 + .../generated_samples/delete_ptr_recordset.py | 43 + .../generated_samples/delete_srv_recordset.py | 43 + .../generated_samples/delete_txt_recordset.py | 43 + .../generated_samples/delete_zone.py | 41 + .../generated_samples/get_aaaa_recordset.py | 43 + .../generated_samples/get_arecordset.py | 43 + .../generated_samples/get_caa_recordset.py | 43 + .../generated_samples/get_cname_recordset.py | 43 + .../get_dns_resource_reference.py | 48 + .../generated_samples/get_mx_recordset.py | 43 + .../generated_samples/get_ns_recordset.py | 43 + .../generated_samples/get_ptr_recordset.py | 43 + .../generated_samples/get_soa_recordset.py | 43 + .../generated_samples/get_srv_recordset.py | 43 + .../generated_samples/get_txt_recordset.py | 43 + .../generated_samples/get_zone.py | 41 + .../generated_samples/list_aaaa_recordset.py | 43 + .../generated_samples/list_arecordset.py | 43 + .../generated_samples/list_caa_recordset.py | 43 + .../generated_samples/list_cname_recordset.py | 43 + .../generated_samples/list_mx_recordset.py | 43 + .../generated_samples/list_ns_recordset.py | 43 + .../generated_samples/list_ptr_recordset.py | 43 + .../list_record_sets_by_zone.py | 42 + .../generated_samples/list_soa_recordset.py | 43 + .../generated_samples/list_srv_recordset.py | 43 + .../generated_samples/list_txt_recordset.py | 43 + .../list_zones_by_resource_group.py | 41 + .../list_zones_by_subscription.py | 39 + .../generated_samples/patch_aaaa_recordset.py | 44 + .../generated_samples/patch_arecordset.py | 44 + .../generated_samples/patch_caa_recordset.py | 44 + .../patch_cname_recordset.py | 44 + .../generated_samples/patch_mx_recordset.py | 44 + .../generated_samples/patch_ns_recordset.py | 44 + .../generated_samples/patch_ptr_recordset.py | 44 + .../generated_samples/patch_soa_recordset.py | 44 + .../generated_samples/patch_srv_recordset.py | 44 + .../generated_samples/patch_txt_recordset.py | 44 + .../generated_samples/patch_zone.py | 42 + 136 files changed, 15635 insertions(+), 7826 deletions(-) create mode 100644 sdk/network/azure-mgmt-dns/azure/mgmt/dns/_serialization.py create mode 100644 sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2016_04_01/_patch.py create mode 100644 sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2016_04_01/_vendor.py create mode 100644 sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2016_04_01/aio/_patch.py create mode 100644 sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2016_04_01/aio/operations/_patch.py delete mode 100644 sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2016_04_01/models/_models.py create mode 100644 sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2016_04_01/models/_patch.py create mode 100644 sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2016_04_01/operations/_patch.py create mode 100644 sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_03_01_preview/_patch.py create mode 100644 sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_03_01_preview/_vendor.py create mode 100644 sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_03_01_preview/aio/_patch.py create mode 100644 sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_03_01_preview/aio/operations/_patch.py delete mode 100644 sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_03_01_preview/models/_models.py create mode 100644 sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_03_01_preview/models/_patch.py create mode 100644 sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_03_01_preview/operations/_patch.py create mode 100644 sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_05_01/_patch.py create mode 100644 sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_05_01/_vendor.py create mode 100644 sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_05_01/aio/_patch.py create mode 100644 sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_05_01/aio/operations/_patch.py delete mode 100644 sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_05_01/models/_models.py create mode 100644 sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_05_01/models/_patch.py create mode 100644 sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_05_01/operations/_patch.py create mode 100644 sdk/network/azure-mgmt-dns/generated_samples/create_or_update_aaaa_recordset.py create mode 100644 sdk/network/azure-mgmt-dns/generated_samples/create_or_update_arecordset.py create mode 100644 sdk/network/azure-mgmt-dns/generated_samples/create_or_update_arecordset_alias.py create mode 100644 sdk/network/azure-mgmt-dns/generated_samples/create_or_update_caa_recordset.py create mode 100644 sdk/network/azure-mgmt-dns/generated_samples/create_or_update_cname_recordset.py create mode 100644 sdk/network/azure-mgmt-dns/generated_samples/create_or_update_mx_recordset.py create mode 100644 sdk/network/azure-mgmt-dns/generated_samples/create_or_update_ns_recordset.py create mode 100644 sdk/network/azure-mgmt-dns/generated_samples/create_or_update_ptr_recordset.py create mode 100644 sdk/network/azure-mgmt-dns/generated_samples/create_or_update_soa_recordset.py create mode 100644 sdk/network/azure-mgmt-dns/generated_samples/create_or_update_srv_recordset.py create mode 100644 sdk/network/azure-mgmt-dns/generated_samples/create_or_update_txt_recordset.py create mode 100644 sdk/network/azure-mgmt-dns/generated_samples/create_or_update_zone.py create mode 100644 sdk/network/azure-mgmt-dns/generated_samples/delete_aaaa_recordset.py create mode 100644 sdk/network/azure-mgmt-dns/generated_samples/delete_arecordset.py create mode 100644 sdk/network/azure-mgmt-dns/generated_samples/delete_caa_recordset.py create mode 100644 sdk/network/azure-mgmt-dns/generated_samples/delete_ptr_recordset.py create mode 100644 sdk/network/azure-mgmt-dns/generated_samples/delete_srv_recordset.py create mode 100644 sdk/network/azure-mgmt-dns/generated_samples/delete_txt_recordset.py create mode 100644 sdk/network/azure-mgmt-dns/generated_samples/delete_zone.py create mode 100644 sdk/network/azure-mgmt-dns/generated_samples/get_aaaa_recordset.py create mode 100644 sdk/network/azure-mgmt-dns/generated_samples/get_arecordset.py create mode 100644 sdk/network/azure-mgmt-dns/generated_samples/get_caa_recordset.py create mode 100644 sdk/network/azure-mgmt-dns/generated_samples/get_cname_recordset.py create mode 100644 sdk/network/azure-mgmt-dns/generated_samples/get_dns_resource_reference.py create mode 100644 sdk/network/azure-mgmt-dns/generated_samples/get_mx_recordset.py create mode 100644 sdk/network/azure-mgmt-dns/generated_samples/get_ns_recordset.py create mode 100644 sdk/network/azure-mgmt-dns/generated_samples/get_ptr_recordset.py create mode 100644 sdk/network/azure-mgmt-dns/generated_samples/get_soa_recordset.py create mode 100644 sdk/network/azure-mgmt-dns/generated_samples/get_srv_recordset.py create mode 100644 sdk/network/azure-mgmt-dns/generated_samples/get_txt_recordset.py create mode 100644 sdk/network/azure-mgmt-dns/generated_samples/get_zone.py create mode 100644 sdk/network/azure-mgmt-dns/generated_samples/list_aaaa_recordset.py create mode 100644 sdk/network/azure-mgmt-dns/generated_samples/list_arecordset.py create mode 100644 sdk/network/azure-mgmt-dns/generated_samples/list_caa_recordset.py create mode 100644 sdk/network/azure-mgmt-dns/generated_samples/list_cname_recordset.py create mode 100644 sdk/network/azure-mgmt-dns/generated_samples/list_mx_recordset.py create mode 100644 sdk/network/azure-mgmt-dns/generated_samples/list_ns_recordset.py create mode 100644 sdk/network/azure-mgmt-dns/generated_samples/list_ptr_recordset.py create mode 100644 sdk/network/azure-mgmt-dns/generated_samples/list_record_sets_by_zone.py create mode 100644 sdk/network/azure-mgmt-dns/generated_samples/list_soa_recordset.py create mode 100644 sdk/network/azure-mgmt-dns/generated_samples/list_srv_recordset.py create mode 100644 sdk/network/azure-mgmt-dns/generated_samples/list_txt_recordset.py create mode 100644 sdk/network/azure-mgmt-dns/generated_samples/list_zones_by_resource_group.py create mode 100644 sdk/network/azure-mgmt-dns/generated_samples/list_zones_by_subscription.py create mode 100644 sdk/network/azure-mgmt-dns/generated_samples/patch_aaaa_recordset.py create mode 100644 sdk/network/azure-mgmt-dns/generated_samples/patch_arecordset.py create mode 100644 sdk/network/azure-mgmt-dns/generated_samples/patch_caa_recordset.py create mode 100644 sdk/network/azure-mgmt-dns/generated_samples/patch_cname_recordset.py create mode 100644 sdk/network/azure-mgmt-dns/generated_samples/patch_mx_recordset.py create mode 100644 sdk/network/azure-mgmt-dns/generated_samples/patch_ns_recordset.py create mode 100644 sdk/network/azure-mgmt-dns/generated_samples/patch_ptr_recordset.py create mode 100644 sdk/network/azure-mgmt-dns/generated_samples/patch_soa_recordset.py create mode 100644 sdk/network/azure-mgmt-dns/generated_samples/patch_srv_recordset.py create mode 100644 sdk/network/azure-mgmt-dns/generated_samples/patch_txt_recordset.py create mode 100644 sdk/network/azure-mgmt-dns/generated_samples/patch_zone.py diff --git a/sdk/network/azure-mgmt-dns/_meta.json b/sdk/network/azure-mgmt-dns/_meta.json index 19cfa750a1e4..413024430bfe 100644 --- a/sdk/network/azure-mgmt-dns/_meta.json +++ b/sdk/network/azure-mgmt-dns/_meta.json @@ -1,8 +1,11 @@ { - "autorest": "3.3.0", - "use": "@autorest/python@5.6.5", - "commit": "6fa6101166a28f1fd82d6a60b8038c9af236e2be", + "commit": "84fd7ed5bc4bc5b35e065a3650f416cd6a5357bc", "repository_url": "https://github.com/Azure/azure-rest-api-specs", - "autorest_command": "autorest specification/dns/resource-manager/readme.md --multiapi --python --python-mode=update --python-sdks-folder=/home/vsts/work/1/s/azure-sdk-for-python/sdk --track2 --use=@autorest/python@5.6.5 --version=3.3.0", + "autorest": "3.9.2", + "use": [ + "@autorest/python@6.4.0", + "@autorest/modelerfour@4.24.3" + ], + "autorest_command": "autorest specification/dns/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.4.0 --use=@autorest/modelerfour@4.24.3 --version=3.9.2 --version-tolerant=False", "readme": "specification/dns/resource-manager/readme.md" } \ No newline at end of file diff --git a/sdk/network/azure-mgmt-dns/azure/mgmt/dns/__init__.py b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/__init__.py index 34fbcbfae313..d6386eaf6897 100644 --- a/sdk/network/azure-mgmt-dns/azure/mgmt/dns/__init__.py +++ b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/__init__.py @@ -14,3 +14,7 @@ patch_sdk() except ImportError: pass + +from ._version import VERSION + +__version__ = VERSION diff --git a/sdk/network/azure-mgmt-dns/azure/mgmt/dns/_configuration.py b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/_configuration.py index d071d8cb9d78..afd57be6470e 100644 --- a/sdk/network/azure-mgmt-dns/azure/mgmt/dns/_configuration.py +++ b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/_configuration.py @@ -8,18 +8,16 @@ # Changes may cause incorrect behavior and will be lost if the code is # regenerated. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING +from typing import Any, TYPE_CHECKING from azure.core.configuration import Configuration from azure.core.pipeline import policies -from azure.mgmt.core.policies import ARMHttpLoggingPolicy +from azure.mgmt.core.policies import ARMChallengeAuthenticationPolicy, ARMHttpLoggingPolicy from ._version import VERSION if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports - from typing import Any - from azure.core.credentials import TokenCredential class DnsManagementClientConfiguration(Configuration): @@ -28,19 +26,18 @@ class DnsManagementClientConfiguration(Configuration): 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: Specifies the Azure subscription ID, which uniquely identifies the Microsoft Azure subscription. + :param subscription_id: Specifies the Azure subscription ID, which uniquely identifies the Microsoft Azure subscription. Required. :type subscription_id: str """ def __init__( self, - credential, # type: "TokenCredential" - subscription_id, # type: str - **kwargs # type: Any + credential: "TokenCredential", + subscription_id: str, + **kwargs: Any ): - # type: (...) -> None if credential is None: raise ValueError("Parameter 'credential' must not be None.") if subscription_id is None: @@ -55,9 +52,8 @@ def __init__( def _configure( self, - **kwargs # type: Any + **kwargs: 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) @@ -68,4 +64,4 @@ def _configure( self.redirect_policy = kwargs.get('redirect_policy') or policies.RedirectPolicy(**kwargs) self.authentication_policy = kwargs.get('authentication_policy') if self.credential and not self.authentication_policy: - self.authentication_policy = policies.BearerTokenCredentialPolicy(self.credential, *self.credential_scopes, **kwargs) + self.authentication_policy = ARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs) diff --git a/sdk/network/azure-mgmt-dns/azure/mgmt/dns/_dns_management_client.py b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/_dns_management_client.py index 018556c074ba..47bb0338ce0c 100644 --- a/sdk/network/azure-mgmt-dns/azure/mgmt/dns/_dns_management_client.py +++ b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/_dns_management_client.py @@ -9,21 +9,18 @@ # regenerated. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING +from typing import Any, Optional, TYPE_CHECKING from azure.mgmt.core import ARMPipelineClient from azure.profiles import KnownProfiles, ProfileDefinition from azure.profiles.multiapiclient import MultiApiClientMixin -from msrest import Deserializer, Serializer from ._configuration import DnsManagementClientConfiguration +from ._serialization import Deserializer, Serializer if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Optional - from azure.core.credentials import TokenCredential - from azure.core.pipeline.transport import HttpRequest, HttpResponse class _SDKClient(object): def __init__(self, *args, **kwargs): @@ -43,9 +40,9 @@ class DnsManagementClient(MultiApiClientMixin, _SDKClient): The api-version parameter sets the default API version if the operation group is not described in the profile. - :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: Specifies the Azure subscription ID, which uniquely identifies the Microsoft Azure subscription. + :param subscription_id: Specifies the Azure subscription ID, which uniquely identifies the Microsoft Azure subscription. Required. :type subscription_id: str :param api_version: API version to use if no profile is provided, or if missing in profile. :type api_version: str @@ -67,15 +64,13 @@ class DnsManagementClient(MultiApiClientMixin, _SDKClient): def __init__( self, - credential, # type: "TokenCredential" - subscription_id, # type: str - api_version=None, # type: Optional[str] - base_url=None, # type: Optional[str] - profile=KnownProfiles.default, # type: KnownProfiles - **kwargs # type: Any + credential: "TokenCredential", + subscription_id: str, + api_version: Optional[str]=None, + base_url: str = "https://management.azure.com", + profile: KnownProfiles=KnownProfiles.default, + **kwargs: Any ): - if not base_url: - base_url = 'https://management.azure.com' self._config = DnsManagementClientConfiguration(credential, subscription_id, **kwargs) self._client = ARMPipelineClient(base_url=base_url, config=self._config, **kwargs) super(DnsManagementClient, self).__init__( @@ -117,6 +112,7 @@ def dns_resource_reference(self): from .v2018_05_01.operations import DnsResourceReferenceOperations as OperationClass else: raise ValueError("API version {} does not have operation group 'dns_resource_reference'".format(api_version)) + self._config.api_version = api_version return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) @property @@ -136,6 +132,7 @@ def record_sets(self): from .v2018_05_01.operations import RecordSetsOperations as OperationClass else: raise ValueError("API version {} does not have operation group 'record_sets'".format(api_version)) + self._config.api_version = api_version return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) @property @@ -155,6 +152,7 @@ def zones(self): from .v2018_05_01.operations import ZonesOperations as OperationClass else: raise ValueError("API version {} does not have operation group 'zones'".format(api_version)) + self._config.api_version = api_version return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) def close(self): diff --git a/sdk/network/azure-mgmt-dns/azure/mgmt/dns/_serialization.py b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/_serialization.py new file mode 100644 index 000000000000..25467dfc00bb --- /dev/null +++ b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/_serialization.py @@ -0,0 +1,1998 @@ +# -------------------------------------------------------------------------- +# +# 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 +# pyright: reportUnnecessaryTypeIgnoreComment=false + +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 +from typing import ( + Dict, + Any, + cast, + Optional, + Union, + AnyStr, + IO, + Mapping, + Callable, + TypeVar, + MutableMapping, + Type, + List, + Mapping, +) + +try: + from urllib import quote # type: ignore +except ImportError: + from urllib.parse import quote +import xml.etree.ElementTree as ET + +import isodate # type: ignore + +from azure.core.exceptions import DeserializationError, SerializationError, raise_with_traceback +from azure.core.serialization import NULL as AzureCoreNull + +_BOM = codecs.BOM_UTF8.decode(encoding="utf-8") + +ModelType = TypeVar("ModelType", bound="Model") +JSON = MutableMapping[str, Any] + + +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: Optional[Union[AnyStr, IO]], content_type: Optional[str] = None) -> 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: Optional[Union[AnyStr, IO]], headers: 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 + unicode_str = str + +_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 # type: ignore +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 +except ImportError: + TZ_UTC = UTC() # type: ignore + +_FLATTEN = re.compile(r"(? None: + self.additional_properties: Dict[str, Any] = {} + for k in kwargs: + if k not in self._attribute_map: + _LOGGER.warning("%s is not a known attribute of class %s and will be ignored", k, self.__class__) + elif k in self._validation and self._validation[k].get("readonly", False): + _LOGGER.warning("Readonly attribute %s will be ignored in class %s", k, self.__class__) + else: + setattr(self, k, kwargs[k]) + + def __eq__(self, other: Any) -> bool: + """Compare objects by comparing all attributes.""" + if isinstance(other, self.__class__): + return self.__dict__ == other.__dict__ + return False + + def __ne__(self, other: Any) -> bool: + """Compare objects by comparing all attributes.""" + return not self.__eq__(other) + + def __str__(self) -> str: + return str(self.__dict__) + + @classmethod + def enable_additional_properties_sending(cls) -> None: + cls._attribute_map["additional_properties"] = {"key": "", "type": "{object}"} + + @classmethod + def is_xml_model(cls) -> bool: + try: + cls._xml_map # type: ignore + except AttributeError: + return False + return True + + @classmethod + def _create_xml_node(cls): + """Create XML node.""" + try: + xml_map = cls._xml_map # type: ignore + except AttributeError: + xml_map = {} + + return _create_xml_node(xml_map.get("name", cls.__name__), xml_map.get("prefix", None), xml_map.get("ns", None)) + + def serialize(self, keep_readonly: bool = False, **kwargs: Any) -> JSON: + """Return the JSON that would be sent to azure from this model. + + This is an alias to `as_dict(full_restapi_key_transformer, keep_readonly=False)`. + + If you want XML serialization, you can pass the kwargs is_xml=True. + + :param bool keep_readonly: If you want to serialize the readonly attributes + :returns: A dict JSON compatible object + :rtype: dict + """ + serializer = Serializer(self._infer_class_models()) + return serializer._serialize(self, keep_readonly=keep_readonly, **kwargs) + + def as_dict( + self, + keep_readonly: bool = True, + key_transformer: Callable[ + [str, Dict[str, Any], Any], Any + ] = attribute_transformer, + **kwargs: Any + ) -> JSON: + """Return a dict that can be serialized using json.dump. + + Advanced usage might optionally use a callback as parameter: + + .. code::python + + def my_key_transformer(key, attr_desc, value): + return key + + Key is the attribute name used in Python. Attr_desc + is a dict of metadata. Currently contains 'type' with the + msrest type and 'key' with the RestAPI encoded key. + Value is the current value in this object. + + The string returned will be used to serialize the key. + If the return type is a list, this is considered hierarchical + result dict. + + See the three examples in this file: + + - attribute_transformer + - full_restapi_key_transformer + - last_restapi_key_transformer + + If you want XML serialization, you can pass the kwargs is_xml=True. + + :param function key_transformer: A key transformer function. + :returns: A dict JSON compatible object + :rtype: dict + """ + serializer = Serializer(self._infer_class_models()) + return serializer._serialize(self, key_transformer=key_transformer, keep_readonly=keep_readonly, **kwargs) + + @classmethod + def _infer_class_models(cls): + try: + str_models = cls.__module__.rsplit(".", 1)[0] + models = sys.modules[str_models] + client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} + if cls.__name__ not in client_models: + raise ValueError("Not Autorest generated code") + except Exception: + # Assume it's not Autorest generated (tests?). Add ourselves as dependencies. + client_models = {cls.__name__: cls} + return client_models + + @classmethod + def deserialize(cls: Type[ModelType], data: Any, content_type: Optional[str] = None) -> ModelType: + """Parse a str using the RestAPI syntax and return a model. + + :param str data: A str using RestAPI structure. JSON by default. + :param str content_type: JSON by default, set application/xml if XML. + :returns: An instance of this model + :raises: DeserializationError if something went wrong + """ + deserializer = Deserializer(cls._infer_class_models()) + return deserializer(cls.__name__, data, content_type=content_type) + + @classmethod + def from_dict( + cls: Type[ModelType], + data: Any, + key_extractors: Optional[Callable[[str, Dict[str, Any], Any], Any]] = None, + content_type: Optional[str] = None, + ) -> ModelType: + """Parse a dict using given key extractor return a model. + + By default consider key + extractors (rest_key_case_insensitive_extractor, attribute_key_case_insensitive_extractor + and last_rest_key_case_insensitive_extractor) + + :param dict data: A dict using RestAPI structure + :param str content_type: JSON by default, set application/xml if XML. + :returns: An instance of this model + :raises: DeserializationError if something went wrong + """ + deserializer = Deserializer(cls._infer_class_models()) + deserializer.key_extractors = ( # type: ignore + [ # type: ignore + attribute_key_case_insensitive_extractor, + rest_key_case_insensitive_extractor, + last_rest_key_case_insensitive_extractor, + ] + if key_extractors is None + else key_extractors + ) + return deserializer(cls.__name__, data, content_type=content_type) + + @classmethod + def _flatten_subtype(cls, key, objects): + if "_subtype_map" not in cls.__dict__: + return {} + result = dict(cls._subtype_map[key]) + for valuetype in cls._subtype_map[key].values(): + result.update(objects[valuetype]._flatten_subtype(key, objects)) + return result + + @classmethod + def _classify(cls, response, objects): + """Check the class _subtype_map for any child classes. + We want to ignore any inherited _subtype_maps. + Remove the polymorphic key from the initial data. + """ + for subtype_key in cls.__dict__.get("_subtype_map", {}).keys(): + subtype_value = None + + if not isinstance(response, ET.Element): + rest_api_response_key = cls._get_rest_key_parts(subtype_key)[-1] + subtype_value = response.pop(rest_api_response_key, None) or response.pop(subtype_key, None) + else: + subtype_value = xml_key_extractor(subtype_key, cls._attribute_map[subtype_key], response) + if subtype_value: + # Try to match base class. Can be class name only + # (bug to fix in Autorest to support x-ms-discriminator-name) + if cls.__name__ == subtype_value: + return cls + flatten_mapping_type = cls._flatten_subtype(subtype_key, objects) + try: + return objects[flatten_mapping_type[subtype_value]] # type: ignore + except KeyError: + _LOGGER.warning( + "Subtype value %s has no mapping, use base class %s.", + subtype_value, + cls.__name__, + ) + break + else: + _LOGGER.warning("Discriminator %s is absent or null, use base class %s.", subtype_key, cls.__name__) + break + return cls + + @classmethod + def _get_rest_key_parts(cls, attr_key): + """Get the RestAPI key of this attr, split it and decode part + :param str attr_key: Attribute key must be in attribute_map. + :returns: A list of RestAPI part + :rtype: list + """ + rest_split_key = _FLATTEN.split(cls._attribute_map[attr_key]["key"]) + return [_decode_attribute_map_key(key_part) for key_part in rest_split_key] + + +def _decode_attribute_map_key(key): + """This decode a key in an _attribute_map to the actual key we want to look at + inside the received data. + + :param str key: A key string from the generated code + """ + return key.replace("\\.", ".") + + +class Serializer(object): + """Request object model serializer.""" + + basic_types = {str: "str", int: "int", bool: "bool", float: "float"} + + _xml_basic_types_serializers = {"bool": lambda x: str(x).lower()} + days = {0: "Mon", 1: "Tue", 2: "Wed", 3: "Thu", 4: "Fri", 5: "Sat", 6: "Sun"} + months = { + 1: "Jan", + 2: "Feb", + 3: "Mar", + 4: "Apr", + 5: "May", + 6: "Jun", + 7: "Jul", + 8: "Aug", + 9: "Sep", + 10: "Oct", + 11: "Nov", + 12: "Dec", + } + validation = { + "min_length": lambda x, y: len(x) < y, + "max_length": lambda x, y: len(x) > 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: Optional[Mapping[str, Type[ModelType]]]=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[str, Type[ModelType]] = 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) # type: ignore + continue + if xml_desc.get("text", False): + serialized.text = new_attr # type: ignore + continue + if isinstance(new_attr, list): + serialized.extend(new_attr) # type: ignore + 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) # type: ignore + 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) # type: ignore + else: # JSON + for k in reversed(keys): # type: ignore + new_attr = {k: new_attr} + + _new_attr = new_attr + _serialized = serialized + for k in keys: # type: ignore + if k not in _serialized: + _serialized.update(_new_attr) # type: ignore + _new_attr = _new_attr[k] # type: ignore + _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_str = data_type.strip("[]{}") + internal_data_type = self.dependencies.get(internal_data_type_str, 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 = [ # type: ignore + 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 is AzureCoreNull: + return None + 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): # type: ignore + # 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) # type: ignore + return result + except ValueError: + for enum_value in enum_obj: # type: ignore + 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: + # Need the cast, as for some reasons "split" is typed as list[str | Any] + dict_keys = cast(List[str], _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: Optional[Mapping[str, Type[ModelType]]]=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[str, Type[ModelType]] = 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 # type: ignore + 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 # type: ignore + 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 deserialize. + """ + 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__ # type: ignore + + 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 deserialize. + :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) # type: ignore + 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) # type: ignore + 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): # type: ignore + 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)) # type: ignore + + @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) # type: ignore + attr = attr + padding # type: ignore + 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) # type: ignore + 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) # type: ignore + + @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): # type: ignore + 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): # type: ignore + 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) # type: ignore + 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() # type: ignore + 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) # type: ignore + 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/network/azure-mgmt-dns/azure/mgmt/dns/aio/_configuration.py b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/aio/_configuration.py index 0a84eac865ac..8a53ee0b3c6d 100644 --- a/sdk/network/azure-mgmt-dns/azure/mgmt/dns/aio/_configuration.py +++ b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/aio/_configuration.py @@ -12,7 +12,7 @@ from azure.core.configuration import Configuration from azure.core.pipeline import policies -from azure.mgmt.core.policies import ARMHttpLoggingPolicy +from azure.mgmt.core.policies import ARMHttpLoggingPolicy, AsyncARMChallengeAuthenticationPolicy from .._version import VERSION @@ -26,9 +26,9 @@ class DnsManagementClientConfiguration(Configuration): 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: Specifies the Azure subscription ID, which uniquely identifies the Microsoft Azure subscription. + :param subscription_id: Specifies the Azure subscription ID, which uniquely identifies the Microsoft Azure subscription. Required. :type subscription_id: str """ @@ -36,7 +36,7 @@ def __init__( self, credential: "AsyncTokenCredential", subscription_id: str, - **kwargs # type: Any + **kwargs: Any ) -> None: if credential is None: raise ValueError("Parameter 'credential' must not be None.") @@ -64,4 +64,4 @@ def _configure( self.redirect_policy = kwargs.get('redirect_policy') or policies.AsyncRedirectPolicy(**kwargs) self.authentication_policy = kwargs.get('authentication_policy') if self.credential and not self.authentication_policy: - self.authentication_policy = policies.AsyncBearerTokenCredentialPolicy(self.credential, *self.credential_scopes, **kwargs) + self.authentication_policy = AsyncARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs) diff --git a/sdk/network/azure-mgmt-dns/azure/mgmt/dns/aio/_dns_management_client.py b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/aio/_dns_management_client.py index a45870528b89..0d6e1fb9f864 100644 --- a/sdk/network/azure-mgmt-dns/azure/mgmt/dns/aio/_dns_management_client.py +++ b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/aio/_dns_management_client.py @@ -11,12 +11,11 @@ from typing import Any, Optional, TYPE_CHECKING -from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest from azure.mgmt.core import AsyncARMPipelineClient from azure.profiles import KnownProfiles, ProfileDefinition from azure.profiles.multiapiclient import MultiApiClientMixin -from msrest import Deserializer, Serializer +from .._serialization import Deserializer, Serializer from ._configuration import DnsManagementClientConfiguration if TYPE_CHECKING: @@ -41,9 +40,9 @@ class DnsManagementClient(MultiApiClientMixin, _SDKClient): The api-version parameter sets the default API version if the operation group is not described in the profile. - :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: Specifies the Azure subscription ID, which uniquely identifies the Microsoft Azure subscription. + :param subscription_id: Specifies the Azure subscription ID, which uniquely identifies the Microsoft Azure subscription. Required. :type subscription_id: str :param api_version: API version to use if no profile is provided, or if missing in profile. :type api_version: str @@ -68,12 +67,10 @@ def __init__( credential: "AsyncTokenCredential", subscription_id: str, api_version: Optional[str] = None, - base_url: Optional[str] = None, + base_url: str = "https://management.azure.com", profile: KnownProfiles = KnownProfiles.default, - **kwargs # type: Any + **kwargs: Any ) -> None: - if not base_url: - base_url = 'https://management.azure.com' self._config = DnsManagementClientConfiguration(credential, subscription_id, **kwargs) self._client = AsyncARMPipelineClient(base_url=base_url, config=self._config, **kwargs) super(DnsManagementClient, self).__init__( @@ -115,6 +112,7 @@ def dns_resource_reference(self): from ..v2018_05_01.aio.operations import DnsResourceReferenceOperations as OperationClass else: raise ValueError("API version {} does not have operation group 'dns_resource_reference'".format(api_version)) + self._config.api_version = api_version return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) @property @@ -134,6 +132,7 @@ def record_sets(self): from ..v2018_05_01.aio.operations import RecordSetsOperations as OperationClass else: raise ValueError("API version {} does not have operation group 'record_sets'".format(api_version)) + self._config.api_version = api_version return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) @property @@ -153,6 +152,7 @@ def zones(self): from ..v2018_05_01.aio.operations import ZonesOperations as OperationClass else: raise ValueError("API version {} does not have operation group 'zones'".format(api_version)) + self._config.api_version = api_version return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) async def close(self): diff --git a/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2016_04_01/__init__.py b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2016_04_01/__init__.py index a21e1fdf48bb..23ee0cabde53 100644 --- a/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2016_04_01/__init__.py +++ b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2016_04_01/__init__.py @@ -10,10 +10,17 @@ from ._version import VERSION __version__ = VERSION -__all__ = ['DnsManagementClient'] try: - from ._patch import patch_sdk # type: ignore - patch_sdk() + from ._patch import __all__ as _patch_all + from ._patch import * # pylint: disable=unused-wildcard-import except ImportError: - pass + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "DnsManagementClient", +] +__all__.extend([p for p in _patch_all if p not in __all__]) + +_patch_sdk() diff --git a/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2016_04_01/_configuration.py b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2016_04_01/_configuration.py index 4bbde6c0b319..c9e90d5fe9e0 100644 --- a/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2016_04_01/_configuration.py +++ b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2016_04_01/_configuration.py @@ -6,66 +6,67 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING +import sys +from typing import Any, TYPE_CHECKING from azure.core.configuration import Configuration from azure.core.pipeline import policies -from azure.mgmt.core.policies import ARMHttpLoggingPolicy +from azure.mgmt.core.policies import ARMChallengeAuthenticationPolicy, ARMHttpLoggingPolicy 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 typing import Any - from azure.core.credentials import TokenCredential -class DnsManagementClientConfiguration(Configuration): +class DnsManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes """Configuration for DnsManagementClient. 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 ID of the target subscription. + :param subscription_id: The ID of the target subscription. Required. :type subscription_id: str + :keyword api_version: Api Version. Default value is "2016-04-01". Note that overriding this + default value may result in unsupported behavior. + :paramtype api_version: str """ - def __init__( - self, - credential, # type: "TokenCredential" - subscription_id, # type: str - **kwargs # type: Any - ): - # type: (...) -> None + def __init__(self, credential: "TokenCredential", subscription_id: str, **kwargs: Any) -> None: + super(DnsManagementClientConfiguration, self).__init__(**kwargs) + api_version: Literal["2016-04-01"] = kwargs.pop("api_version", "2016-04-01") + if credential is None: raise ValueError("Parameter 'credential' must not be None.") if subscription_id is None: raise ValueError("Parameter 'subscription_id' must not be None.") - super(DnsManagementClientConfiguration, self).__init__(**kwargs) self.credential = credential self.subscription_id = subscription_id - self.api_version = "2016-04-01" - self.credential_scopes = kwargs.pop('credential_scopes', ['https://management.azure.com/.default']) - kwargs.setdefault('sdk_moniker', 'mgmt-dns/{}'.format(VERSION)) + self.api_version = api_version + self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "mgmt-dns/{}".format(VERSION)) self._configure(**kwargs) - def _configure( - self, - **kwargs # type: Any - ): - # type: (...) -> None - self.user_agent_policy = kwargs.get('user_agent_policy') or policies.UserAgentPolicy(**kwargs) - self.headers_policy = kwargs.get('headers_policy') or policies.HeadersPolicy(**kwargs) - self.proxy_policy = kwargs.get('proxy_policy') or policies.ProxyPolicy(**kwargs) - self.logging_policy = kwargs.get('logging_policy') or policies.NetworkTraceLoggingPolicy(**kwargs) - self.http_logging_policy = kwargs.get('http_logging_policy') or ARMHttpLoggingPolicy(**kwargs) - self.retry_policy = kwargs.get('retry_policy') or policies.RetryPolicy(**kwargs) - self.custom_hook_policy = kwargs.get('custom_hook_policy') or policies.CustomHookPolicy(**kwargs) - self.redirect_policy = kwargs.get('redirect_policy') or policies.RedirectPolicy(**kwargs) - self.authentication_policy = kwargs.get('authentication_policy') + def _configure(self, **kwargs: Any) -> None: + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.RetryPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.RedirectPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") if self.credential and not self.authentication_policy: - self.authentication_policy = policies.BearerTokenCredentialPolicy(self.credential, *self.credential_scopes, **kwargs) + self.authentication_policy = ARMChallengeAuthenticationPolicy( + self.credential, *self.credential_scopes, **kwargs + ) diff --git a/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2016_04_01/_dns_management_client.py b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2016_04_01/_dns_management_client.py index 029bb1d755f7..d098dc9e7154 100644 --- a/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2016_04_01/_dns_management_client.py +++ b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2016_04_01/_dns_management_client.py @@ -6,89 +6,89 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING +from copy import deepcopy +from typing import Any, TYPE_CHECKING +from azure.core.rest import HttpRequest, HttpResponse from azure.mgmt.core import ARMPipelineClient -from msrest import Deserializer, Serializer + +from . import models as _models +from .._serialization import Deserializer, Serializer +from ._configuration import DnsManagementClientConfiguration +from .operations import RecordSetsOperations, ZonesOperations if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Optional - from azure.core.credentials import TokenCredential - from azure.core.pipeline.transport import HttpRequest, HttpResponse - -from ._configuration import DnsManagementClientConfiguration -from .operations import RecordSetsOperations -from .operations import ZonesOperations -from . import models -class DnsManagementClient(object): +class DnsManagementClient: # pylint: disable=client-accepts-api-version-keyword """The DNS Management Client. :ivar record_sets: RecordSetsOperations operations :vartype record_sets: azure.mgmt.dns.v2016_04_01.operations.RecordSetsOperations :ivar zones: ZonesOperations operations :vartype zones: azure.mgmt.dns.v2016_04_01.operations.ZonesOperations - :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 ID of the target subscription. + :param subscription_id: The ID of the target subscription. Required. :type subscription_id: str - :param str base_url: Service URL - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :param base_url: Service URL. Default value is "https://management.azure.com". + :type base_url: str + :keyword api_version: Api Version. Default value is "2016-04-01". Note that overriding this + default value may result in unsupported behavior. + :paramtype api_version: str + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. """ def __init__( self, - credential, # type: "TokenCredential" - subscription_id, # type: str - base_url=None, # type: Optional[str] - **kwargs # type: Any - ): - # type: (...) -> None - if not base_url: - base_url = 'https://management.azure.com' - self._config = DnsManagementClientConfiguration(credential, subscription_id, **kwargs) + credential: "TokenCredential", + subscription_id: str, + base_url: str = "https://management.azure.com", + **kwargs: Any + ) -> None: + self._config = DnsManagementClientConfiguration( + 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)} + client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)} self._serialize = Serializer(client_models) - self._serialize.client_side_validation = False self._deserialize = Deserializer(client_models) + self._serialize.client_side_validation = False + self.record_sets = RecordSetsOperations(self._client, self._config, self._serialize, self._deserialize) + self.zones = ZonesOperations(self._client, self._config, self._serialize, self._deserialize) - self.record_sets = RecordSetsOperations( - self._client, self._config, self._serialize, self._deserialize) - self.zones = ZonesOperations( - self._client, self._config, self._serialize, self._deserialize) - - def _send_request(self, http_request, **kwargs): - # type: (HttpRequest, Any) -> HttpResponse + def _send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: """Runs the network request through the client's chained policies. - :param http_request: The network request you want to make. Required. - :type http_request: ~azure.core.pipeline.transport.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to True. + >>> from azure.core.rest import HttpRequest + >>> request = HttpRequest("GET", "https://www.example.org/") + + >>> response = client._send_request(request) + + + For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request + + :param request: The network request you want to make. Required. + :type request: ~azure.core.rest.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to False. :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.pipeline.transport.HttpResponse + :rtype: ~azure.core.rest.HttpResponse """ - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), - } - http_request.url = self._client.format_url(http_request.url, **path_format_arguments) - stream = kwargs.pop("stream", True) - pipeline_response = self._client._pipeline.run(http_request, stream=stream, **kwargs) - return pipeline_response.http_response - - def close(self): - # type: () -> None + + request_copy = deepcopy(request) + request_copy.url = self._client.format_url(request_copy.url) + return self._client.send_request(request_copy, **kwargs) + + def close(self) -> None: self._client.close() - def __enter__(self): - # type: () -> DnsManagementClient + def __enter__(self) -> "DnsManagementClient": self._client.__enter__() return self - def __exit__(self, *exc_details): - # type: (Any) -> None + def __exit__(self, *exc_details: Any) -> None: self._client.__exit__(*exc_details) diff --git a/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2016_04_01/_metadata.json b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2016_04_01/_metadata.json index 851a947eeb48..98d2f164abbc 100644 --- a/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2016_04_01/_metadata.json +++ b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2016_04_01/_metadata.json @@ -5,39 +5,41 @@ "name": "DnsManagementClient", "filename": "_dns_management_client", "description": "The DNS Management Client.", - "base_url": "\u0027https://management.azure.com\u0027", - "custom_base_url": null, + "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\"], \"msrest\": [\"Deserializer\", \"Serializer\"], \"azure.mgmt.core\": [\"ARMPipelineClient\"]}, \"local\": {\"._configuration\": [\"DnsManagementClientConfiguration\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}, \"azurecore\": {\"azure.core.pipeline.transport\": [\"HttpRequest\", \"HttpResponse\"]}}}", - "async_imports": "{\"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}, \"regular\": {\"azurecore\": {\"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"], \"msrest\": [\"Deserializer\", \"Serializer\"], \"azure.mgmt.core\": [\"AsyncARMPipelineClient\"]}, \"local\": {\"._configuration\": [\"DnsManagementClientConfiguration\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}, \"azurecore\": {\"azure.core.pipeline.transport\": [\"AsyncHttpResponse\", \"HttpRequest\"]}}}" + "sync_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"azurecore\": {\"azure.mgmt.core\": [\"ARMPipelineClient\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"DnsManagementClientConfiguration\"], \".._serialization\": [\"Deserializer\", \"Serializer\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", + "async_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"azurecore\": {\"azure.mgmt.core\": [\"AsyncARMPipelineClient\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"DnsManagementClientConfiguration\"], \"..._serialization\": [\"Deserializer\", \"Serializer\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" }, "global_parameters": { "sync": { "credential": { - "signature": "credential, # type: \"TokenCredential\"", - "description": "Credential needed for the client to connect to Azure.", + "signature": "credential: \"TokenCredential\",", + "description": "Credential needed for the client to connect to Azure. Required.", "docstring_type": "~azure.core.credentials.TokenCredential", - "required": true + "required": true, + "method_location": "positional" }, "subscription_id": { - "signature": "subscription_id, # type: str", - "description": "The ID of the target subscription.", + "signature": "subscription_id: str,", + "description": "The ID of the target subscription. Required.", "docstring_type": "str", - "required": true + "required": true, + "method_location": "positional" } }, "async": { "credential": { "signature": "credential: \"AsyncTokenCredential\",", - "description": "Credential needed for the client to connect to Azure.", + "description": "Credential needed for the client to connect to Azure. Required.", "docstring_type": "~azure.core.credentials_async.AsyncTokenCredential", "required": true }, "subscription_id": { "signature": "subscription_id: str,", - "description": "The ID of the target subscription.", + "description": "The ID of the target subscription. Required.", "docstring_type": "str", "required": true } @@ -48,22 +50,25 @@ "service_client_specific": { "sync": { "api_version": { - "signature": "api_version=None, # type: Optional[str]", + "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 + "required": false, + "method_location": "positional" }, "base_url": { - "signature": "base_url=None, # type: Optional[str]", + "signature": "base_url: str = \"https://management.azure.com\",", "description": "Service URL", "docstring_type": "str", - "required": false + "required": false, + "method_location": "positional" }, "profile": { - "signature": "profile=KnownProfiles.default, # type: KnownProfiles", + "signature": "profile: KnownProfiles=KnownProfiles.default,", "description": "A profile definition, from KnownProfiles to dict.", "docstring_type": "azure.profiles.KnownProfiles", - "required": false + "required": false, + "method_location": "positional" } }, "async": { @@ -71,19 +76,22 @@ "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 + "required": false, + "method_location": "positional" }, "base_url": { - "signature": "base_url: Optional[str] = None,", + "signature": "base_url: str = \"https://management.azure.com\",", "description": "Service URL", "docstring_type": "str", - "required": false + "required": false, + "method_location": "positional" }, "profile": { "signature": "profile: KnownProfiles = KnownProfiles.default,", "description": "A profile definition, from KnownProfiles to dict.", "docstring_type": "azure.profiles.KnownProfiles", - "required": false + "required": false, + "method_location": "positional" } } } @@ -91,14 +99,13 @@ "config": { "credential": true, "credential_scopes": ["https://management.azure.com/.default"], - "credential_default_policy_type": "BearerTokenCredentialPolicy", - "credential_default_policy_type_has_async_version": true, - "credential_key_header_name": null, - "sync_imports": "{\"regular\": {\"azurecore\": {\"azure.core.configuration\": [\"Configuration\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"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\"]}, \"local\": {\".._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" + "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": { "record_sets": "RecordSetsOperations", "zones": "ZonesOperations" } -} \ No newline at end of file +} diff --git a/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2016_04_01/_patch.py b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2016_04_01/_patch.py new file mode 100644 index 000000000000..f7dd32510333 --- /dev/null +++ b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2016_04_01/_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/network/azure-mgmt-dns/azure/mgmt/dns/v2016_04_01/_vendor.py b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2016_04_01/_vendor.py new file mode 100644 index 000000000000..bd0df84f5319 --- /dev/null +++ b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2016_04_01/_vendor.py @@ -0,0 +1,30 @@ +# -------------------------------------------------------------------------- +# 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 typing import List, cast + +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) + if files: + request.set_formdata_body(files) + return request + + +def _format_url_section(template, **kwargs): + components = template.split("/") + while components: + try: + return template.format(**kwargs) + except KeyError as key: + # Need the cast, as for some reasons "split" is typed as list[str | Any] + formatted_components = cast(List[str], template.split("/")) + components = [c for c in formatted_components if "{}".format(key.args[0]) not in c] + template = "/".join(components) diff --git a/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2016_04_01/_version.py b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2016_04_01/_version.py index 142a0420b39b..e5754a47ce68 100644 --- a/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2016_04_01/_version.py +++ b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2016_04_01/_version.py @@ -6,4 +6,4 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -VERSION = "8.0.0" +VERSION = "1.0.0b1" diff --git a/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2016_04_01/aio/__init__.py b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2016_04_01/aio/__init__.py index 1a93fabcef86..e94042023e78 100644 --- a/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2016_04_01/aio/__init__.py +++ b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2016_04_01/aio/__init__.py @@ -7,4 +7,17 @@ # -------------------------------------------------------------------------- from ._dns_management_client import DnsManagementClient -__all__ = ['DnsManagementClient'] + +try: + from ._patch import __all__ as _patch_all + from ._patch import * # pylint: disable=unused-wildcard-import +except ImportError: + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "DnsManagementClient", +] +__all__.extend([p for p in _patch_all if p not in __all__]) + +_patch_sdk() diff --git a/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2016_04_01/aio/_configuration.py b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2016_04_01/aio/_configuration.py index 819efcdcdc67..dc869414a604 100644 --- a/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2016_04_01/aio/_configuration.py +++ b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2016_04_01/aio/_configuration.py @@ -6,62 +6,67 @@ # 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 from azure.core.pipeline import policies -from azure.mgmt.core.policies import ARMHttpLoggingPolicy +from azure.mgmt.core.policies import ARMHttpLoggingPolicy, AsyncARMChallengeAuthenticationPolicy 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 -class DnsManagementClientConfiguration(Configuration): +class DnsManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes """Configuration for DnsManagementClient. 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 ID of the target subscription. + :param subscription_id: The ID of the target subscription. Required. :type subscription_id: str + :keyword api_version: Api Version. Default value is "2016-04-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(DnsManagementClientConfiguration, self).__init__(**kwargs) + api_version: Literal["2016-04-01"] = kwargs.pop("api_version", "2016-04-01") + if credential is None: raise ValueError("Parameter 'credential' must not be None.") if subscription_id is None: raise ValueError("Parameter 'subscription_id' must not be None.") - super(DnsManagementClientConfiguration, self).__init__(**kwargs) self.credential = credential self.subscription_id = subscription_id - self.api_version = "2016-04-01" - self.credential_scopes = kwargs.pop('credential_scopes', ['https://management.azure.com/.default']) - kwargs.setdefault('sdk_moniker', 'mgmt-dns/{}'.format(VERSION)) + self.api_version = api_version + self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "mgmt-dns/{}".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 = policies.AsyncBearerTokenCredentialPolicy(self.credential, *self.credential_scopes, **kwargs) + self.authentication_policy = AsyncARMChallengeAuthenticationPolicy( + self.credential, *self.credential_scopes, **kwargs + ) diff --git a/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2016_04_01/aio/_dns_management_client.py b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2016_04_01/aio/_dns_management_client.py index bcad725200ac..2d5bf393265c 100644 --- a/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2016_04_01/aio/_dns_management_client.py +++ b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2016_04_01/aio/_dns_management_client.py @@ -6,75 +6,82 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, Optional, TYPE_CHECKING +from copy import deepcopy +from typing import Any, Awaitable, TYPE_CHECKING -from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.rest import AsyncHttpResponse, HttpRequest from azure.mgmt.core import AsyncARMPipelineClient -from msrest import Deserializer, Serializer + +from .. import models as _models +from ..._serialization import Deserializer, Serializer +from ._configuration import DnsManagementClientConfiguration +from .operations import RecordSetsOperations, ZonesOperations if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential -from ._configuration import DnsManagementClientConfiguration -from .operations import RecordSetsOperations -from .operations import ZonesOperations -from .. import models - -class DnsManagementClient(object): +class DnsManagementClient: # pylint: disable=client-accepts-api-version-keyword """The DNS Management Client. :ivar record_sets: RecordSetsOperations operations :vartype record_sets: azure.mgmt.dns.v2016_04_01.aio.operations.RecordSetsOperations :ivar zones: ZonesOperations operations :vartype zones: azure.mgmt.dns.v2016_04_01.aio.operations.ZonesOperations - :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 ID of the target subscription. + :param subscription_id: The ID of the target subscription. Required. :type subscription_id: str - :param str base_url: Service URL - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :param base_url: Service URL. Default value is "https://management.azure.com". + :type base_url: str + :keyword api_version: Api Version. Default value is "2016-04-01". Note that overriding this + default value may result in unsupported behavior. + :paramtype api_version: str + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. """ def __init__( self, credential: "AsyncTokenCredential", subscription_id: str, - base_url: Optional[str] = None, + base_url: str = "https://management.azure.com", **kwargs: Any ) -> None: - if not base_url: - base_url = 'https://management.azure.com' - self._config = DnsManagementClientConfiguration(credential, subscription_id, **kwargs) + self._config = DnsManagementClientConfiguration( + 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)} + client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)} self._serialize = Serializer(client_models) - self._serialize.client_side_validation = False self._deserialize = Deserializer(client_models) + self._serialize.client_side_validation = False + self.record_sets = RecordSetsOperations(self._client, self._config, self._serialize, self._deserialize) + self.zones = ZonesOperations(self._client, self._config, self._serialize, self._deserialize) - self.record_sets = RecordSetsOperations( - self._client, self._config, self._serialize, self._deserialize) - self.zones = ZonesOperations( - self._client, self._config, self._serialize, self._deserialize) - - async def _send_request(self, http_request: HttpRequest, **kwargs: Any) -> AsyncHttpResponse: + def _send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]: """Runs the network request through the client's chained policies. - :param http_request: The network request you want to make. Required. - :type http_request: ~azure.core.pipeline.transport.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to True. + >>> from azure.core.rest import HttpRequest + >>> request = HttpRequest("GET", "https://www.example.org/") + + >>> response = await client._send_request(request) + + + For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request + + :param request: The network request you want to make. Required. + :type request: ~azure.core.rest.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to False. :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.pipeline.transport.AsyncHttpResponse + :rtype: ~azure.core.rest.AsyncHttpResponse """ - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), - } - http_request.url = self._client.format_url(http_request.url, **path_format_arguments) - stream = kwargs.pop("stream", True) - pipeline_response = await self._client._pipeline.run(http_request, stream=stream, **kwargs) - return pipeline_response.http_response + + request_copy = deepcopy(request) + request_copy.url = self._client.format_url(request_copy.url) + return self._client.send_request(request_copy, **kwargs) async def close(self) -> None: await self._client.close() @@ -83,5 +90,5 @@ async def __aenter__(self) -> "DnsManagementClient": await self._client.__aenter__() return self - async def __aexit__(self, *exc_details) -> None: + async def __aexit__(self, *exc_details: Any) -> None: await self._client.__aexit__(*exc_details) diff --git a/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2016_04_01/aio/_patch.py b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2016_04_01/aio/_patch.py new file mode 100644 index 000000000000..f7dd32510333 --- /dev/null +++ b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2016_04_01/aio/_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/network/azure-mgmt-dns/azure/mgmt/dns/v2016_04_01/aio/operations/__init__.py b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2016_04_01/aio/operations/__init__.py index caab83d882c4..c12bcc6610ed 100644 --- a/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2016_04_01/aio/operations/__init__.py +++ b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2016_04_01/aio/operations/__init__.py @@ -9,7 +9,13 @@ from ._record_sets_operations import RecordSetsOperations from ._zones_operations import ZonesOperations +from ._patch import __all__ as _patch_all +from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import patch_sdk as _patch_sdk + __all__ = [ - 'RecordSetsOperations', - 'ZonesOperations', + "RecordSetsOperations", + "ZonesOperations", ] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2016_04_01/aio/operations/_patch.py b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2016_04_01/aio/operations/_patch.py new file mode 100644 index 000000000000..f7dd32510333 --- /dev/null +++ b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2016_04_01/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/network/azure-mgmt-dns/azure/mgmt/dns/v2016_04_01/aio/operations/_record_sets_operations.py b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2016_04_01/aio/operations/_record_sets_operations.py index 4fbf21039d25..ae612448b878 100644 --- a/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2016_04_01/aio/operations/_record_sets_operations.py +++ b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2016_04_01/aio/operations/_record_sets_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,197 +6,430 @@ # 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, Generic, Optional, TypeVar, Union -import warnings +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, HttpRequest +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 - -T = TypeVar('T') +from ..._vendor import _convert_request +from ...operations._record_sets_operations import ( + build_create_or_update_request, + build_delete_request, + build_get_request, + build_list_by_dns_zone_request, + build_list_by_type_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 RecordSetsOperations: - """RecordSetsOperations 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 RecordSetsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.dns.v2016_04_01.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.dns.v2016_04_01.aio.DnsManagementClient`'s + :attr:`record_sets` 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") + @overload async def update( self, resource_group_name: str, zone_name: str, relative_record_set_name: str, - record_type: Union[str, "_models.RecordType"], - parameters: "_models.RecordSet", + record_type: Union[str, _models.RecordType], + parameters: _models.RecordSet, if_match: Optional[str] = None, - **kwargs - ) -> "_models.RecordSet": + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RecordSet: """Updates a record set within a DNS zone. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param zone_name: The name of the DNS zone (without a terminating dot). + :param zone_name: The name of the DNS zone (without a terminating dot). Required. :type zone_name: str :param relative_record_set_name: The name of the record set, relative to the name of the zone. + Required. :type relative_record_set_name: str - :param record_type: The type of DNS record in this record set. + :param record_type: The type of DNS record in this record set. Known values are: "A", "AAAA", + "CNAME", "MX", "NS", "PTR", "SOA", "SRV", and "TXT". Required. :type record_type: str or ~azure.mgmt.dns.v2016_04_01.models.RecordType - :param parameters: Parameters supplied to the Update operation. + :param parameters: Parameters supplied to the Update operation. Required. :type parameters: ~azure.mgmt.dns.v2016_04_01.models.RecordSet :param if_match: The etag of the record set. Omit this value to always overwrite the current record set. Specify the last-seen etag value to prevent accidentally overwriting concurrent - changes. + changes. 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: RecordSet or the result of cls(response) + :rtype: ~azure.mgmt.dns.v2016_04_01.models.RecordSet + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def update( + self, + resource_group_name: str, + zone_name: str, + relative_record_set_name: str, + record_type: Union[str, _models.RecordType], + parameters: IO, + if_match: Optional[str] = None, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RecordSet: + """Updates a record set within a DNS zone. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param zone_name: The name of the DNS zone (without a terminating dot). Required. + :type zone_name: str + :param relative_record_set_name: The name of the record set, relative to the name of the zone. + Required. + :type relative_record_set_name: str + :param record_type: The type of DNS record in this record set. Known values are: "A", "AAAA", + "CNAME", "MX", "NS", "PTR", "SOA", "SRV", and "TXT". Required. + :type record_type: str or ~azure.mgmt.dns.v2016_04_01.models.RecordType + :param parameters: Parameters supplied to the Update operation. Required. + :type parameters: IO + :param if_match: The etag of the record set. Omit this value to always overwrite the current + record set. Specify the last-seen etag value to prevent accidentally overwriting concurrent + changes. 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: RecordSet, or the result of cls(response) + :return: RecordSet or the result of cls(response) :rtype: ~azure.mgmt.dns.v2016_04_01.models.RecordSet - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def update( + self, + resource_group_name: str, + zone_name: str, + relative_record_set_name: str, + record_type: Union[str, _models.RecordType], + parameters: Union[_models.RecordSet, IO], + if_match: Optional[str] = None, + **kwargs: Any + ) -> _models.RecordSet: + """Updates a record set within a DNS zone. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param zone_name: The name of the DNS zone (without a terminating dot). Required. + :type zone_name: str + :param relative_record_set_name: The name of the record set, relative to the name of the zone. + Required. + :type relative_record_set_name: str + :param record_type: The type of DNS record in this record set. Known values are: "A", "AAAA", + "CNAME", "MX", "NS", "PTR", "SOA", "SRV", and "TXT". Required. + :type record_type: str or ~azure.mgmt.dns.v2016_04_01.models.RecordType + :param parameters: Parameters supplied to the Update operation. Is either a RecordSet type or a + IO type. Required. + :type parameters: ~azure.mgmt.dns.v2016_04_01.models.RecordSet or IO + :param if_match: The etag of the record set. Omit this value to always overwrite the current + record set. Specify the last-seen etag value to prevent accidentally overwriting concurrent + changes. 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: RecordSet or the result of cls(response) + :rtype: ~azure.mgmt.dns.v2016_04_01.models.RecordSet + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RecordSet"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2016-04-01" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.update.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), - 'zoneName': self._serialize.url("zone_name", zone_name, 'str'), - 'relativeRecordSetName': self._serialize.url("relative_record_set_name", relative_record_set_name, 'str', skip_quote=True), - 'recordType': self._serialize.url("record_type", record_type, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - if if_match is not None: - header_parameters['If-Match'] = self._serialize.header("if_match", if_match, 'str') - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(parameters, 'RecordSet') - body_content_kwargs['content'] = body_content - request = self._client.patch(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + 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: Literal["2016-04-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-04-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.RecordSet] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "RecordSet") + + request = build_update_request( + resource_group_name=resource_group_name, + zone_name=zone_name, + relative_record_set_name=relative_record_set_name, + record_type=record_type, + subscription_id=self._config.subscription_id, + if_match=if_match, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.update.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = 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('RecordSet', pipeline_response) + deserialized = self._deserialize("RecordSet", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}/{recordType}/{relativeRecordSetName}'} # type: ignore + update.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}/{recordType}/{relativeRecordSetName}" + } + + @overload async def create_or_update( self, resource_group_name: str, zone_name: str, relative_record_set_name: str, - record_type: Union[str, "_models.RecordType"], - parameters: "_models.RecordSet", + record_type: Union[str, _models.RecordType], + parameters: _models.RecordSet, if_match: Optional[str] = None, if_none_match: Optional[str] = None, - **kwargs - ) -> "_models.RecordSet": + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RecordSet: """Creates or updates a record set within a DNS zone. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param zone_name: The name of the DNS zone (without a terminating dot). + :param zone_name: The name of the DNS zone (without a terminating dot). Required. :type zone_name: str :param relative_record_set_name: The name of the record set, relative to the name of the zone. + Required. :type relative_record_set_name: str :param record_type: The type of DNS record in this record set. Record sets of type SOA can be - updated but not created (they are created when the DNS zone is created). + updated but not created (they are created when the DNS zone is created). Known values are: "A", + "AAAA", "CNAME", "MX", "NS", "PTR", "SOA", "SRV", and "TXT". Required. :type record_type: str or ~azure.mgmt.dns.v2016_04_01.models.RecordType - :param parameters: Parameters supplied to the CreateOrUpdate operation. + :param parameters: Parameters supplied to the CreateOrUpdate operation. Required. :type parameters: ~azure.mgmt.dns.v2016_04_01.models.RecordSet :param if_match: The etag of the record set. Omit this value to always overwrite the current record set. Specify the last-seen etag value to prevent accidentally overwriting any concurrent - changes. + changes. Default value is None. :type if_match: str :param if_none_match: Set to '*' to allow a new record set to be created, but to prevent - updating an existing record set. Other values will be ignored. + updating an existing record set. 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: RecordSet, or the result of cls(response) + :return: RecordSet or the result of cls(response) :rtype: ~azure.mgmt.dns.v2016_04_01.models.RecordSet - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_or_update( + self, + resource_group_name: str, + zone_name: str, + relative_record_set_name: str, + record_type: Union[str, _models.RecordType], + parameters: IO, + if_match: Optional[str] = None, + if_none_match: Optional[str] = None, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RecordSet: + """Creates or updates a record set within a DNS zone. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param zone_name: The name of the DNS zone (without a terminating dot). Required. + :type zone_name: str + :param relative_record_set_name: The name of the record set, relative to the name of the zone. + Required. + :type relative_record_set_name: str + :param record_type: The type of DNS record in this record set. Record sets of type SOA can be + updated but not created (they are created when the DNS zone is created). Known values are: "A", + "AAAA", "CNAME", "MX", "NS", "PTR", "SOA", "SRV", and "TXT". Required. + :type record_type: str or ~azure.mgmt.dns.v2016_04_01.models.RecordType + :param parameters: Parameters supplied to the CreateOrUpdate operation. Required. + :type parameters: IO + :param if_match: The etag of the record set. Omit this value to always overwrite the current + record set. Specify the last-seen etag value to prevent accidentally overwriting any concurrent + changes. Default value is None. + :type if_match: str + :param if_none_match: Set to '*' to allow a new record set to be created, but to prevent + updating an existing record set. 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: RecordSet or the result of cls(response) + :rtype: ~azure.mgmt.dns.v2016_04_01.models.RecordSet + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create_or_update( + self, + resource_group_name: str, + zone_name: str, + relative_record_set_name: str, + record_type: Union[str, _models.RecordType], + parameters: Union[_models.RecordSet, IO], + if_match: Optional[str] = None, + if_none_match: Optional[str] = None, + **kwargs: Any + ) -> _models.RecordSet: + """Creates or updates a record set within a DNS zone. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param zone_name: The name of the DNS zone (without a terminating dot). Required. + :type zone_name: str + :param relative_record_set_name: The name of the record set, relative to the name of the zone. + Required. + :type relative_record_set_name: str + :param record_type: The type of DNS record in this record set. Record sets of type SOA can be + updated but not created (they are created when the DNS zone is created). Known values are: "A", + "AAAA", "CNAME", "MX", "NS", "PTR", "SOA", "SRV", and "TXT". Required. + :type record_type: str or ~azure.mgmt.dns.v2016_04_01.models.RecordType + :param parameters: Parameters supplied to the CreateOrUpdate operation. Is either a RecordSet + type or a IO type. Required. + :type parameters: ~azure.mgmt.dns.v2016_04_01.models.RecordSet or IO + :param if_match: The etag of the record set. Omit this value to always overwrite the current + record set. Specify the last-seen etag value to prevent accidentally overwriting any concurrent + changes. Default value is None. + :type if_match: str + :param if_none_match: Set to '*' to allow a new record set to be created, but to prevent + updating an existing record set. 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: RecordSet or the result of cls(response) + :rtype: ~azure.mgmt.dns.v2016_04_01.models.RecordSet + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RecordSet"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2016-04-01" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.create_or_update.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), - 'zoneName': self._serialize.url("zone_name", zone_name, 'str'), - 'relativeRecordSetName': self._serialize.url("relative_record_set_name", relative_record_set_name, 'str', skip_quote=True), - 'recordType': self._serialize.url("record_type", record_type, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - if if_match is not None: - header_parameters['If-Match'] = self._serialize.header("if_match", if_match, 'str') - if if_none_match is not None: - header_parameters['If-None-Match'] = self._serialize.header("if_none_match", if_none_match, 'str') - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(parameters, 'RecordSet') - body_content_kwargs['content'] = body_content - request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + 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: Literal["2016-04-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-04-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.RecordSet] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "RecordSet") + + request = build_create_or_update_request( + resource_group_name=resource_group_name, + zone_name=zone_name, + relative_record_set_name=relative_record_set_name, + record_type=record_type, + subscription_id=self._config.subscription_id, + if_match=if_match, + if_none_match=if_none_match, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create_or_update.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response if response.status_code not in [200, 201]: @@ -203,77 +437,86 @@ async def create_or_update( raise HttpResponseError(response=response, error_format=ARMErrorFormat) if response.status_code == 200: - deserialized = self._deserialize('RecordSet', pipeline_response) + deserialized = self._deserialize("RecordSet", pipeline_response) if response.status_code == 201: - deserialized = self._deserialize('RecordSet', pipeline_response) + deserialized = self._deserialize("RecordSet", pipeline_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}/{recordType}/{relativeRecordSetName}'} # type: ignore + return deserialized # type: ignore - async def delete( + create_or_update.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}/{recordType}/{relativeRecordSetName}" + } + + @distributed_trace_async + async def delete( # pylint: disable=inconsistent-return-statements self, resource_group_name: str, zone_name: str, relative_record_set_name: str, - record_type: Union[str, "_models.RecordType"], + record_type: Union[str, _models.RecordType], if_match: Optional[str] = None, - **kwargs + **kwargs: Any ) -> None: """Deletes a record set from a DNS zone. This operation cannot be undone. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param zone_name: The name of the DNS zone (without a terminating dot). + :param zone_name: The name of the DNS zone (without a terminating dot). Required. :type zone_name: str :param relative_record_set_name: The name of the record set, relative to the name of the zone. + Required. :type relative_record_set_name: str :param record_type: The type of DNS record in this record set. Record sets of type SOA cannot - be deleted (they are deleted when the DNS zone is deleted). + be deleted (they are deleted when the DNS zone is deleted). Known values are: "A", "AAAA", + "CNAME", "MX", "NS", "PTR", "SOA", "SRV", and "TXT". Required. :type record_type: str or ~azure.mgmt.dns.v2016_04_01.models.RecordType :param if_match: The etag of the record set. Omit this value to always delete the current record set. Specify the last-seen etag value to prevent accidentally deleting any concurrent - changes. + changes. Default value is None. :type if_match: 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 - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2016-04-01" - accept = "application/json" - - # Construct URL - url = self.delete.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), - 'zoneName': self._serialize.url("zone_name", zone_name, 'str'), - 'relativeRecordSetName': self._serialize.url("relative_record_set_name", relative_record_set_name, 'str', skip_quote=True), - 'recordType': self._serialize.url("record_type", record_type, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-04-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-04-01")) + cls: ClsType[None] = kwargs.pop("cls", None) + + request = build_delete_request( + resource_group_name=resource_group_name, + zone_name=zone_name, + relative_record_set_name=relative_record_set_name, + record_type=record_type, + subscription_id=self._config.subscription_id, + if_match=if_match, + api_version=api_version, + template_url=self.delete.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) - # Construct headers - header_parameters = {} # type: Dict[str, Any] - if if_match is not None: - header_parameters['If-Match'] = self._serialize.header("if_match", if_match, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.delete(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 204]: @@ -283,152 +526,181 @@ async def delete( if cls: return cls(pipeline_response, None, {}) - delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}/{recordType}/{relativeRecordSetName}'} # type: ignore + delete.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}/{recordType}/{relativeRecordSetName}" + } + @distributed_trace_async async def get( self, resource_group_name: str, zone_name: str, relative_record_set_name: str, - record_type: Union[str, "_models.RecordType"], - **kwargs - ) -> "_models.RecordSet": + record_type: Union[str, _models.RecordType], + **kwargs: Any + ) -> _models.RecordSet: """Gets a record set. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param zone_name: The name of the DNS zone (without a terminating dot). + :param zone_name: The name of the DNS zone (without a terminating dot). Required. :type zone_name: str :param relative_record_set_name: The name of the record set, relative to the name of the zone. + Required. :type relative_record_set_name: str - :param record_type: The type of DNS record in this record set. + :param record_type: The type of DNS record in this record set. Known values are: "A", "AAAA", + "CNAME", "MX", "NS", "PTR", "SOA", "SRV", and "TXT". Required. :type record_type: str or ~azure.mgmt.dns.v2016_04_01.models.RecordType :keyword callable cls: A custom type or function that will be passed the direct response - :return: RecordSet, or the result of cls(response) + :return: RecordSet or the result of cls(response) :rtype: ~azure.mgmt.dns.v2016_04_01.models.RecordSet - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RecordSet"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2016-04-01" - accept = "application/json" - - # Construct URL - url = self.get.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), - 'zoneName': self._serialize.url("zone_name", zone_name, 'str'), - 'relativeRecordSetName': self._serialize.url("relative_record_set_name", relative_record_set_name, 'str', skip_quote=True), - 'recordType': self._serialize.url("record_type", record_type, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-04-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-04-01")) + cls: ClsType[_models.RecordSet] = kwargs.pop("cls", None) + + request = build_get_request( + resource_group_name=resource_group_name, + zone_name=zone_name, + relative_record_set_name=relative_record_set_name, + record_type=record_type, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('RecordSet', pipeline_response) + deserialized = self._deserialize("RecordSet", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}/{recordType}/{relativeRecordSetName}'} # type: ignore + get.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}/{recordType}/{relativeRecordSetName}" + } + + @distributed_trace def list_by_type( self, resource_group_name: str, zone_name: str, - record_type: Union[str, "_models.RecordType"], + record_type: Union[str, _models.RecordType], top: Optional[int] = None, recordsetnamesuffix: Optional[str] = None, - **kwargs - ) -> AsyncIterable["_models.RecordSetListResult"]: + **kwargs: Any + ) -> AsyncIterable["_models.RecordSet"]: """Lists the record sets of a specified type in a DNS zone. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param zone_name: The name of the DNS zone (without a terminating dot). + :param zone_name: The name of the DNS zone (without a terminating dot). Required. :type zone_name: str - :param record_type: The type of record sets to enumerate. + :param record_type: The type of record sets to enumerate. Known values are: "A", "AAAA", + "CNAME", "MX", "NS", "PTR", "SOA", "SRV", and "TXT". Required. :type record_type: str or ~azure.mgmt.dns.v2016_04_01.models.RecordType :param top: The maximum number of record sets to return. If not specified, returns up to 100 - record sets. + record sets. Default value is None. :type top: int :param recordsetnamesuffix: The suffix label of the record set name that has to be used to filter the record set enumerations. If this parameter is specified, Enumeration will return - only records that end with .:code:``. + only records that end with .:code:``. Default value is None. :type recordsetnamesuffix: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either RecordSetListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.dns.v2016_04_01.models.RecordSetListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either RecordSet or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.dns.v2016_04_01.models.RecordSet] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RecordSetListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-04-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-04-01")) + cls: ClsType[_models.RecordSetListResult] = kwargs.pop("cls", None) + 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 = "2016-04-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_by_type.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), - 'zoneName': self._serialize.url("zone_name", zone_name, 'str'), - 'recordType': self._serialize.url("record_type", record_type, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - if top is not None: - query_parameters['$top'] = self._serialize.query("top", top, 'int') - if recordsetnamesuffix is not None: - query_parameters['$recordsetnamesuffix'] = self._serialize.query("recordsetnamesuffix", recordsetnamesuffix, 'str') - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_by_type_request( + resource_group_name=resource_group_name, + zone_name=zone_name, + record_type=record_type, + subscription_id=self._config.subscription_id, + top=top, + recordsetnamesuffix=recordsetnamesuffix, + api_version=api_version, + template_url=self.list_by_type.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('RecordSetListResult', pipeline_response) + deserialized = self._deserialize("RecordSetListResult", pipeline_response) list_of_elem = deserialized.value if cls: - list_of_elem = cls(list_of_elem) + list_of_elem = cls(list_of_elem) # type: ignore return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: @@ -437,85 +709,102 @@ async def get_next(next_link=None): return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list_by_type.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}/{recordType}'} # type: ignore + return AsyncItemPaged(get_next, extract_data) + list_by_type.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}/{recordType}" + } + + @distributed_trace def list_by_dns_zone( self, resource_group_name: str, zone_name: str, top: Optional[int] = None, recordsetnamesuffix: Optional[str] = None, - **kwargs - ) -> AsyncIterable["_models.RecordSetListResult"]: + **kwargs: Any + ) -> AsyncIterable["_models.RecordSet"]: """Lists all record sets in a DNS zone. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param zone_name: The name of the DNS zone (without a terminating dot). + :param zone_name: The name of the DNS zone (without a terminating dot). Required. :type zone_name: str :param top: The maximum number of record sets to return. If not specified, returns up to 100 - record sets. + record sets. Default value is None. :type top: int :param recordsetnamesuffix: The suffix label of the record set name that has to be used to filter the record set enumerations. If this parameter is specified, Enumeration will return - only records that end with .:code:``. + only records that end with .:code:``. Default value is None. :type recordsetnamesuffix: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either RecordSetListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.dns.v2016_04_01.models.RecordSetListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either RecordSet or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.dns.v2016_04_01.models.RecordSet] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RecordSetListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-04-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-04-01")) + cls: ClsType[_models.RecordSetListResult] = kwargs.pop("cls", None) + 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 = "2016-04-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_by_dns_zone.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), - 'zoneName': self._serialize.url("zone_name", zone_name, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - if top is not None: - query_parameters['$top'] = self._serialize.query("top", top, 'int') - if recordsetnamesuffix is not None: - query_parameters['$recordsetnamesuffix'] = self._serialize.query("recordsetnamesuffix", recordsetnamesuffix, 'str') - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_by_dns_zone_request( + resource_group_name=resource_group_name, + zone_name=zone_name, + subscription_id=self._config.subscription_id, + top=top, + recordsetnamesuffix=recordsetnamesuffix, + api_version=api_version, + template_url=self.list_by_dns_zone.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('RecordSetListResult', pipeline_response) + deserialized = self._deserialize("RecordSetListResult", pipeline_response) list_of_elem = deserialized.value if cls: - list_of_elem = cls(list_of_elem) + list_of_elem = cls(list_of_elem) # type: ignore return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: @@ -524,7 +813,8 @@ async def get_next(next_link=None): return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list_by_dns_zone.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}/recordsets'} # type: ignore + return AsyncItemPaged(get_next, extract_data) + + list_by_dns_zone.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}/recordsets" + } diff --git a/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2016_04_01/aio/operations/_zones_operations.py b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2016_04_01/aio/operations/_zones_operations.py index 7bdb708bee0c..203617ac2166 100644 --- a/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2016_04_01/aio/operations/_zones_operations.py +++ b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2016_04_01/aio/operations/_zones_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,109 +6,219 @@ # 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, Generic, Optional, TypeVar, Union -import warnings +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, HttpRequest +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 - -T = TypeVar('T') +from ..._vendor import _convert_request +from ...operations._zones_operations import ( + build_create_or_update_request, + build_delete_request, + build_get_request, + build_list_by_resource_group_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 ZonesOperations: - """ZonesOperations 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 ZonesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.dns.v2016_04_01.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.dns.v2016_04_01.aio.DnsManagementClient`'s + :attr:`zones` 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") + @overload async def create_or_update( self, resource_group_name: str, zone_name: str, - parameters: "_models.Zone", + parameters: _models.Zone, if_match: Optional[str] = None, if_none_match: Optional[str] = None, - **kwargs - ) -> "_models.Zone": + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Zone: """Creates or updates a DNS zone. Does not modify DNS records within the zone. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param zone_name: The name of the DNS zone (without a terminating dot). + :param zone_name: The name of the DNS zone (without a terminating dot). Required. :type zone_name: str - :param parameters: Parameters supplied to the CreateOrUpdate operation. + :param parameters: Parameters supplied to the CreateOrUpdate operation. Required. :type parameters: ~azure.mgmt.dns.v2016_04_01.models.Zone :param if_match: The etag of the DNS zone. Omit this value to always overwrite the current zone. Specify the last-seen etag value to prevent accidentally overwriting any concurrent - changes. + changes. Default value is None. + :type if_match: str + :param if_none_match: Set to '*' to allow a new DNS zone to be created, but to prevent updating + an existing zone. 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: Zone or the result of cls(response) + :rtype: ~azure.mgmt.dns.v2016_04_01.models.Zone + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_or_update( + self, + resource_group_name: str, + zone_name: str, + parameters: IO, + if_match: Optional[str] = None, + if_none_match: Optional[str] = None, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Zone: + """Creates or updates a DNS zone. Does not modify DNS records within the zone. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param zone_name: The name of the DNS zone (without a terminating dot). Required. + :type zone_name: str + :param parameters: Parameters supplied to the CreateOrUpdate operation. Required. + :type parameters: IO + :param if_match: The etag of the DNS zone. Omit this value to always overwrite the current + zone. Specify the last-seen etag value to prevent accidentally overwriting any concurrent + changes. Default value is None. :type if_match: str :param if_none_match: Set to '*' to allow a new DNS zone to be created, but to prevent updating - an existing zone. Other values will be ignored. + an existing zone. 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: Zone, or the result of cls(response) + :return: Zone or the result of cls(response) :rtype: ~azure.mgmt.dns.v2016_04_01.models.Zone - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create_or_update( + self, + resource_group_name: str, + zone_name: str, + parameters: Union[_models.Zone, IO], + if_match: Optional[str] = None, + if_none_match: Optional[str] = None, + **kwargs: Any + ) -> _models.Zone: + """Creates or updates a DNS zone. Does not modify DNS records within the zone. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param zone_name: The name of the DNS zone (without a terminating dot). Required. + :type zone_name: str + :param parameters: Parameters supplied to the CreateOrUpdate operation. Is either a Zone type + or a IO type. Required. + :type parameters: ~azure.mgmt.dns.v2016_04_01.models.Zone or IO + :param if_match: The etag of the DNS zone. Omit this value to always overwrite the current + zone. Specify the last-seen etag value to prevent accidentally overwriting any concurrent + changes. Default value is None. + :type if_match: str + :param if_none_match: Set to '*' to allow a new DNS zone to be created, but to prevent updating + an existing zone. 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: Zone or the result of cls(response) + :rtype: ~azure.mgmt.dns.v2016_04_01.models.Zone + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Zone"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2016-04-01" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.create_or_update.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), - 'zoneName': self._serialize.url("zone_name", zone_name, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - if if_match is not None: - header_parameters['If-Match'] = self._serialize.header("if_match", if_match, 'str') - if if_none_match is not None: - header_parameters['If-None-Match'] = self._serialize.header("if_none_match", if_none_match, 'str') - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(parameters, 'Zone') - body_content_kwargs['content'] = body_content - request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + 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: Literal["2016-04-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-04-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.Zone] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "Zone") + + request = build_create_or_update_request( + resource_group_name=resource_group_name, + zone_name=zone_name, + subscription_id=self._config.subscription_id, + if_match=if_match, + if_none_match=if_none_match, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create_or_update.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response if response.status_code not in [200, 201]: @@ -115,53 +226,54 @@ async def create_or_update( raise HttpResponseError(response=response, error_format=ARMErrorFormat) if response.status_code == 200: - deserialized = self._deserialize('Zone', pipeline_response) + deserialized = self._deserialize("Zone", pipeline_response) if response.status_code == 201: - deserialized = self._deserialize('Zone', pipeline_response) + deserialized = self._deserialize("Zone", pipeline_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}'} # type: ignore + return deserialized # type: ignore + + create_or_update.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}" + } async def _delete_initial( - self, - resource_group_name: str, - zone_name: str, - if_match: Optional[str] = None, - **kwargs - ) -> Optional["_models.ZoneDeleteResult"]: - cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.ZoneDeleteResult"]] + self, resource_group_name: str, zone_name: str, if_match: Optional[str] = None, **kwargs: Any + ) -> Optional[_models.ZoneDeleteResult]: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2016-04-01" - accept = "application/json" - - # Construct URL - url = self._delete_initial.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), - 'zoneName': self._serialize.url("zone_name", zone_name, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-04-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-04-01")) + cls: ClsType[Optional[_models.ZoneDeleteResult]] = kwargs.pop("cls", None) + + request = build_delete_request( + resource_group_name=resource_group_name, + zone_name=zone_name, + subscription_id=self._config.subscription_id, + if_match=if_match, + api_version=api_version, + template_url=self._delete_initial.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) - # Construct headers - header_parameters = {} # type: Dict[str, Any] - if if_match is not None: - header_parameters['If-Match'] = self._serialize.header("if_match", if_match, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.delete(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: @@ -170,208 +282,230 @@ async def _delete_initial( deserialized = None if response.status_code == 200: - deserialized = self._deserialize('ZoneDeleteResult', pipeline_response) + deserialized = self._deserialize("ZoneDeleteResult", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - _delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}'} # type: ignore + _delete_initial.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}" + } + + @distributed_trace_async async def begin_delete( - self, - resource_group_name: str, - zone_name: str, - if_match: Optional[str] = None, - **kwargs - ) -> AsyncLROPoller["_models.ZoneDeleteResult"]: + self, resource_group_name: str, zone_name: str, if_match: Optional[str] = None, **kwargs: Any + ) -> AsyncLROPoller[_models.ZoneDeleteResult]: """Deletes a DNS zone. WARNING: All DNS records in the zone will also be deleted. This operation cannot be undone. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param zone_name: The name of the DNS zone (without a terminating dot). + :param zone_name: The name of the DNS zone (without a terminating dot). Required. :type zone_name: str :param if_match: The etag of the DNS zone. Omit this value to always delete the current zone. Specify the last-seen etag value to prevent accidentally deleting any concurrent changes. + Default value is None. :type if_match: 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: Pass in True if you'd like the AsyncARMPolling polling method, - False for no polling, or your own initialized polling object for a personal polling strategy. + :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 ZoneDeleteResult or the result of cls(response) + :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 ZoneDeleteResult or the result of + cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.dns.v2016_04_01.models.ZoneDeleteResult] :raises ~azure.core.exceptions.HttpResponseError: """ - polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType["_models.ZoneDeleteResult"] - 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: Literal["2016-04-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-04-01")) + cls: ClsType[_models.ZoneDeleteResult] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) if cont_token is None: raw_result = await self._delete_initial( resource_group_name=resource_group_name, zone_name=zone_name, if_match=if_match, - cls=lambda x,y,z: x, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - - kwargs.pop('error_map', None) - kwargs.pop('content_type', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - deserialized = self._deserialize('ZoneDeleteResult', pipeline_response) - + deserialized = self._deserialize("ZoneDeleteResult", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - path_format_arguments = { - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), - 'zoneName': self._serialize.url("zone_name", zone_name, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), - } - - if polling is True: polling_method = AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) - elif polling is False: polling_method = AsyncNoPolling() - else: polling_method = polling + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - else: - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}'} # type: ignore + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - async def get( - self, - resource_group_name: str, - zone_name: str, - **kwargs - ) -> "_models.Zone": + begin_delete.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}" + } + + @distributed_trace_async + async def get(self, resource_group_name: str, zone_name: str, **kwargs: Any) -> _models.Zone: """Gets a DNS zone. Retrieves the zone properties, but not the record sets within the zone. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param zone_name: The name of the DNS zone (without a terminating dot). + :param zone_name: The name of the DNS zone (without a terminating dot). Required. :type zone_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: Zone, or the result of cls(response) + :return: Zone or the result of cls(response) :rtype: ~azure.mgmt.dns.v2016_04_01.models.Zone - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Zone"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2016-04-01" - accept = "application/json" - - # Construct URL - url = self.get.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), - 'zoneName': self._serialize.url("zone_name", zone_name, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-04-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-04-01")) + cls: ClsType[_models.Zone] = kwargs.pop("cls", None) + + request = build_get_request( + resource_group_name=resource_group_name, + zone_name=zone_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('Zone', pipeline_response) + deserialized = self._deserialize("Zone", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}'} # type: ignore + get.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}" + } + + @distributed_trace def list_by_resource_group( - self, - resource_group_name: str, - top: Optional[int] = None, - **kwargs - ) -> AsyncIterable["_models.ZoneListResult"]: + self, resource_group_name: str, top: Optional[int] = None, **kwargs: Any + ) -> AsyncIterable["_models.Zone"]: """Lists the DNS zones within a resource group. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str :param top: The maximum number of record sets to return. If not specified, returns up to 100 - record sets. + record sets. Default value is None. :type top: int :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either ZoneListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.dns.v2016_04_01.models.ZoneListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either Zone or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.dns.v2016_04_01.models.Zone] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.ZoneListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-04-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-04-01")) + cls: ClsType[_models.ZoneListResult] = kwargs.pop("cls", None) + 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 = "2016-04-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_by_resource_group.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - if top is not None: - query_parameters['$top'] = self._serialize.query("top", top, 'int') - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_by_resource_group_request( + resource_group_name=resource_group_name, + subscription_id=self._config.subscription_id, + top=top, + api_version=api_version, + template_url=self.list_by_resource_group.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('ZoneListResult', pipeline_response) + deserialized = self._deserialize("ZoneListResult", pipeline_response) list_of_elem = deserialized.value if cls: - list_of_elem = cls(list_of_elem) + list_of_elem = cls(list_of_elem) # type: ignore return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: @@ -380,70 +514,83 @@ async def get_next(next_link=None): return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list_by_resource_group.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones'} # type: ignore + return AsyncItemPaged(get_next, extract_data) - def list( - self, - top: Optional[int] = None, - **kwargs - ) -> AsyncIterable["_models.ZoneListResult"]: + list_by_resource_group.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones" + } + + @distributed_trace + def list(self, top: Optional[int] = None, **kwargs: Any) -> AsyncIterable["_models.Zone"]: """Lists the DNS zones in all resource groups in a subscription. :param top: The maximum number of DNS zones to return. If not specified, returns up to 100 - zones. + zones. Default value is None. :type top: int :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either ZoneListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.dns.v2016_04_01.models.ZoneListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either Zone or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.dns.v2016_04_01.models.Zone] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.ZoneListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-04-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-04-01")) + cls: ClsType[_models.ZoneListResult] = kwargs.pop("cls", None) + 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 = "2016-04-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list.metadata['url'] # type: ignore - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - if top is not None: - query_parameters['$top'] = self._serialize.query("top", top, 'int') - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_request( + subscription_id=self._config.subscription_id, + top=top, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('ZoneListResult', pipeline_response) + deserialized = self._deserialize("ZoneListResult", pipeline_response) list_of_elem = deserialized.value if cls: - list_of_elem = cls(list_of_elem) + list_of_elem = cls(list_of_elem) # type: ignore return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: @@ -452,7 +599,6 @@ async def get_next(next_link=None): return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Network/dnszones'} # type: ignore + return AsyncItemPaged(get_next, extract_data) + + list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Network/dnszones"} diff --git a/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2016_04_01/models/__init__.py b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2016_04_01/models/__init__.py index 4f52b8ef8668..a50864993003 100644 --- a/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2016_04_01/models/__init__.py +++ b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2016_04_01/models/__init__.py @@ -6,76 +6,58 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -try: - from ._models_py3 import ARecord - from ._models_py3 import AaaaRecord - from ._models_py3 import CloudErrorBody - from ._models_py3 import CnameRecord - from ._models_py3 import MxRecord - from ._models_py3 import NsRecord - from ._models_py3 import PtrRecord - from ._models_py3 import RecordSet - from ._models_py3 import RecordSetListResult - from ._models_py3 import RecordSetUpdateParameters - from ._models_py3 import Resource - from ._models_py3 import SoaRecord - from ._models_py3 import SrvRecord - from ._models_py3 import SubResource - from ._models_py3 import TrackedResource - from ._models_py3 import TxtRecord - from ._models_py3 import Zone - from ._models_py3 import ZoneDeleteResult - from ._models_py3 import ZoneListResult -except (SyntaxError, ImportError): - from ._models import ARecord # type: ignore - from ._models import AaaaRecord # type: ignore - from ._models import CloudErrorBody # type: ignore - from ._models import CnameRecord # type: ignore - from ._models import MxRecord # type: ignore - from ._models import NsRecord # type: ignore - from ._models import PtrRecord # type: ignore - from ._models import RecordSet # type: ignore - from ._models import RecordSetListResult # type: ignore - from ._models import RecordSetUpdateParameters # type: ignore - from ._models import Resource # type: ignore - from ._models import SoaRecord # type: ignore - from ._models import SrvRecord # type: ignore - from ._models import SubResource # type: ignore - from ._models import TrackedResource # type: ignore - from ._models import TxtRecord # type: ignore - from ._models import Zone # type: ignore - from ._models import ZoneDeleteResult # type: ignore - from ._models import ZoneListResult # type: ignore +from ._models_py3 import ARecord +from ._models_py3 import AaaaRecord +from ._models_py3 import CloudErrorBody +from ._models_py3 import CnameRecord +from ._models_py3 import MxRecord +from ._models_py3 import NsRecord +from ._models_py3 import PtrRecord +from ._models_py3 import RecordSet +from ._models_py3 import RecordSetListResult +from ._models_py3 import RecordSetUpdateParameters +from ._models_py3 import Resource +from ._models_py3 import SoaRecord +from ._models_py3 import SrvRecord +from ._models_py3 import SubResource +from ._models_py3 import TrackedResource +from ._models_py3 import TxtRecord +from ._models_py3 import Zone +from ._models_py3 import ZoneDeleteResult +from ._models_py3 import ZoneListResult -from ._dns_management_client_enums import ( - HttpStatusCode, - OperationStatus, - RecordType, - ZoneType, -) +from ._dns_management_client_enums import HttpStatusCode +from ._dns_management_client_enums import OperationStatus +from ._dns_management_client_enums import RecordType +from ._dns_management_client_enums import ZoneType +from ._patch import __all__ as _patch_all +from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import patch_sdk as _patch_sdk __all__ = [ - 'ARecord', - 'AaaaRecord', - 'CloudErrorBody', - 'CnameRecord', - 'MxRecord', - 'NsRecord', - 'PtrRecord', - 'RecordSet', - 'RecordSetListResult', - 'RecordSetUpdateParameters', - 'Resource', - 'SoaRecord', - 'SrvRecord', - 'SubResource', - 'TrackedResource', - 'TxtRecord', - 'Zone', - 'ZoneDeleteResult', - 'ZoneListResult', - 'HttpStatusCode', - 'OperationStatus', - 'RecordType', - 'ZoneType', + "ARecord", + "AaaaRecord", + "CloudErrorBody", + "CnameRecord", + "MxRecord", + "NsRecord", + "PtrRecord", + "RecordSet", + "RecordSetListResult", + "RecordSetUpdateParameters", + "Resource", + "SoaRecord", + "SrvRecord", + "SubResource", + "TrackedResource", + "TxtRecord", + "Zone", + "ZoneDeleteResult", + "ZoneListResult", + "HttpStatusCode", + "OperationStatus", + "RecordType", + "ZoneType", ] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2016_04_01/models/_dns_management_client_enums.py b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2016_04_01/models/_dns_management_client_enums.py index d3200a6666eb..28d380236533 100644 --- a/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2016_04_01/models/_dns_management_client_enums.py +++ b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2016_04_01/models/_dns_management_client_enums.py @@ -6,29 +6,14 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from enum import Enum, EnumMeta -from six import with_metaclass +from enum import Enum +from azure.core import CaseInsensitiveEnumMeta -class _CaseInsensitiveEnumMeta(EnumMeta): - def __getitem__(self, name): - return super().__getitem__(name.upper()) - def __getattr__(cls, name): - """Return the enum member matching `name` - We use __getattr__ instead of descriptors or inserting into the enum - class' __dict__ in order to support `name` and `value` being both - properties for enum members (which live in the class' __dict__) and - enum members themselves. - """ - try: - return cls._member_map_[name.upper()] - except KeyError: - raise AttributeError(name) +class HttpStatusCode(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """HttpStatusCode.""" - -class HttpStatusCode(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - - CONTINUE_ENUM = "Continue" + CONTINUE = "Continue" SWITCHING_PROTOCOLS = "SwitchingProtocols" OK = "OK" CREATED = "Created" @@ -76,13 +61,17 @@ class HttpStatusCode(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): GATEWAY_TIMEOUT = "GatewayTimeout" HTTP_VERSION_NOT_SUPPORTED = "HttpVersionNotSupported" -class OperationStatus(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): + +class OperationStatus(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """OperationStatus.""" IN_PROGRESS = "InProgress" SUCCEEDED = "Succeeded" FAILED = "Failed" -class RecordType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): + +class RecordType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """RecordType.""" A = "A" AAAA = "AAAA" @@ -94,9 +83,9 @@ class RecordType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): SRV = "SRV" TXT = "TXT" -class ZoneType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """The type of this DNS zone (Public or Private). - """ + +class ZoneType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The type of this DNS zone (Public or Private).""" PUBLIC = "Public" PRIVATE = "Private" diff --git a/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2016_04_01/models/_models.py b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2016_04_01/models/_models.py deleted file mode 100644 index 31cf91caa65f..000000000000 --- a/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2016_04_01/models/_models.py +++ /dev/null @@ -1,623 +0,0 @@ -# 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. -# -------------------------------------------------------------------------- - -import msrest.serialization - - -class AaaaRecord(msrest.serialization.Model): - """An AAAA record. - - :param ipv6_address: The IPv6 address of this AAAA record. - :type ipv6_address: str - """ - - _attribute_map = { - 'ipv6_address': {'key': 'ipv6Address', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(AaaaRecord, self).__init__(**kwargs) - self.ipv6_address = kwargs.get('ipv6_address', None) - - -class ARecord(msrest.serialization.Model): - """An A record. - - :param ipv4_address: The IPv4 address of this A record. - :type ipv4_address: str - """ - - _attribute_map = { - 'ipv4_address': {'key': 'ipv4Address', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(ARecord, self).__init__(**kwargs) - self.ipv4_address = kwargs.get('ipv4_address', None) - - -class CloudErrorBody(msrest.serialization.Model): - """An error response from the service. - - :param code: An identifier for the error. Codes are invariant and are intended to be consumed - programmatically. - :type code: str - :param message: A message describing the error, intended to be suitable for display in a user - interface. - :type message: str - :param target: The target of the particular error. For example, the name of the property in - error. - :type target: str - :param details: A list of additional details about the error. - :type details: list[~azure.mgmt.dns.v2016_04_01.models.CloudErrorBody] - """ - - _attribute_map = { - 'code': {'key': 'code', 'type': 'str'}, - 'message': {'key': 'message', 'type': 'str'}, - 'target': {'key': 'target', 'type': 'str'}, - 'details': {'key': 'details', 'type': '[CloudErrorBody]'}, - } - - def __init__( - self, - **kwargs - ): - super(CloudErrorBody, self).__init__(**kwargs) - self.code = kwargs.get('code', None) - self.message = kwargs.get('message', None) - self.target = kwargs.get('target', None) - self.details = kwargs.get('details', None) - - -class CnameRecord(msrest.serialization.Model): - """A CNAME record. - - :param cname: The canonical name for this CNAME record. - :type cname: str - """ - - _attribute_map = { - 'cname': {'key': 'cname', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(CnameRecord, self).__init__(**kwargs) - self.cname = kwargs.get('cname', None) - - -class MxRecord(msrest.serialization.Model): - """An MX record. - - :param preference: The preference value for this MX record. - :type preference: int - :param exchange: The domain name of the mail host for this MX record. - :type exchange: str - """ - - _attribute_map = { - 'preference': {'key': 'preference', 'type': 'int'}, - 'exchange': {'key': 'exchange', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(MxRecord, self).__init__(**kwargs) - self.preference = kwargs.get('preference', None) - self.exchange = kwargs.get('exchange', None) - - -class NsRecord(msrest.serialization.Model): - """An NS record. - - :param nsdname: The name server name for this NS record. - :type nsdname: str - """ - - _attribute_map = { - 'nsdname': {'key': 'nsdname', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(NsRecord, self).__init__(**kwargs) - self.nsdname = kwargs.get('nsdname', None) - - -class PtrRecord(msrest.serialization.Model): - """A PTR record. - - :param ptrdname: The PTR target domain name for this PTR record. - :type ptrdname: str - """ - - _attribute_map = { - 'ptrdname': {'key': 'ptrdname', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(PtrRecord, self).__init__(**kwargs) - self.ptrdname = kwargs.get('ptrdname', None) - - -class RecordSet(msrest.serialization.Model): - """Describes a DNS record set (a collection of DNS records with the same name and type). - - Variables are only populated by the server, and will be ignored when sending a request. - - :param id: The ID of the record set. - :type id: str - :param name: The name of the record set. - :type name: str - :param type: The type of the record set. - :type type: str - :param etag: The etag of the record set. - :type etag: str - :param metadata: The metadata attached to the record set. - :type metadata: dict[str, str] - :param ttl: The TTL (time-to-live) of the records in the record set. - :type ttl: long - :ivar fqdn: Fully qualified domain name of the record set. - :vartype fqdn: str - :param a_records: The list of A records in the record set. - :type a_records: list[~azure.mgmt.dns.v2016_04_01.models.ARecord] - :param aaaa_records: The list of AAAA records in the record set. - :type aaaa_records: list[~azure.mgmt.dns.v2016_04_01.models.AaaaRecord] - :param mx_records: The list of MX records in the record set. - :type mx_records: list[~azure.mgmt.dns.v2016_04_01.models.MxRecord] - :param ns_records: The list of NS records in the record set. - :type ns_records: list[~azure.mgmt.dns.v2016_04_01.models.NsRecord] - :param ptr_records: The list of PTR records in the record set. - :type ptr_records: list[~azure.mgmt.dns.v2016_04_01.models.PtrRecord] - :param srv_records: The list of SRV records in the record set. - :type srv_records: list[~azure.mgmt.dns.v2016_04_01.models.SrvRecord] - :param txt_records: The list of TXT records in the record set. - :type txt_records: list[~azure.mgmt.dns.v2016_04_01.models.TxtRecord] - :param cname_record: The CNAME record in the record set. - :type cname_record: ~azure.mgmt.dns.v2016_04_01.models.CnameRecord - :param soa_record: The SOA record in the record set. - :type soa_record: ~azure.mgmt.dns.v2016_04_01.models.SoaRecord - """ - - _validation = { - 'fqdn': {'readonly': True}, - } - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'etag': {'key': 'etag', 'type': 'str'}, - 'metadata': {'key': 'properties.metadata', 'type': '{str}'}, - 'ttl': {'key': 'properties.TTL', 'type': 'long'}, - 'fqdn': {'key': 'properties.fqdn', 'type': 'str'}, - 'a_records': {'key': 'properties.ARecords', 'type': '[ARecord]'}, - 'aaaa_records': {'key': 'properties.AAAARecords', 'type': '[AaaaRecord]'}, - 'mx_records': {'key': 'properties.MXRecords', 'type': '[MxRecord]'}, - 'ns_records': {'key': 'properties.NSRecords', 'type': '[NsRecord]'}, - 'ptr_records': {'key': 'properties.PTRRecords', 'type': '[PtrRecord]'}, - 'srv_records': {'key': 'properties.SRVRecords', 'type': '[SrvRecord]'}, - 'txt_records': {'key': 'properties.TXTRecords', 'type': '[TxtRecord]'}, - 'cname_record': {'key': 'properties.CNAMERecord', 'type': 'CnameRecord'}, - 'soa_record': {'key': 'properties.SOARecord', 'type': 'SoaRecord'}, - } - - def __init__( - self, - **kwargs - ): - super(RecordSet, self).__init__(**kwargs) - self.id = kwargs.get('id', None) - self.name = kwargs.get('name', None) - self.type = kwargs.get('type', None) - self.etag = kwargs.get('etag', None) - self.metadata = kwargs.get('metadata', None) - self.ttl = kwargs.get('ttl', None) - self.fqdn = None - self.a_records = kwargs.get('a_records', None) - self.aaaa_records = kwargs.get('aaaa_records', None) - self.mx_records = kwargs.get('mx_records', None) - self.ns_records = kwargs.get('ns_records', None) - self.ptr_records = kwargs.get('ptr_records', None) - self.srv_records = kwargs.get('srv_records', None) - self.txt_records = kwargs.get('txt_records', None) - self.cname_record = kwargs.get('cname_record', None) - self.soa_record = kwargs.get('soa_record', None) - - -class RecordSetListResult(msrest.serialization.Model): - """The response to a record set List operation. - - :param value: Information about the record sets in the response. - :type value: list[~azure.mgmt.dns.v2016_04_01.models.RecordSet] - :param next_link: The continuation token for the next page of results. - :type next_link: str - """ - - _attribute_map = { - 'value': {'key': 'value', 'type': '[RecordSet]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(RecordSetListResult, self).__init__(**kwargs) - self.value = kwargs.get('value', None) - self.next_link = kwargs.get('next_link', None) - - -class RecordSetUpdateParameters(msrest.serialization.Model): - """Parameters supplied to update a record set. - - :param record_set: Specifies information about the record set being updated. - :type record_set: ~azure.mgmt.dns.v2016_04_01.models.RecordSet - """ - - _attribute_map = { - 'record_set': {'key': 'RecordSet', 'type': 'RecordSet'}, - } - - def __init__( - self, - **kwargs - ): - super(RecordSetUpdateParameters, self).__init__(**kwargs) - self.record_set = kwargs.get('record_set', None) - - -class Resource(msrest.serialization.Model): - """Common fields that are returned in the response for all Azure Resource Manager resources. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: Fully qualified resource ID for the resource. Ex - - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. - :vartype id: str - :ivar name: The name of the resource. - :vartype name: str - :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or - "Microsoft.Storage/storageAccounts". - :vartype type: str - """ - - _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - } - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(Resource, self).__init__(**kwargs) - self.id = None - self.name = None - self.type = None - - -class SoaRecord(msrest.serialization.Model): - """An SOA record. - - :param host: The domain name of the authoritative name server for this SOA record. - :type host: str - :param email: The email contact for this SOA record. - :type email: str - :param serial_number: The serial number for this SOA record. - :type serial_number: long - :param refresh_time: The refresh value for this SOA record. - :type refresh_time: long - :param retry_time: The retry time for this SOA record. - :type retry_time: long - :param expire_time: The expire time for this SOA record. - :type expire_time: long - :param minimum_ttl: The minimum value for this SOA record. By convention this is used to - determine the negative caching duration. - :type minimum_ttl: long - """ - - _attribute_map = { - 'host': {'key': 'host', 'type': 'str'}, - 'email': {'key': 'email', 'type': 'str'}, - 'serial_number': {'key': 'serialNumber', 'type': 'long'}, - 'refresh_time': {'key': 'refreshTime', 'type': 'long'}, - 'retry_time': {'key': 'retryTime', 'type': 'long'}, - 'expire_time': {'key': 'expireTime', 'type': 'long'}, - 'minimum_ttl': {'key': 'minimumTTL', 'type': 'long'}, - } - - def __init__( - self, - **kwargs - ): - super(SoaRecord, self).__init__(**kwargs) - self.host = kwargs.get('host', None) - self.email = kwargs.get('email', None) - self.serial_number = kwargs.get('serial_number', None) - self.refresh_time = kwargs.get('refresh_time', None) - self.retry_time = kwargs.get('retry_time', None) - self.expire_time = kwargs.get('expire_time', None) - self.minimum_ttl = kwargs.get('minimum_ttl', None) - - -class SrvRecord(msrest.serialization.Model): - """An SRV record. - - :param priority: The priority value for this SRV record. - :type priority: int - :param weight: The weight value for this SRV record. - :type weight: int - :param port: The port value for this SRV record. - :type port: int - :param target: The target domain name for this SRV record. - :type target: str - """ - - _attribute_map = { - 'priority': {'key': 'priority', 'type': 'int'}, - 'weight': {'key': 'weight', 'type': 'int'}, - 'port': {'key': 'port', 'type': 'int'}, - 'target': {'key': 'target', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(SrvRecord, self).__init__(**kwargs) - self.priority = kwargs.get('priority', None) - self.weight = kwargs.get('weight', None) - self.port = kwargs.get('port', None) - self.target = kwargs.get('target', None) - - -class SubResource(msrest.serialization.Model): - """SubResource. - - :param id: Resource Id. - :type id: str - """ - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(SubResource, self).__init__(**kwargs) - self.id = kwargs.get('id', None) - - -class TrackedResource(Resource): - """The resource model definition for an Azure Resource Manager tracked top level resource which has 'tags' and a 'location'. - - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to Azure. - - :ivar id: Fully qualified resource ID for the resource. Ex - - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. - :vartype id: str - :ivar name: The name of the resource. - :vartype name: str - :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or - "Microsoft.Storage/storageAccounts". - :vartype type: str - :param tags: A set of tags. Resource tags. - :type tags: dict[str, str] - :param location: Required. The geo-location where the resource lives. - :type location: str - """ - - _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'location': {'required': True}, - } - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'tags': {'key': 'tags', 'type': '{str}'}, - 'location': {'key': 'location', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(TrackedResource, self).__init__(**kwargs) - self.tags = kwargs.get('tags', None) - self.location = kwargs['location'] - - -class TxtRecord(msrest.serialization.Model): - """A TXT record. - - :param value: The text value of this TXT record. - :type value: list[str] - """ - - _attribute_map = { - 'value': {'key': 'value', 'type': '[str]'}, - } - - def __init__( - self, - **kwargs - ): - super(TxtRecord, self).__init__(**kwargs) - self.value = kwargs.get('value', None) - - -class Zone(TrackedResource): - """Describes a DNS zone. - - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to Azure. - - :ivar id: Fully qualified resource ID for the resource. Ex - - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. - :vartype id: str - :ivar name: The name of the resource. - :vartype name: str - :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or - "Microsoft.Storage/storageAccounts". - :vartype type: str - :param tags: A set of tags. Resource tags. - :type tags: dict[str, str] - :param location: Required. The geo-location where the resource lives. - :type location: str - :param etag: The etag of the zone. - :type etag: str - :param max_number_of_record_sets: The maximum number of record sets that can be created in this - DNS zone. This is a read-only property and any attempt to set this value will be ignored. - :type max_number_of_record_sets: long - :ivar max_number_of_records_per_record_set: The maximum number of records per record set that - can be created in this DNS zone. This is a read-only property and any attempt to set this - value will be ignored. - :vartype max_number_of_records_per_record_set: long - :param number_of_record_sets: The current number of record sets in this DNS zone. This is a - read-only property and any attempt to set this value will be ignored. - :type number_of_record_sets: long - :ivar name_servers: The name servers for this DNS zone. This is a read-only property and any - attempt to set this value will be ignored. - :vartype name_servers: list[str] - :param zone_type: The type of this DNS zone (Public or Private). Possible values include: - "Public", "Private". Default value: "Public". - :type zone_type: str or ~azure.mgmt.dns.v2016_04_01.models.ZoneType - """ - - _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'location': {'required': True}, - 'max_number_of_records_per_record_set': {'readonly': True}, - 'name_servers': {'readonly': True}, - } - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'tags': {'key': 'tags', 'type': '{str}'}, - 'location': {'key': 'location', 'type': 'str'}, - 'etag': {'key': 'etag', 'type': 'str'}, - 'max_number_of_record_sets': {'key': 'properties.maxNumberOfRecordSets', 'type': 'long'}, - 'max_number_of_records_per_record_set': {'key': 'properties.maxNumberOfRecordsPerRecordSet', 'type': 'long'}, - 'number_of_record_sets': {'key': 'properties.numberOfRecordSets', 'type': 'long'}, - 'name_servers': {'key': 'properties.nameServers', 'type': '[str]'}, - 'zone_type': {'key': 'properties.zoneType', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(Zone, self).__init__(**kwargs) - self.etag = kwargs.get('etag', None) - self.max_number_of_record_sets = kwargs.get('max_number_of_record_sets', None) - self.max_number_of_records_per_record_set = None - self.number_of_record_sets = kwargs.get('number_of_record_sets', None) - self.name_servers = None - self.zone_type = kwargs.get('zone_type', "Public") - - -class ZoneDeleteResult(msrest.serialization.Model): - """The response to a Zone Delete operation. - - :param azure_async_operation: Users can perform a Get on Azure-AsyncOperation to get the status - of their delete Zone operations. - :type azure_async_operation: str - :param status: Possible values include: "InProgress", "Succeeded", "Failed". - :type status: str or ~azure.mgmt.dns.v2016_04_01.models.OperationStatus - :param status_code: Possible values include: "Continue", "SwitchingProtocols", "OK", - "Created", "Accepted", "NonAuthoritativeInformation", "NoContent", "ResetContent", - "PartialContent", "MultipleChoices", "Ambiguous", "MovedPermanently", "Moved", "Found", - "Redirect", "SeeOther", "RedirectMethod", "NotModified", "UseProxy", "Unused", - "TemporaryRedirect", "RedirectKeepVerb", "BadRequest", "Unauthorized", "PaymentRequired", - "Forbidden", "NotFound", "MethodNotAllowed", "NotAcceptable", "ProxyAuthenticationRequired", - "RequestTimeout", "Conflict", "Gone", "LengthRequired", "PreconditionFailed", - "RequestEntityTooLarge", "RequestUriTooLong", "UnsupportedMediaType", - "RequestedRangeNotSatisfiable", "ExpectationFailed", "UpgradeRequired", "InternalServerError", - "NotImplemented", "BadGateway", "ServiceUnavailable", "GatewayTimeout", - "HttpVersionNotSupported". - :type status_code: str or ~azure.mgmt.dns.v2016_04_01.models.HttpStatusCode - :param request_id: - :type request_id: str - """ - - _attribute_map = { - 'azure_async_operation': {'key': 'azureAsyncOperation', 'type': 'str'}, - 'status': {'key': 'status', 'type': 'str'}, - 'status_code': {'key': 'statusCode', 'type': 'str'}, - 'request_id': {'key': 'requestId', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(ZoneDeleteResult, self).__init__(**kwargs) - self.azure_async_operation = kwargs.get('azure_async_operation', None) - self.status = kwargs.get('status', None) - self.status_code = kwargs.get('status_code', None) - self.request_id = kwargs.get('request_id', None) - - -class ZoneListResult(msrest.serialization.Model): - """The response to a Zone List or ListAll operation. - - :param value: Information about the DNS zones. - :type value: list[~azure.mgmt.dns.v2016_04_01.models.Zone] - :param next_link: The continuation token for the next page of results. - :type next_link: str - """ - - _attribute_map = { - 'value': {'key': 'value', 'type': '[Zone]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(ZoneListResult, self).__init__(**kwargs) - self.value = kwargs.get('value', None) - self.next_link = kwargs.get('next_link', None) diff --git a/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2016_04_01/models/_models_py3.py b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2016_04_01/models/_models_py3.py index 8a2078aacd66..093b5616e4ca 100644 --- a/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2016_04_01/models/_models_py3.py +++ b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2016_04_01/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. @@ -6,76 +7,76 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Dict, List, Optional, Union +from typing import Any, Dict, List, Optional, TYPE_CHECKING, Union -import msrest.serialization +from ... import _serialization -from ._dns_management_client_enums import * +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from .. import models as _models -class AaaaRecord(msrest.serialization.Model): +class AaaaRecord(_serialization.Model): """An AAAA record. - :param ipv6_address: The IPv6 address of this AAAA record. - :type ipv6_address: str + :ivar ipv6_address: The IPv6 address of this AAAA record. + :vartype ipv6_address: str """ _attribute_map = { - 'ipv6_address': {'key': 'ipv6Address', 'type': 'str'}, + "ipv6_address": {"key": "ipv6Address", "type": "str"}, } - def __init__( - self, - *, - ipv6_address: Optional[str] = None, - **kwargs - ): - super(AaaaRecord, self).__init__(**kwargs) + def __init__(self, *, ipv6_address: Optional[str] = None, **kwargs: Any) -> None: + """ + :keyword ipv6_address: The IPv6 address of this AAAA record. + :paramtype ipv6_address: str + """ + super().__init__(**kwargs) self.ipv6_address = ipv6_address -class ARecord(msrest.serialization.Model): +class ARecord(_serialization.Model): """An A record. - :param ipv4_address: The IPv4 address of this A record. - :type ipv4_address: str + :ivar ipv4_address: The IPv4 address of this A record. + :vartype ipv4_address: str """ _attribute_map = { - 'ipv4_address': {'key': 'ipv4Address', 'type': 'str'}, + "ipv4_address": {"key": "ipv4Address", "type": "str"}, } - def __init__( - self, - *, - ipv4_address: Optional[str] = None, - **kwargs - ): - super(ARecord, self).__init__(**kwargs) + def __init__(self, *, ipv4_address: Optional[str] = None, **kwargs: Any) -> None: + """ + :keyword ipv4_address: The IPv4 address of this A record. + :paramtype ipv4_address: str + """ + super().__init__(**kwargs) self.ipv4_address = ipv4_address -class CloudErrorBody(msrest.serialization.Model): +class CloudErrorBody(_serialization.Model): """An error response from the service. - :param code: An identifier for the error. Codes are invariant and are intended to be consumed + :ivar code: An identifier for the error. Codes are invariant and are intended to be consumed programmatically. - :type code: str - :param message: A message describing the error, intended to be suitable for display in a user + :vartype code: str + :ivar message: A message describing the error, intended to be suitable for display in a user interface. - :type message: str - :param target: The target of the particular error. For example, the name of the property in + :vartype message: str + :ivar target: The target of the particular error. For example, the name of the property in error. - :type target: str - :param details: A list of additional details about the error. - :type details: list[~azure.mgmt.dns.v2016_04_01.models.CloudErrorBody] + :vartype target: str + :ivar details: A list of additional details about the error. + :vartype details: list[~azure.mgmt.dns.v2016_04_01.models.CloudErrorBody] """ _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__( @@ -84,188 +85,230 @@ def __init__( code: Optional[str] = None, message: Optional[str] = None, target: Optional[str] = None, - details: Optional[List["CloudErrorBody"]] = None, - **kwargs - ): - super(CloudErrorBody, self).__init__(**kwargs) + details: Optional[List["_models.CloudErrorBody"]] = None, + **kwargs: Any + ) -> None: + """ + :keyword code: An identifier for the error. Codes are invariant and are intended to be consumed + programmatically. + :paramtype code: str + :keyword message: A message describing the error, intended to be suitable for display in a user + interface. + :paramtype message: str + :keyword target: The target of the particular error. For example, the name of the property in + error. + :paramtype target: str + :keyword details: A list of additional details about the error. + :paramtype details: list[~azure.mgmt.dns.v2016_04_01.models.CloudErrorBody] + """ + super().__init__(**kwargs) self.code = code self.message = message self.target = target self.details = details -class CnameRecord(msrest.serialization.Model): +class CnameRecord(_serialization.Model): """A CNAME record. - :param cname: The canonical name for this CNAME record. - :type cname: str + :ivar cname: The canonical name for this CNAME record. + :vartype cname: str """ _attribute_map = { - 'cname': {'key': 'cname', 'type': 'str'}, + "cname": {"key": "cname", "type": "str"}, } - def __init__( - self, - *, - cname: Optional[str] = None, - **kwargs - ): - super(CnameRecord, self).__init__(**kwargs) + def __init__(self, *, cname: Optional[str] = None, **kwargs: Any) -> None: + """ + :keyword cname: The canonical name for this CNAME record. + :paramtype cname: str + """ + super().__init__(**kwargs) self.cname = cname -class MxRecord(msrest.serialization.Model): +class MxRecord(_serialization.Model): """An MX record. - :param preference: The preference value for this MX record. - :type preference: int - :param exchange: The domain name of the mail host for this MX record. - :type exchange: str + :ivar preference: The preference value for this MX record. + :vartype preference: int + :ivar exchange: The domain name of the mail host for this MX record. + :vartype exchange: str """ _attribute_map = { - 'preference': {'key': 'preference', 'type': 'int'}, - 'exchange': {'key': 'exchange', 'type': 'str'}, + "preference": {"key": "preference", "type": "int"}, + "exchange": {"key": "exchange", "type": "str"}, } - def __init__( - self, - *, - preference: Optional[int] = None, - exchange: Optional[str] = None, - **kwargs - ): - super(MxRecord, self).__init__(**kwargs) + def __init__(self, *, preference: Optional[int] = None, exchange: Optional[str] = None, **kwargs: Any) -> None: + """ + :keyword preference: The preference value for this MX record. + :paramtype preference: int + :keyword exchange: The domain name of the mail host for this MX record. + :paramtype exchange: str + """ + super().__init__(**kwargs) self.preference = preference self.exchange = exchange -class NsRecord(msrest.serialization.Model): +class NsRecord(_serialization.Model): """An NS record. - :param nsdname: The name server name for this NS record. - :type nsdname: str + :ivar nsdname: The name server name for this NS record. + :vartype nsdname: str """ _attribute_map = { - 'nsdname': {'key': 'nsdname', 'type': 'str'}, + "nsdname": {"key": "nsdname", "type": "str"}, } - def __init__( - self, - *, - nsdname: Optional[str] = None, - **kwargs - ): - super(NsRecord, self).__init__(**kwargs) + def __init__(self, *, nsdname: Optional[str] = None, **kwargs: Any) -> None: + """ + :keyword nsdname: The name server name for this NS record. + :paramtype nsdname: str + """ + super().__init__(**kwargs) self.nsdname = nsdname -class PtrRecord(msrest.serialization.Model): +class PtrRecord(_serialization.Model): """A PTR record. - :param ptrdname: The PTR target domain name for this PTR record. - :type ptrdname: str + :ivar ptrdname: The PTR target domain name for this PTR record. + :vartype ptrdname: str """ _attribute_map = { - 'ptrdname': {'key': 'ptrdname', 'type': 'str'}, + "ptrdname": {"key": "ptrdname", "type": "str"}, } - def __init__( - self, - *, - ptrdname: Optional[str] = None, - **kwargs - ): - super(PtrRecord, self).__init__(**kwargs) + def __init__(self, *, ptrdname: Optional[str] = None, **kwargs: Any) -> None: + """ + :keyword ptrdname: The PTR target domain name for this PTR record. + :paramtype ptrdname: str + """ + super().__init__(**kwargs) self.ptrdname = ptrdname -class RecordSet(msrest.serialization.Model): +class RecordSet(_serialization.Model): # pylint: disable=too-many-instance-attributes """Describes a DNS record set (a collection of DNS records with the same name and type). Variables are only populated by the server, and will be ignored when sending a request. - :param id: The ID of the record set. - :type id: str - :param name: The name of the record set. - :type name: str - :param type: The type of the record set. - :type type: str - :param etag: The etag of the record set. - :type etag: str - :param metadata: The metadata attached to the record set. - :type metadata: dict[str, str] - :param ttl: The TTL (time-to-live) of the records in the record set. - :type ttl: long + :ivar id: The ID of the record set. + :vartype id: str + :ivar name: The name of the record set. + :vartype name: str + :ivar type: The type of the record set. + :vartype type: str + :ivar etag: The etag of the record set. + :vartype etag: str + :ivar metadata: The metadata attached to the record set. + :vartype metadata: dict[str, str] + :ivar ttl: The TTL (time-to-live) of the records in the record set. + :vartype ttl: int :ivar fqdn: Fully qualified domain name of the record set. :vartype fqdn: str - :param a_records: The list of A records in the record set. - :type a_records: list[~azure.mgmt.dns.v2016_04_01.models.ARecord] - :param aaaa_records: The list of AAAA records in the record set. - :type aaaa_records: list[~azure.mgmt.dns.v2016_04_01.models.AaaaRecord] - :param mx_records: The list of MX records in the record set. - :type mx_records: list[~azure.mgmt.dns.v2016_04_01.models.MxRecord] - :param ns_records: The list of NS records in the record set. - :type ns_records: list[~azure.mgmt.dns.v2016_04_01.models.NsRecord] - :param ptr_records: The list of PTR records in the record set. - :type ptr_records: list[~azure.mgmt.dns.v2016_04_01.models.PtrRecord] - :param srv_records: The list of SRV records in the record set. - :type srv_records: list[~azure.mgmt.dns.v2016_04_01.models.SrvRecord] - :param txt_records: The list of TXT records in the record set. - :type txt_records: list[~azure.mgmt.dns.v2016_04_01.models.TxtRecord] - :param cname_record: The CNAME record in the record set. - :type cname_record: ~azure.mgmt.dns.v2016_04_01.models.CnameRecord - :param soa_record: The SOA record in the record set. - :type soa_record: ~azure.mgmt.dns.v2016_04_01.models.SoaRecord + :ivar a_records: The list of A records in the record set. + :vartype a_records: list[~azure.mgmt.dns.v2016_04_01.models.ARecord] + :ivar aaaa_records: The list of AAAA records in the record set. + :vartype aaaa_records: list[~azure.mgmt.dns.v2016_04_01.models.AaaaRecord] + :ivar mx_records: The list of MX records in the record set. + :vartype mx_records: list[~azure.mgmt.dns.v2016_04_01.models.MxRecord] + :ivar ns_records: The list of NS records in the record set. + :vartype ns_records: list[~azure.mgmt.dns.v2016_04_01.models.NsRecord] + :ivar ptr_records: The list of PTR records in the record set. + :vartype ptr_records: list[~azure.mgmt.dns.v2016_04_01.models.PtrRecord] + :ivar srv_records: The list of SRV records in the record set. + :vartype srv_records: list[~azure.mgmt.dns.v2016_04_01.models.SrvRecord] + :ivar txt_records: The list of TXT records in the record set. + :vartype txt_records: list[~azure.mgmt.dns.v2016_04_01.models.TxtRecord] + :ivar cname_record: The CNAME record in the record set. + :vartype cname_record: ~azure.mgmt.dns.v2016_04_01.models.CnameRecord + :ivar soa_record: The SOA record in the record set. + :vartype soa_record: ~azure.mgmt.dns.v2016_04_01.models.SoaRecord """ _validation = { - 'fqdn': {'readonly': True}, + "fqdn": {"readonly": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'etag': {'key': 'etag', 'type': 'str'}, - 'metadata': {'key': 'properties.metadata', 'type': '{str}'}, - 'ttl': {'key': 'properties.TTL', 'type': 'long'}, - 'fqdn': {'key': 'properties.fqdn', 'type': 'str'}, - 'a_records': {'key': 'properties.ARecords', 'type': '[ARecord]'}, - 'aaaa_records': {'key': 'properties.AAAARecords', 'type': '[AaaaRecord]'}, - 'mx_records': {'key': 'properties.MXRecords', 'type': '[MxRecord]'}, - 'ns_records': {'key': 'properties.NSRecords', 'type': '[NsRecord]'}, - 'ptr_records': {'key': 'properties.PTRRecords', 'type': '[PtrRecord]'}, - 'srv_records': {'key': 'properties.SRVRecords', 'type': '[SrvRecord]'}, - 'txt_records': {'key': 'properties.TXTRecords', 'type': '[TxtRecord]'}, - 'cname_record': {'key': 'properties.CNAMERecord', 'type': 'CnameRecord'}, - 'soa_record': {'key': 'properties.SOARecord', 'type': 'SoaRecord'}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "etag": {"key": "etag", "type": "str"}, + "metadata": {"key": "properties.metadata", "type": "{str}"}, + "ttl": {"key": "properties.TTL", "type": "int"}, + "fqdn": {"key": "properties.fqdn", "type": "str"}, + "a_records": {"key": "properties.ARecords", "type": "[ARecord]"}, + "aaaa_records": {"key": "properties.AAAARecords", "type": "[AaaaRecord]"}, + "mx_records": {"key": "properties.MXRecords", "type": "[MxRecord]"}, + "ns_records": {"key": "properties.NSRecords", "type": "[NsRecord]"}, + "ptr_records": {"key": "properties.PTRRecords", "type": "[PtrRecord]"}, + "srv_records": {"key": "properties.SRVRecords", "type": "[SrvRecord]"}, + "txt_records": {"key": "properties.TXTRecords", "type": "[TxtRecord]"}, + "cname_record": {"key": "properties.CNAMERecord", "type": "CnameRecord"}, + "soa_record": {"key": "properties.SOARecord", "type": "SoaRecord"}, } def __init__( self, *, - id: Optional[str] = None, + id: Optional[str] = None, # pylint: disable=redefined-builtin name: Optional[str] = None, type: Optional[str] = None, etag: Optional[str] = None, metadata: Optional[Dict[str, str]] = None, ttl: Optional[int] = None, - a_records: Optional[List["ARecord"]] = None, - aaaa_records: Optional[List["AaaaRecord"]] = None, - mx_records: Optional[List["MxRecord"]] = None, - ns_records: Optional[List["NsRecord"]] = None, - ptr_records: Optional[List["PtrRecord"]] = None, - srv_records: Optional[List["SrvRecord"]] = None, - txt_records: Optional[List["TxtRecord"]] = None, - cname_record: Optional["CnameRecord"] = None, - soa_record: Optional["SoaRecord"] = None, - **kwargs - ): - super(RecordSet, self).__init__(**kwargs) + a_records: Optional[List["_models.ARecord"]] = None, + aaaa_records: Optional[List["_models.AaaaRecord"]] = None, + mx_records: Optional[List["_models.MxRecord"]] = None, + ns_records: Optional[List["_models.NsRecord"]] = None, + ptr_records: Optional[List["_models.PtrRecord"]] = None, + srv_records: Optional[List["_models.SrvRecord"]] = None, + txt_records: Optional[List["_models.TxtRecord"]] = None, + cname_record: Optional["_models.CnameRecord"] = None, + soa_record: Optional["_models.SoaRecord"] = None, + **kwargs: Any + ) -> None: + """ + :keyword id: The ID of the record set. + :paramtype id: str + :keyword name: The name of the record set. + :paramtype name: str + :keyword type: The type of the record set. + :paramtype type: str + :keyword etag: The etag of the record set. + :paramtype etag: str + :keyword metadata: The metadata attached to the record set. + :paramtype metadata: dict[str, str] + :keyword ttl: The TTL (time-to-live) of the records in the record set. + :paramtype ttl: int + :keyword a_records: The list of A records in the record set. + :paramtype a_records: list[~azure.mgmt.dns.v2016_04_01.models.ARecord] + :keyword aaaa_records: The list of AAAA records in the record set. + :paramtype aaaa_records: list[~azure.mgmt.dns.v2016_04_01.models.AaaaRecord] + :keyword mx_records: The list of MX records in the record set. + :paramtype mx_records: list[~azure.mgmt.dns.v2016_04_01.models.MxRecord] + :keyword ns_records: The list of NS records in the record set. + :paramtype ns_records: list[~azure.mgmt.dns.v2016_04_01.models.NsRecord] + :keyword ptr_records: The list of PTR records in the record set. + :paramtype ptr_records: list[~azure.mgmt.dns.v2016_04_01.models.PtrRecord] + :keyword srv_records: The list of SRV records in the record set. + :paramtype srv_records: list[~azure.mgmt.dns.v2016_04_01.models.SrvRecord] + :keyword txt_records: The list of TXT records in the record set. + :paramtype txt_records: list[~azure.mgmt.dns.v2016_04_01.models.TxtRecord] + :keyword cname_record: The CNAME record in the record set. + :paramtype cname_record: ~azure.mgmt.dns.v2016_04_01.models.CnameRecord + :keyword soa_record: The SOA record in the record set. + :paramtype soa_record: ~azure.mgmt.dns.v2016_04_01.models.SoaRecord + """ + super().__init__(**kwargs) self.id = id self.name = name self.type = type @@ -284,54 +327,55 @@ def __init__( self.soa_record = soa_record -class RecordSetListResult(msrest.serialization.Model): +class RecordSetListResult(_serialization.Model): """The response to a record set List operation. - :param value: Information about the record sets in the response. - :type value: list[~azure.mgmt.dns.v2016_04_01.models.RecordSet] - :param next_link: The continuation token for the next page of results. - :type next_link: str + :ivar value: Information about the record sets in the response. + :vartype value: list[~azure.mgmt.dns.v2016_04_01.models.RecordSet] + :ivar next_link: The continuation token for the next page of results. + :vartype next_link: str """ _attribute_map = { - 'value': {'key': 'value', 'type': '[RecordSet]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "value": {"key": "value", "type": "[RecordSet]"}, + "next_link": {"key": "nextLink", "type": "str"}, } def __init__( - self, - *, - value: Optional[List["RecordSet"]] = None, - next_link: Optional[str] = None, - **kwargs - ): - super(RecordSetListResult, self).__init__(**kwargs) + self, *, value: Optional[List["_models.RecordSet"]] = None, next_link: Optional[str] = None, **kwargs: Any + ) -> None: + """ + :keyword value: Information about the record sets in the response. + :paramtype value: list[~azure.mgmt.dns.v2016_04_01.models.RecordSet] + :keyword next_link: The continuation token for the next page of results. + :paramtype next_link: str + """ + super().__init__(**kwargs) self.value = value self.next_link = next_link -class RecordSetUpdateParameters(msrest.serialization.Model): +class RecordSetUpdateParameters(_serialization.Model): """Parameters supplied to update a record set. - :param record_set: Specifies information about the record set being updated. - :type record_set: ~azure.mgmt.dns.v2016_04_01.models.RecordSet + :ivar record_set: Specifies information about the record set being updated. + :vartype record_set: ~azure.mgmt.dns.v2016_04_01.models.RecordSet """ _attribute_map = { - 'record_set': {'key': 'RecordSet', 'type': 'RecordSet'}, + "record_set": {"key": "RecordSet", "type": "RecordSet"}, } - def __init__( - self, - *, - record_set: Optional["RecordSet"] = None, - **kwargs - ): - super(RecordSetUpdateParameters, self).__init__(**kwargs) + def __init__(self, *, record_set: Optional["_models.RecordSet"] = None, **kwargs: Any) -> None: + """ + :keyword record_set: Specifies information about the record set being updated. + :paramtype record_set: ~azure.mgmt.dns.v2016_04_01.models.RecordSet + """ + super().__init__(**kwargs) self.record_set = record_set -class Resource(msrest.serialization.Model): +class Resource(_serialization.Model): """Common fields that are returned in the response for all Azure Resource Manager resources. Variables are only populated by the server, and will be ignored when sending a request. @@ -347,55 +391,53 @@ class Resource(msrest.serialization.Model): """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, } - def __init__( - self, - **kwargs - ): - super(Resource, self).__init__(**kwargs) + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) self.id = None self.name = None self.type = None -class SoaRecord(msrest.serialization.Model): +class SoaRecord(_serialization.Model): """An SOA record. - :param host: The domain name of the authoritative name server for this SOA record. - :type host: str - :param email: The email contact for this SOA record. - :type email: str - :param serial_number: The serial number for this SOA record. - :type serial_number: long - :param refresh_time: The refresh value for this SOA record. - :type refresh_time: long - :param retry_time: The retry time for this SOA record. - :type retry_time: long - :param expire_time: The expire time for this SOA record. - :type expire_time: long - :param minimum_ttl: The minimum value for this SOA record. By convention this is used to + :ivar host: The domain name of the authoritative name server for this SOA record. + :vartype host: str + :ivar email: The email contact for this SOA record. + :vartype email: str + :ivar serial_number: The serial number for this SOA record. + :vartype serial_number: int + :ivar refresh_time: The refresh value for this SOA record. + :vartype refresh_time: int + :ivar retry_time: The retry time for this SOA record. + :vartype retry_time: int + :ivar expire_time: The expire time for this SOA record. + :vartype expire_time: int + :ivar minimum_ttl: The minimum value for this SOA record. By convention this is used to determine the negative caching duration. - :type minimum_ttl: long + :vartype minimum_ttl: int """ _attribute_map = { - 'host': {'key': 'host', 'type': 'str'}, - 'email': {'key': 'email', 'type': 'str'}, - 'serial_number': {'key': 'serialNumber', 'type': 'long'}, - 'refresh_time': {'key': 'refreshTime', 'type': 'long'}, - 'retry_time': {'key': 'retryTime', 'type': 'long'}, - 'expire_time': {'key': 'expireTime', 'type': 'long'}, - 'minimum_ttl': {'key': 'minimumTTL', 'type': 'long'}, + "host": {"key": "host", "type": "str"}, + "email": {"key": "email", "type": "str"}, + "serial_number": {"key": "serialNumber", "type": "int"}, + "refresh_time": {"key": "refreshTime", "type": "int"}, + "retry_time": {"key": "retryTime", "type": "int"}, + "expire_time": {"key": "expireTime", "type": "int"}, + "minimum_ttl": {"key": "minimumTTL", "type": "int"}, } def __init__( @@ -408,9 +450,26 @@ def __init__( retry_time: Optional[int] = None, expire_time: Optional[int] = None, minimum_ttl: Optional[int] = None, - **kwargs - ): - super(SoaRecord, self).__init__(**kwargs) + **kwargs: Any + ) -> None: + """ + :keyword host: The domain name of the authoritative name server for this SOA record. + :paramtype host: str + :keyword email: The email contact for this SOA record. + :paramtype email: str + :keyword serial_number: The serial number for this SOA record. + :paramtype serial_number: int + :keyword refresh_time: The refresh value for this SOA record. + :paramtype refresh_time: int + :keyword retry_time: The retry time for this SOA record. + :paramtype retry_time: int + :keyword expire_time: The expire time for this SOA record. + :paramtype expire_time: int + :keyword minimum_ttl: The minimum value for this SOA record. By convention this is used to + determine the negative caching duration. + :paramtype minimum_ttl: int + """ + super().__init__(**kwargs) self.host = host self.email = email self.serial_number = serial_number @@ -420,24 +479,24 @@ def __init__( self.minimum_ttl = minimum_ttl -class SrvRecord(msrest.serialization.Model): +class SrvRecord(_serialization.Model): """An SRV record. - :param priority: The priority value for this SRV record. - :type priority: int - :param weight: The weight value for this SRV record. - :type weight: int - :param port: The port value for this SRV record. - :type port: int - :param target: The target domain name for this SRV record. - :type target: str + :ivar priority: The priority value for this SRV record. + :vartype priority: int + :ivar weight: The weight value for this SRV record. + :vartype weight: int + :ivar port: The port value for this SRV record. + :vartype port: int + :ivar target: The target domain name for this SRV record. + :vartype target: str """ _attribute_map = { - 'priority': {'key': 'priority', 'type': 'int'}, - 'weight': {'key': 'weight', 'type': 'int'}, - 'port': {'key': 'port', 'type': 'int'}, - 'target': {'key': 'target', 'type': 'str'}, + "priority": {"key": "priority", "type": "int"}, + "weight": {"key": "weight", "type": "int"}, + "port": {"key": "port", "type": "int"}, + "target": {"key": "target", "type": "str"}, } def __init__( @@ -447,38 +506,48 @@ def __init__( weight: Optional[int] = None, port: Optional[int] = None, target: Optional[str] = None, - **kwargs - ): - super(SrvRecord, self).__init__(**kwargs) + **kwargs: Any + ) -> None: + """ + :keyword priority: The priority value for this SRV record. + :paramtype priority: int + :keyword weight: The weight value for this SRV record. + :paramtype weight: int + :keyword port: The port value for this SRV record. + :paramtype port: int + :keyword target: The target domain name for this SRV record. + :paramtype target: str + """ + super().__init__(**kwargs) self.priority = priority self.weight = weight self.port = port self.target = target -class SubResource(msrest.serialization.Model): +class SubResource(_serialization.Model): """SubResource. - :param id: Resource Id. - :type id: str + :ivar id: Resource Id. + :vartype id: str """ _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, + "id": {"key": "id", "type": "str"}, } - def __init__( - self, - *, - id: Optional[str] = None, - **kwargs - ): - super(SubResource, self).__init__(**kwargs) + def __init__(self, *, id: Optional[str] = None, **kwargs: Any) -> None: # pylint: disable=redefined-builtin + """ + :keyword id: Resource Id. + :paramtype id: str + """ + super().__init__(**kwargs) self.id = id class TrackedResource(Resource): - """The resource model definition for an Azure Resource Manager tracked top level resource which has 'tags' and a 'location'. + """The resource model definition for an Azure Resource Manager tracked top level resource which + has 'tags' and a 'location'. Variables are only populated by the server, and will be ignored when sending a request. @@ -492,61 +561,60 @@ class TrackedResource(Resource): :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts". :vartype type: str - :param tags: A set of tags. Resource tags. - :type tags: dict[str, str] - :param location: Required. The geo-location where the resource lives. - :type location: str + :ivar tags: Resource tags. + :vartype tags: dict[str, str] + :ivar location: The geo-location where the resource lives. Required. + :vartype location: str """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'location': {'required': True}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "location": {"required": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'tags': {'key': 'tags', 'type': '{str}'}, - 'location': {'key': 'location', 'type': 'str'}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "tags": {"key": "tags", "type": "{str}"}, + "location": {"key": "location", "type": "str"}, } - def __init__( - self, - *, - location: str, - tags: Optional[Dict[str, str]] = None, - **kwargs - ): - super(TrackedResource, self).__init__(**kwargs) + def __init__(self, *, location: str, tags: Optional[Dict[str, str]] = None, **kwargs: Any) -> None: + """ + :keyword tags: Resource tags. + :paramtype tags: dict[str, str] + :keyword location: The geo-location where the resource lives. Required. + :paramtype location: str + """ + super().__init__(**kwargs) self.tags = tags self.location = location -class TxtRecord(msrest.serialization.Model): +class TxtRecord(_serialization.Model): """A TXT record. - :param value: The text value of this TXT record. - :type value: list[str] + :ivar value: The text value of this TXT record. + :vartype value: list[str] """ _attribute_map = { - 'value': {'key': 'value', 'type': '[str]'}, + "value": {"key": "value", "type": "[str]"}, } - def __init__( - self, - *, - value: Optional[List[str]] = None, - **kwargs - ): - super(TxtRecord, self).__init__(**kwargs) + def __init__(self, *, value: Optional[List[str]] = None, **kwargs: Any) -> None: + """ + :keyword value: The text value of this TXT record. + :paramtype value: list[str] + """ + super().__init__(**kwargs) self.value = value -class Zone(TrackedResource): +class Zone(TrackedResource): # pylint: disable=too-many-instance-attributes """Describes a DNS zone. Variables are only populated by the server, and will be ignored when sending a request. @@ -561,51 +629,51 @@ class Zone(TrackedResource): :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts". :vartype type: str - :param tags: A set of tags. Resource tags. - :type tags: dict[str, str] - :param location: Required. The geo-location where the resource lives. - :type location: str - :param etag: The etag of the zone. - :type etag: str - :param max_number_of_record_sets: The maximum number of record sets that can be created in this + :ivar tags: Resource tags. + :vartype tags: dict[str, str] + :ivar location: The geo-location where the resource lives. Required. + :vartype location: str + :ivar etag: The etag of the zone. + :vartype etag: str + :ivar max_number_of_record_sets: The maximum number of record sets that can be created in this DNS zone. This is a read-only property and any attempt to set this value will be ignored. - :type max_number_of_record_sets: long + :vartype max_number_of_record_sets: int :ivar max_number_of_records_per_record_set: The maximum number of records per record set that can be created in this DNS zone. This is a read-only property and any attempt to set this value will be ignored. - :vartype max_number_of_records_per_record_set: long - :param number_of_record_sets: The current number of record sets in this DNS zone. This is a + :vartype max_number_of_records_per_record_set: int + :ivar number_of_record_sets: The current number of record sets in this DNS zone. This is a read-only property and any attempt to set this value will be ignored. - :type number_of_record_sets: long + :vartype number_of_record_sets: int :ivar name_servers: The name servers for this DNS zone. This is a read-only property and any attempt to set this value will be ignored. :vartype name_servers: list[str] - :param zone_type: The type of this DNS zone (Public or Private). Possible values include: - "Public", "Private". Default value: "Public". - :type zone_type: str or ~azure.mgmt.dns.v2016_04_01.models.ZoneType + :ivar zone_type: The type of this DNS zone (Public or Private). Known values are: "Public" and + "Private". + :vartype zone_type: str or ~azure.mgmt.dns.v2016_04_01.models.ZoneType """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'location': {'required': True}, - 'max_number_of_records_per_record_set': {'readonly': True}, - 'name_servers': {'readonly': True}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "location": {"required": True}, + "max_number_of_records_per_record_set": {"readonly": True}, + "name_servers": {"readonly": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'tags': {'key': 'tags', 'type': '{str}'}, - 'location': {'key': 'location', 'type': 'str'}, - 'etag': {'key': 'etag', 'type': 'str'}, - 'max_number_of_record_sets': {'key': 'properties.maxNumberOfRecordSets', 'type': 'long'}, - 'max_number_of_records_per_record_set': {'key': 'properties.maxNumberOfRecordsPerRecordSet', 'type': 'long'}, - 'number_of_record_sets': {'key': 'properties.numberOfRecordSets', 'type': 'long'}, - 'name_servers': {'key': 'properties.nameServers', 'type': '[str]'}, - 'zone_type': {'key': 'properties.zoneType', 'type': 'str'}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "tags": {"key": "tags", "type": "{str}"}, + "location": {"key": "location", "type": "str"}, + "etag": {"key": "etag", "type": "str"}, + "max_number_of_record_sets": {"key": "properties.maxNumberOfRecordSets", "type": "int"}, + "max_number_of_records_per_record_set": {"key": "properties.maxNumberOfRecordsPerRecordSet", "type": "int"}, + "number_of_record_sets": {"key": "properties.numberOfRecordSets", "type": "int"}, + "name_servers": {"key": "properties.nameServers", "type": "[str]"}, + "zone_type": {"key": "properties.zoneType", "type": "str"}, } def __init__( @@ -616,10 +684,27 @@ def __init__( etag: Optional[str] = None, max_number_of_record_sets: Optional[int] = None, number_of_record_sets: Optional[int] = None, - zone_type: Optional[Union[str, "ZoneType"]] = "Public", - **kwargs - ): - super(Zone, self).__init__(tags=tags, location=location, **kwargs) + zone_type: Union[str, "_models.ZoneType"] = "Public", + **kwargs: Any + ) -> None: + """ + :keyword tags: Resource tags. + :paramtype tags: dict[str, str] + :keyword location: The geo-location where the resource lives. Required. + :paramtype location: str + :keyword etag: The etag of the zone. + :paramtype etag: str + :keyword max_number_of_record_sets: The maximum number of record sets that can be created in + this DNS zone. This is a read-only property and any attempt to set this value will be ignored. + :paramtype max_number_of_record_sets: int + :keyword number_of_record_sets: The current number of record sets in this DNS zone. This is a + read-only property and any attempt to set this value will be ignored. + :paramtype number_of_record_sets: int + :keyword zone_type: The type of this DNS zone (Public or Private). Known values are: "Public" + and "Private". + :paramtype zone_type: str or ~azure.mgmt.dns.v2016_04_01.models.ZoneType + """ + super().__init__(tags=tags, location=location, **kwargs) self.etag = etag self.max_number_of_record_sets = max_number_of_record_sets self.max_number_of_records_per_record_set = None @@ -628,74 +713,95 @@ def __init__( self.zone_type = zone_type -class ZoneDeleteResult(msrest.serialization.Model): +class ZoneDeleteResult(_serialization.Model): """The response to a Zone Delete operation. - :param azure_async_operation: Users can perform a Get on Azure-AsyncOperation to get the status + :ivar azure_async_operation: Users can perform a Get on Azure-AsyncOperation to get the status of their delete Zone operations. - :type azure_async_operation: str - :param status: Possible values include: "InProgress", "Succeeded", "Failed". - :type status: str or ~azure.mgmt.dns.v2016_04_01.models.OperationStatus - :param status_code: Possible values include: "Continue", "SwitchingProtocols", "OK", - "Created", "Accepted", "NonAuthoritativeInformation", "NoContent", "ResetContent", - "PartialContent", "MultipleChoices", "Ambiguous", "MovedPermanently", "Moved", "Found", - "Redirect", "SeeOther", "RedirectMethod", "NotModified", "UseProxy", "Unused", - "TemporaryRedirect", "RedirectKeepVerb", "BadRequest", "Unauthorized", "PaymentRequired", - "Forbidden", "NotFound", "MethodNotAllowed", "NotAcceptable", "ProxyAuthenticationRequired", - "RequestTimeout", "Conflict", "Gone", "LengthRequired", "PreconditionFailed", - "RequestEntityTooLarge", "RequestUriTooLong", "UnsupportedMediaType", - "RequestedRangeNotSatisfiable", "ExpectationFailed", "UpgradeRequired", "InternalServerError", - "NotImplemented", "BadGateway", "ServiceUnavailable", "GatewayTimeout", - "HttpVersionNotSupported". - :type status_code: str or ~azure.mgmt.dns.v2016_04_01.models.HttpStatusCode - :param request_id: - :type request_id: str + :vartype azure_async_operation: str + :ivar status: Known values are: "InProgress", "Succeeded", and "Failed". + :vartype status: str or ~azure.mgmt.dns.v2016_04_01.models.OperationStatus + :ivar status_code: Known values are: "Continue", "SwitchingProtocols", "OK", "Created", + "Accepted", "NonAuthoritativeInformation", "NoContent", "ResetContent", "PartialContent", + "MultipleChoices", "Ambiguous", "MovedPermanently", "Moved", "Found", "Redirect", "SeeOther", + "RedirectMethod", "NotModified", "UseProxy", "Unused", "TemporaryRedirect", "RedirectKeepVerb", + "BadRequest", "Unauthorized", "PaymentRequired", "Forbidden", "NotFound", "MethodNotAllowed", + "NotAcceptable", "ProxyAuthenticationRequired", "RequestTimeout", "Conflict", "Gone", + "LengthRequired", "PreconditionFailed", "RequestEntityTooLarge", "RequestUriTooLong", + "UnsupportedMediaType", "RequestedRangeNotSatisfiable", "ExpectationFailed", "UpgradeRequired", + "InternalServerError", "NotImplemented", "BadGateway", "ServiceUnavailable", "GatewayTimeout", + and "HttpVersionNotSupported". + :vartype status_code: str or ~azure.mgmt.dns.v2016_04_01.models.HttpStatusCode + :ivar request_id: + :vartype request_id: str """ _attribute_map = { - 'azure_async_operation': {'key': 'azureAsyncOperation', 'type': 'str'}, - 'status': {'key': 'status', 'type': 'str'}, - 'status_code': {'key': 'statusCode', 'type': 'str'}, - 'request_id': {'key': 'requestId', 'type': 'str'}, + "azure_async_operation": {"key": "azureAsyncOperation", "type": "str"}, + "status": {"key": "status", "type": "str"}, + "status_code": {"key": "statusCode", "type": "str"}, + "request_id": {"key": "requestId", "type": "str"}, } def __init__( self, *, azure_async_operation: Optional[str] = None, - status: Optional[Union[str, "OperationStatus"]] = None, - status_code: Optional[Union[str, "HttpStatusCode"]] = None, + status: Optional[Union[str, "_models.OperationStatus"]] = None, + status_code: Optional[Union[str, "_models.HttpStatusCode"]] = None, request_id: Optional[str] = None, - **kwargs - ): - super(ZoneDeleteResult, self).__init__(**kwargs) + **kwargs: Any + ) -> None: + """ + :keyword azure_async_operation: Users can perform a Get on Azure-AsyncOperation to get the + status of their delete Zone operations. + :paramtype azure_async_operation: str + :keyword status: Known values are: "InProgress", "Succeeded", and "Failed". + :paramtype status: str or ~azure.mgmt.dns.v2016_04_01.models.OperationStatus + :keyword status_code: Known values are: "Continue", "SwitchingProtocols", "OK", "Created", + "Accepted", "NonAuthoritativeInformation", "NoContent", "ResetContent", "PartialContent", + "MultipleChoices", "Ambiguous", "MovedPermanently", "Moved", "Found", "Redirect", "SeeOther", + "RedirectMethod", "NotModified", "UseProxy", "Unused", "TemporaryRedirect", "RedirectKeepVerb", + "BadRequest", "Unauthorized", "PaymentRequired", "Forbidden", "NotFound", "MethodNotAllowed", + "NotAcceptable", "ProxyAuthenticationRequired", "RequestTimeout", "Conflict", "Gone", + "LengthRequired", "PreconditionFailed", "RequestEntityTooLarge", "RequestUriTooLong", + "UnsupportedMediaType", "RequestedRangeNotSatisfiable", "ExpectationFailed", "UpgradeRequired", + "InternalServerError", "NotImplemented", "BadGateway", "ServiceUnavailable", "GatewayTimeout", + and "HttpVersionNotSupported". + :paramtype status_code: str or ~azure.mgmt.dns.v2016_04_01.models.HttpStatusCode + :keyword request_id: + :paramtype request_id: str + """ + super().__init__(**kwargs) self.azure_async_operation = azure_async_operation self.status = status self.status_code = status_code self.request_id = request_id -class ZoneListResult(msrest.serialization.Model): +class ZoneListResult(_serialization.Model): """The response to a Zone List or ListAll operation. - :param value: Information about the DNS zones. - :type value: list[~azure.mgmt.dns.v2016_04_01.models.Zone] - :param next_link: The continuation token for the next page of results. - :type next_link: str + :ivar value: Information about the DNS zones. + :vartype value: list[~azure.mgmt.dns.v2016_04_01.models.Zone] + :ivar next_link: The continuation token for the next page of results. + :vartype next_link: str """ _attribute_map = { - 'value': {'key': 'value', 'type': '[Zone]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "value": {"key": "value", "type": "[Zone]"}, + "next_link": {"key": "nextLink", "type": "str"}, } def __init__( - self, - *, - value: Optional[List["Zone"]] = None, - next_link: Optional[str] = None, - **kwargs - ): - super(ZoneListResult, self).__init__(**kwargs) + self, *, value: Optional[List["_models.Zone"]] = None, next_link: Optional[str] = None, **kwargs: Any + ) -> None: + """ + :keyword value: Information about the DNS zones. + :paramtype value: list[~azure.mgmt.dns.v2016_04_01.models.Zone] + :keyword next_link: The continuation token for the next page of results. + :paramtype next_link: str + """ + super().__init__(**kwargs) self.value = value self.next_link = next_link diff --git a/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2016_04_01/models/_patch.py b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2016_04_01/models/_patch.py new file mode 100644 index 000000000000..f7dd32510333 --- /dev/null +++ b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2016_04_01/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/network/azure-mgmt-dns/azure/mgmt/dns/v2016_04_01/operations/__init__.py b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2016_04_01/operations/__init__.py index caab83d882c4..c12bcc6610ed 100644 --- a/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2016_04_01/operations/__init__.py +++ b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2016_04_01/operations/__init__.py @@ -9,7 +9,13 @@ from ._record_sets_operations import RecordSetsOperations from ._zones_operations import ZonesOperations +from ._patch import __all__ as _patch_all +from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import patch_sdk as _patch_sdk + __all__ = [ - 'RecordSetsOperations', - 'ZonesOperations', + "RecordSetsOperations", + "ZonesOperations", ] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2016_04_01/operations/_patch.py b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2016_04_01/operations/_patch.py new file mode 100644 index 000000000000..f7dd32510333 --- /dev/null +++ b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2016_04_01/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/network/azure-mgmt-dns/azure/mgmt/dns/v2016_04_01/operations/_record_sets_operations.py b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2016_04_01/operations/_record_sets_operations.py index 932e496155e1..a7d7cf763ed9 100644 --- a/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2016_04_01/operations/_record_sets_operations.py +++ b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2016_04_01/operations/_record_sets_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,203 +6,702 @@ # 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 TYPE_CHECKING -import warnings - -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 HttpRequest, HttpResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from ..._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_update_request( + resource_group_name: str, + zone_name: str, + relative_record_set_name: str, + record_type: Union[str, _models.RecordType], + subscription_id: str, + *, + if_match: Optional[str] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-04-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-04-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}/{recordType}/{relativeRecordSetName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "zoneName": _SERIALIZER.url("zone_name", zone_name, "str"), + "relativeRecordSetName": _SERIALIZER.url( + "relative_record_set_name", relative_record_set_name, "str", skip_quote=True + ), + "recordType": _SERIALIZER.url("record_type", record_type, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if if_match is not None: + _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_create_or_update_request( + resource_group_name: str, + zone_name: str, + relative_record_set_name: str, + record_type: Union[str, _models.RecordType], + subscription_id: str, + *, + if_match: Optional[str] = None, + if_none_match: Optional[str] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-04-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-04-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}/{recordType}/{relativeRecordSetName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "zoneName": _SERIALIZER.url("zone_name", zone_name, "str"), + "relativeRecordSetName": _SERIALIZER.url( + "relative_record_set_name", relative_record_set_name, "str", skip_quote=True + ), + "recordType": _SERIALIZER.url("record_type", record_type, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if if_match is not None: + _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") + if if_none_match is not None: + _headers["If-None-Match"] = _SERIALIZER.header("if_none_match", if_none_match, "str") + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_delete_request( + resource_group_name: str, + zone_name: str, + relative_record_set_name: str, + record_type: Union[str, _models.RecordType], + subscription_id: str, + *, + if_match: Optional[str] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-04-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-04-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}/{recordType}/{relativeRecordSetName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "zoneName": _SERIALIZER.url("zone_name", zone_name, "str"), + "relativeRecordSetName": _SERIALIZER.url( + "relative_record_set_name", relative_record_set_name, "str", skip_quote=True + ), + "recordType": _SERIALIZER.url("record_type", record_type, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if if_match is not None: + _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") + _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, + zone_name: str, + relative_record_set_name: str, + record_type: Union[str, _models.RecordType], + subscription_id: str, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-04-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-04-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}/{recordType}/{relativeRecordSetName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "zoneName": _SERIALIZER.url("zone_name", zone_name, "str"), + "relativeRecordSetName": _SERIALIZER.url( + "relative_record_set_name", relative_record_set_name, "str", skip_quote=True + ), + "recordType": _SERIALIZER.url("record_type", record_type, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_by_type_request( + resource_group_name: str, + zone_name: str, + record_type: Union[str, _models.RecordType], + subscription_id: str, + *, + top: Optional[int] = None, + recordsetnamesuffix: Optional[str] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-04-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-04-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}/{recordType}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "zoneName": _SERIALIZER.url("zone_name", zone_name, "str"), + "recordType": _SERIALIZER.url("record_type", record_type, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + if top is not None: + _params["$top"] = _SERIALIZER.query("top", top, "int") + if recordsetnamesuffix is not None: + _params["$recordsetnamesuffix"] = _SERIALIZER.query("recordsetnamesuffix", recordsetnamesuffix, "str") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_by_dns_zone_request( + resource_group_name: str, + zone_name: str, + subscription_id: str, + *, + top: Optional[int] = None, + recordsetnamesuffix: Optional[str] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-04-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-04-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}/recordsets", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "zoneName": _SERIALIZER.url("zone_name", zone_name, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + if top is not None: + _params["$top"] = _SERIALIZER.query("top", top, "int") + if recordsetnamesuffix is not None: + _params["$recordsetnamesuffix"] = _SERIALIZER.query("recordsetnamesuffix", recordsetnamesuffix, "str") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class RecordSetsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar, Union + Instead, you should access the following operations through + :class:`~azure.mgmt.dns.v2016_04_01.DnsManagementClient`'s + :attr:`record_sets` attribute. + """ - T = TypeVar('T') - ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + models = _models -class RecordSetsOperations(object): - """RecordSetsOperations operations. + 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") - 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. + @overload + def update( + self, + resource_group_name: str, + zone_name: str, + relative_record_set_name: str, + record_type: Union[str, _models.RecordType], + parameters: _models.RecordSet, + if_match: Optional[str] = None, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RecordSet: + """Updates a record set within a DNS zone. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.dns.v2016_04_01.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. - """ + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param zone_name: The name of the DNS zone (without a terminating dot). Required. + :type zone_name: str + :param relative_record_set_name: The name of the record set, relative to the name of the zone. + Required. + :type relative_record_set_name: str + :param record_type: The type of DNS record in this record set. Known values are: "A", "AAAA", + "CNAME", "MX", "NS", "PTR", "SOA", "SRV", and "TXT". Required. + :type record_type: str or ~azure.mgmt.dns.v2016_04_01.models.RecordType + :param parameters: Parameters supplied to the Update operation. Required. + :type parameters: ~azure.mgmt.dns.v2016_04_01.models.RecordSet + :param if_match: The etag of the record set. Omit this value to always overwrite the current + record set. Specify the last-seen etag value to prevent accidentally overwriting concurrent + changes. 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: RecordSet or the result of cls(response) + :rtype: ~azure.mgmt.dns.v2016_04_01.models.RecordSet + :raises ~azure.core.exceptions.HttpResponseError: + """ - models = _models + @overload + def update( + self, + resource_group_name: str, + zone_name: str, + relative_record_set_name: str, + record_type: Union[str, _models.RecordType], + parameters: IO, + if_match: Optional[str] = None, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RecordSet: + """Updates a record set within a DNS zone. - def __init__(self, client, config, serializer, deserializer): - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param zone_name: The name of the DNS zone (without a terminating dot). Required. + :type zone_name: str + :param relative_record_set_name: The name of the record set, relative to the name of the zone. + Required. + :type relative_record_set_name: str + :param record_type: The type of DNS record in this record set. Known values are: "A", "AAAA", + "CNAME", "MX", "NS", "PTR", "SOA", "SRV", and "TXT". Required. + :type record_type: str or ~azure.mgmt.dns.v2016_04_01.models.RecordType + :param parameters: Parameters supplied to the Update operation. Required. + :type parameters: IO + :param if_match: The etag of the record set. Omit this value to always overwrite the current + record set. Specify the last-seen etag value to prevent accidentally overwriting concurrent + changes. 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: RecordSet or the result of cls(response) + :rtype: ~azure.mgmt.dns.v2016_04_01.models.RecordSet + :raises ~azure.core.exceptions.HttpResponseError: + """ + @distributed_trace def update( self, - resource_group_name, # type: str - zone_name, # type: str - relative_record_set_name, # type: str - record_type, # type: Union[str, "_models.RecordType"] - parameters, # type: "_models.RecordSet" - if_match=None, # type: Optional[str] - **kwargs # type: Any - ): - # type: (...) -> "_models.RecordSet" + resource_group_name: str, + zone_name: str, + relative_record_set_name: str, + record_type: Union[str, _models.RecordType], + parameters: Union[_models.RecordSet, IO], + if_match: Optional[str] = None, + **kwargs: Any + ) -> _models.RecordSet: """Updates a record set within a DNS zone. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param zone_name: The name of the DNS zone (without a terminating dot). + :param zone_name: The name of the DNS zone (without a terminating dot). Required. :type zone_name: str :param relative_record_set_name: The name of the record set, relative to the name of the zone. + Required. :type relative_record_set_name: str - :param record_type: The type of DNS record in this record set. + :param record_type: The type of DNS record in this record set. Known values are: "A", "AAAA", + "CNAME", "MX", "NS", "PTR", "SOA", "SRV", and "TXT". Required. :type record_type: str or ~azure.mgmt.dns.v2016_04_01.models.RecordType - :param parameters: Parameters supplied to the Update operation. - :type parameters: ~azure.mgmt.dns.v2016_04_01.models.RecordSet + :param parameters: Parameters supplied to the Update operation. Is either a RecordSet type or a + IO type. Required. + :type parameters: ~azure.mgmt.dns.v2016_04_01.models.RecordSet or IO :param if_match: The etag of the record set. Omit this value to always overwrite the current record set. Specify the last-seen etag value to prevent accidentally overwriting concurrent - changes. + changes. 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: RecordSet, or the result of cls(response) + :return: RecordSet or the result of cls(response) :rtype: ~azure.mgmt.dns.v2016_04_01.models.RecordSet - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RecordSet"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2016-04-01" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.update.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), - 'zoneName': self._serialize.url("zone_name", zone_name, 'str'), - 'relativeRecordSetName': self._serialize.url("relative_record_set_name", relative_record_set_name, 'str', skip_quote=True), - 'recordType': self._serialize.url("record_type", record_type, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - if if_match is not None: - header_parameters['If-Match'] = self._serialize.header("if_match", if_match, 'str') - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(parameters, 'RecordSet') - body_content_kwargs['content'] = body_content - request = self._client.patch(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + 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: Literal["2016-04-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-04-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.RecordSet] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "RecordSet") + + request = build_update_request( + resource_group_name=resource_group_name, + zone_name=zone_name, + relative_record_set_name=relative_record_set_name, + record_type=record_type, + subscription_id=self._config.subscription_id, + if_match=if_match, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.update.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = 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('RecordSet', pipeline_response) + deserialized = self._deserialize("RecordSet", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}/{recordType}/{relativeRecordSetName}'} # type: ignore + update.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}/{recordType}/{relativeRecordSetName}" + } + + @overload def create_or_update( self, - resource_group_name, # type: str - zone_name, # type: str - relative_record_set_name, # type: str - record_type, # type: Union[str, "_models.RecordType"] - parameters, # type: "_models.RecordSet" - if_match=None, # type: Optional[str] - if_none_match=None, # type: Optional[str] - **kwargs # type: Any - ): - # type: (...) -> "_models.RecordSet" + resource_group_name: str, + zone_name: str, + relative_record_set_name: str, + record_type: Union[str, _models.RecordType], + parameters: _models.RecordSet, + if_match: Optional[str] = None, + if_none_match: Optional[str] = None, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RecordSet: """Creates or updates a record set within a DNS zone. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param zone_name: The name of the DNS zone (without a terminating dot). + :param zone_name: The name of the DNS zone (without a terminating dot). Required. :type zone_name: str :param relative_record_set_name: The name of the record set, relative to the name of the zone. + Required. :type relative_record_set_name: str :param record_type: The type of DNS record in this record set. Record sets of type SOA can be - updated but not created (they are created when the DNS zone is created). + updated but not created (they are created when the DNS zone is created). Known values are: "A", + "AAAA", "CNAME", "MX", "NS", "PTR", "SOA", "SRV", and "TXT". Required. :type record_type: str or ~azure.mgmt.dns.v2016_04_01.models.RecordType - :param parameters: Parameters supplied to the CreateOrUpdate operation. + :param parameters: Parameters supplied to the CreateOrUpdate operation. Required. :type parameters: ~azure.mgmt.dns.v2016_04_01.models.RecordSet :param if_match: The etag of the record set. Omit this value to always overwrite the current record set. Specify the last-seen etag value to prevent accidentally overwriting any concurrent - changes. + changes. Default value is None. :type if_match: str :param if_none_match: Set to '*' to allow a new record set to be created, but to prevent - updating an existing record set. Other values will be ignored. + updating an existing record set. 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: RecordSet, or the result of cls(response) + :return: RecordSet or the result of cls(response) :rtype: ~azure.mgmt.dns.v2016_04_01.models.RecordSet - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_or_update( + self, + resource_group_name: str, + zone_name: str, + relative_record_set_name: str, + record_type: Union[str, _models.RecordType], + parameters: IO, + if_match: Optional[str] = None, + if_none_match: Optional[str] = None, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RecordSet: + """Creates or updates a record set within a DNS zone. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param zone_name: The name of the DNS zone (without a terminating dot). Required. + :type zone_name: str + :param relative_record_set_name: The name of the record set, relative to the name of the zone. + Required. + :type relative_record_set_name: str + :param record_type: The type of DNS record in this record set. Record sets of type SOA can be + updated but not created (they are created when the DNS zone is created). Known values are: "A", + "AAAA", "CNAME", "MX", "NS", "PTR", "SOA", "SRV", and "TXT". Required. + :type record_type: str or ~azure.mgmt.dns.v2016_04_01.models.RecordType + :param parameters: Parameters supplied to the CreateOrUpdate operation. Required. + :type parameters: IO + :param if_match: The etag of the record set. Omit this value to always overwrite the current + record set. Specify the last-seen etag value to prevent accidentally overwriting any concurrent + changes. Default value is None. + :type if_match: str + :param if_none_match: Set to '*' to allow a new record set to be created, but to prevent + updating an existing record set. 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: RecordSet or the result of cls(response) + :rtype: ~azure.mgmt.dns.v2016_04_01.models.RecordSet + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create_or_update( + self, + resource_group_name: str, + zone_name: str, + relative_record_set_name: str, + record_type: Union[str, _models.RecordType], + parameters: Union[_models.RecordSet, IO], + if_match: Optional[str] = None, + if_none_match: Optional[str] = None, + **kwargs: Any + ) -> _models.RecordSet: + """Creates or updates a record set within a DNS zone. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param zone_name: The name of the DNS zone (without a terminating dot). Required. + :type zone_name: str + :param relative_record_set_name: The name of the record set, relative to the name of the zone. + Required. + :type relative_record_set_name: str + :param record_type: The type of DNS record in this record set. Record sets of type SOA can be + updated but not created (they are created when the DNS zone is created). Known values are: "A", + "AAAA", "CNAME", "MX", "NS", "PTR", "SOA", "SRV", and "TXT". Required. + :type record_type: str or ~azure.mgmt.dns.v2016_04_01.models.RecordType + :param parameters: Parameters supplied to the CreateOrUpdate operation. Is either a RecordSet + type or a IO type. Required. + :type parameters: ~azure.mgmt.dns.v2016_04_01.models.RecordSet or IO + :param if_match: The etag of the record set. Omit this value to always overwrite the current + record set. Specify the last-seen etag value to prevent accidentally overwriting any concurrent + changes. Default value is None. + :type if_match: str + :param if_none_match: Set to '*' to allow a new record set to be created, but to prevent + updating an existing record set. 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: RecordSet or the result of cls(response) + :rtype: ~azure.mgmt.dns.v2016_04_01.models.RecordSet + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RecordSet"] 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 = "2016-04-01" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.create_or_update.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), - 'zoneName': self._serialize.url("zone_name", zone_name, 'str'), - 'relativeRecordSetName': self._serialize.url("relative_record_set_name", relative_record_set_name, 'str', skip_quote=True), - 'recordType': self._serialize.url("record_type", record_type, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - if if_match is not None: - header_parameters['If-Match'] = self._serialize.header("if_match", if_match, 'str') - if if_none_match is not None: - header_parameters['If-None-Match'] = self._serialize.header("if_none_match", if_none_match, 'str') - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(parameters, 'RecordSet') - body_content_kwargs['content'] = body_content - request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + 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: Literal["2016-04-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-04-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.RecordSet] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "RecordSet") + + request = build_create_or_update_request( + resource_group_name=resource_group_name, + zone_name=zone_name, + relative_record_set_name=relative_record_set_name, + record_type=record_type, + subscription_id=self._config.subscription_id, + if_match=if_match, + if_none_match=if_none_match, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create_or_update.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response if response.status_code not in [200, 201]: @@ -209,78 +709,86 @@ def create_or_update( raise HttpResponseError(response=response, error_format=ARMErrorFormat) if response.status_code == 200: - deserialized = self._deserialize('RecordSet', pipeline_response) + deserialized = self._deserialize("RecordSet", pipeline_response) if response.status_code == 201: - deserialized = self._deserialize('RecordSet', pipeline_response) + deserialized = self._deserialize("RecordSet", pipeline_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}/{recordType}/{relativeRecordSetName}'} # type: ignore + return deserialized # type: ignore - def delete( + create_or_update.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}/{recordType}/{relativeRecordSetName}" + } + + @distributed_trace + def delete( # pylint: disable=inconsistent-return-statements self, - resource_group_name, # type: str - zone_name, # type: str - relative_record_set_name, # type: str - record_type, # type: Union[str, "_models.RecordType"] - if_match=None, # type: Optional[str] - **kwargs # type: Any - ): - # type: (...) -> None + resource_group_name: str, + zone_name: str, + relative_record_set_name: str, + record_type: Union[str, _models.RecordType], + if_match: Optional[str] = None, + **kwargs: Any + ) -> None: """Deletes a record set from a DNS zone. This operation cannot be undone. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param zone_name: The name of the DNS zone (without a terminating dot). + :param zone_name: The name of the DNS zone (without a terminating dot). Required. :type zone_name: str :param relative_record_set_name: The name of the record set, relative to the name of the zone. + Required. :type relative_record_set_name: str :param record_type: The type of DNS record in this record set. Record sets of type SOA cannot - be deleted (they are deleted when the DNS zone is deleted). + be deleted (they are deleted when the DNS zone is deleted). Known values are: "A", "AAAA", + "CNAME", "MX", "NS", "PTR", "SOA", "SRV", and "TXT". Required. :type record_type: str or ~azure.mgmt.dns.v2016_04_01.models.RecordType :param if_match: The etag of the record set. Omit this value to always delete the current record set. Specify the last-seen etag value to prevent accidentally deleting any concurrent - changes. + changes. Default value is None. :type if_match: 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 - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2016-04-01" - accept = "application/json" - - # Construct URL - url = self.delete.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), - 'zoneName': self._serialize.url("zone_name", zone_name, 'str'), - 'relativeRecordSetName': self._serialize.url("relative_record_set_name", relative_record_set_name, 'str', skip_quote=True), - 'recordType': self._serialize.url("record_type", record_type, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-04-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-04-01")) + cls: ClsType[None] = kwargs.pop("cls", None) + + request = build_delete_request( + resource_group_name=resource_group_name, + zone_name=zone_name, + relative_record_set_name=relative_record_set_name, + record_type=record_type, + subscription_id=self._config.subscription_id, + if_match=if_match, + api_version=api_version, + template_url=self.delete.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) - # Construct headers - header_parameters = {} # type: Dict[str, Any] - if if_match is not None: - header_parameters['If-Match'] = self._serialize.header("if_match", if_match, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.delete(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 204]: @@ -290,154 +798,181 @@ def delete( if cls: return cls(pipeline_response, None, {}) - delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}/{recordType}/{relativeRecordSetName}'} # type: ignore + delete.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}/{recordType}/{relativeRecordSetName}" + } + @distributed_trace def get( self, - resource_group_name, # type: str - zone_name, # type: str - relative_record_set_name, # type: str - record_type, # type: Union[str, "_models.RecordType"] - **kwargs # type: Any - ): - # type: (...) -> "_models.RecordSet" + resource_group_name: str, + zone_name: str, + relative_record_set_name: str, + record_type: Union[str, _models.RecordType], + **kwargs: Any + ) -> _models.RecordSet: """Gets a record set. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param zone_name: The name of the DNS zone (without a terminating dot). + :param zone_name: The name of the DNS zone (without a terminating dot). Required. :type zone_name: str :param relative_record_set_name: The name of the record set, relative to the name of the zone. + Required. :type relative_record_set_name: str - :param record_type: The type of DNS record in this record set. + :param record_type: The type of DNS record in this record set. Known values are: "A", "AAAA", + "CNAME", "MX", "NS", "PTR", "SOA", "SRV", and "TXT". Required. :type record_type: str or ~azure.mgmt.dns.v2016_04_01.models.RecordType :keyword callable cls: A custom type or function that will be passed the direct response - :return: RecordSet, or the result of cls(response) + :return: RecordSet or the result of cls(response) :rtype: ~azure.mgmt.dns.v2016_04_01.models.RecordSet - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RecordSet"] 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 = "2016-04-01" - accept = "application/json" - - # Construct URL - url = self.get.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), - 'zoneName': self._serialize.url("zone_name", zone_name, 'str'), - 'relativeRecordSetName': self._serialize.url("relative_record_set_name", relative_record_set_name, 'str', skip_quote=True), - 'recordType': self._serialize.url("record_type", record_type, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-04-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-04-01")) + cls: ClsType[_models.RecordSet] = kwargs.pop("cls", None) + + request = build_get_request( + resource_group_name=resource_group_name, + zone_name=zone_name, + relative_record_set_name=relative_record_set_name, + record_type=record_type, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('RecordSet', pipeline_response) + deserialized = self._deserialize("RecordSet", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}/{recordType}/{relativeRecordSetName}'} # type: ignore + get.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}/{recordType}/{relativeRecordSetName}" + } + + @distributed_trace def list_by_type( self, - resource_group_name, # type: str - zone_name, # type: str - record_type, # type: Union[str, "_models.RecordType"] - top=None, # type: Optional[int] - recordsetnamesuffix=None, # type: Optional[str] - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.RecordSetListResult"] + resource_group_name: str, + zone_name: str, + record_type: Union[str, _models.RecordType], + top: Optional[int] = None, + recordsetnamesuffix: Optional[str] = None, + **kwargs: Any + ) -> Iterable["_models.RecordSet"]: """Lists the record sets of a specified type in a DNS zone. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param zone_name: The name of the DNS zone (without a terminating dot). + :param zone_name: The name of the DNS zone (without a terminating dot). Required. :type zone_name: str - :param record_type: The type of record sets to enumerate. + :param record_type: The type of record sets to enumerate. Known values are: "A", "AAAA", + "CNAME", "MX", "NS", "PTR", "SOA", "SRV", and "TXT". Required. :type record_type: str or ~azure.mgmt.dns.v2016_04_01.models.RecordType :param top: The maximum number of record sets to return. If not specified, returns up to 100 - record sets. + record sets. Default value is None. :type top: int :param recordsetnamesuffix: The suffix label of the record set name that has to be used to filter the record set enumerations. If this parameter is specified, Enumeration will return - only records that end with .:code:``. + only records that end with .:code:``. Default value is None. :type recordsetnamesuffix: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either RecordSetListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.dns.v2016_04_01.models.RecordSetListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either RecordSet or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.dns.v2016_04_01.models.RecordSet] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RecordSetListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-04-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-04-01")) + cls: ClsType[_models.RecordSetListResult] = kwargs.pop("cls", None) + 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 = "2016-04-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_by_type.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), - 'zoneName': self._serialize.url("zone_name", zone_name, 'str'), - 'recordType': self._serialize.url("record_type", record_type, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - if top is not None: - query_parameters['$top'] = self._serialize.query("top", top, 'int') - if recordsetnamesuffix is not None: - query_parameters['$recordsetnamesuffix'] = self._serialize.query("recordsetnamesuffix", recordsetnamesuffix, 'str') - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_by_type_request( + resource_group_name=resource_group_name, + zone_name=zone_name, + record_type=record_type, + subscription_id=self._config.subscription_id, + top=top, + recordsetnamesuffix=recordsetnamesuffix, + api_version=api_version, + template_url=self.list_by_type.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('RecordSetListResult', pipeline_response) + deserialized = self._deserialize("RecordSetListResult", pipeline_response) list_of_elem = deserialized.value if cls: - list_of_elem = cls(list_of_elem) + list_of_elem = cls(list_of_elem) # type: ignore return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: @@ -446,86 +981,102 @@ def get_next(next_link=None): return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list_by_type.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}/{recordType}'} # type: ignore + return ItemPaged(get_next, extract_data) + + list_by_type.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}/{recordType}" + } + @distributed_trace def list_by_dns_zone( self, - resource_group_name, # type: str - zone_name, # type: str - top=None, # type: Optional[int] - recordsetnamesuffix=None, # type: Optional[str] - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.RecordSetListResult"] + resource_group_name: str, + zone_name: str, + top: Optional[int] = None, + recordsetnamesuffix: Optional[str] = None, + **kwargs: Any + ) -> Iterable["_models.RecordSet"]: """Lists all record sets in a DNS zone. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param zone_name: The name of the DNS zone (without a terminating dot). + :param zone_name: The name of the DNS zone (without a terminating dot). Required. :type zone_name: str :param top: The maximum number of record sets to return. If not specified, returns up to 100 - record sets. + record sets. Default value is None. :type top: int :param recordsetnamesuffix: The suffix label of the record set name that has to be used to filter the record set enumerations. If this parameter is specified, Enumeration will return - only records that end with .:code:``. + only records that end with .:code:``. Default value is None. :type recordsetnamesuffix: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either RecordSetListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.dns.v2016_04_01.models.RecordSetListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either RecordSet or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.dns.v2016_04_01.models.RecordSet] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RecordSetListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-04-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-04-01")) + cls: ClsType[_models.RecordSetListResult] = kwargs.pop("cls", None) + 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 = "2016-04-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_by_dns_zone.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), - 'zoneName': self._serialize.url("zone_name", zone_name, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - if top is not None: - query_parameters['$top'] = self._serialize.query("top", top, 'int') - if recordsetnamesuffix is not None: - query_parameters['$recordsetnamesuffix'] = self._serialize.query("recordsetnamesuffix", recordsetnamesuffix, 'str') - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_by_dns_zone_request( + resource_group_name=resource_group_name, + zone_name=zone_name, + subscription_id=self._config.subscription_id, + top=top, + recordsetnamesuffix=recordsetnamesuffix, + api_version=api_version, + template_url=self.list_by_dns_zone.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('RecordSetListResult', pipeline_response) + deserialized = self._deserialize("RecordSetListResult", pipeline_response) list_of_elem = deserialized.value if cls: - list_of_elem = cls(list_of_elem) + list_of_elem = cls(list_of_elem) # type: ignore return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: @@ -534,7 +1085,8 @@ def get_next(next_link=None): return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list_by_dns_zone.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}/recordsets'} # type: ignore + return ItemPaged(get_next, extract_data) + + list_by_dns_zone.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}/recordsets" + } diff --git a/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2016_04_01/operations/_zones_operations.py b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2016_04_01/operations/_zones_operations.py index c7a184a37bdc..52583b5d412a 100644 --- a/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2016_04_01/operations/_zones_operations.py +++ b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2016_04_01/operations/_zones_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,114 +6,387 @@ # 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 TYPE_CHECKING -import warnings - -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 HttpRequest, HttpResponse +from azure.core.pipeline.transport import HttpResponse from azure.core.polling import LROPoller, NoPolling, PollingMethod +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.arm_polling import ARMPolling from .. import models as _models +from ..._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_create_or_update_request( + resource_group_name: str, + zone_name: str, + subscription_id: str, + *, + if_match: Optional[str] = None, + if_none_match: Optional[str] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-04-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-04-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "zoneName": _SERIALIZER.url("zone_name", zone_name, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if if_match is not None: + _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") + if if_none_match is not None: + _headers["If-None-Match"] = _SERIALIZER.header("if_none_match", if_none_match, "str") + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_delete_request( + resource_group_name: str, zone_name: str, subscription_id: str, *, if_match: Optional[str] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-04-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-04-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "zoneName": _SERIALIZER.url("zone_name", zone_name, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if if_match is not None: + _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") + _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, zone_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: Literal["2016-04-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-04-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "zoneName": _SERIALIZER.url("zone_name", zone_name, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_by_resource_group_request( + resource_group_name: str, subscription_id: str, *, top: Optional[int] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-04-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-04-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + if top is not None: + _params["$top"] = _SERIALIZER.query("top", top, "int") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_request(subscription_id: str, *, top: Optional[int] = None, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-04-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-04-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Network/dnszones") + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar, Union + # Construct parameters + if top is not None: + _params["$top"] = _SERIALIZER.query("top", top, "int") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - T = TypeVar('T') - ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") -class ZonesOperations(object): - """ZonesOperations operations. + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - 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.dns.v2016_04_01.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. +class ZonesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.dns.v2016_04_01.DnsManagementClient`'s + :attr:`zones` 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") + @overload def create_or_update( self, - resource_group_name, # type: str - zone_name, # type: str - parameters, # type: "_models.Zone" - if_match=None, # type: Optional[str] - if_none_match=None, # type: Optional[str] - **kwargs # type: Any - ): - # type: (...) -> "_models.Zone" + resource_group_name: str, + zone_name: str, + parameters: _models.Zone, + if_match: Optional[str] = None, + if_none_match: Optional[str] = None, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Zone: """Creates or updates a DNS zone. Does not modify DNS records within the zone. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param zone_name: The name of the DNS zone (without a terminating dot). + :param zone_name: The name of the DNS zone (without a terminating dot). Required. :type zone_name: str - :param parameters: Parameters supplied to the CreateOrUpdate operation. + :param parameters: Parameters supplied to the CreateOrUpdate operation. Required. :type parameters: ~azure.mgmt.dns.v2016_04_01.models.Zone :param if_match: The etag of the DNS zone. Omit this value to always overwrite the current zone. Specify the last-seen etag value to prevent accidentally overwriting any concurrent - changes. + changes. Default value is None. + :type if_match: str + :param if_none_match: Set to '*' to allow a new DNS zone to be created, but to prevent updating + an existing zone. 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: Zone or the result of cls(response) + :rtype: ~azure.mgmt.dns.v2016_04_01.models.Zone + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_or_update( + self, + resource_group_name: str, + zone_name: str, + parameters: IO, + if_match: Optional[str] = None, + if_none_match: Optional[str] = None, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Zone: + """Creates or updates a DNS zone. Does not modify DNS records within the zone. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param zone_name: The name of the DNS zone (without a terminating dot). Required. + :type zone_name: str + :param parameters: Parameters supplied to the CreateOrUpdate operation. Required. + :type parameters: IO + :param if_match: The etag of the DNS zone. Omit this value to always overwrite the current + zone. Specify the last-seen etag value to prevent accidentally overwriting any concurrent + changes. Default value is None. + :type if_match: str + :param if_none_match: Set to '*' to allow a new DNS zone to be created, but to prevent updating + an existing zone. 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: Zone or the result of cls(response) + :rtype: ~azure.mgmt.dns.v2016_04_01.models.Zone + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create_or_update( + self, + resource_group_name: str, + zone_name: str, + parameters: Union[_models.Zone, IO], + if_match: Optional[str] = None, + if_none_match: Optional[str] = None, + **kwargs: Any + ) -> _models.Zone: + """Creates or updates a DNS zone. Does not modify DNS records within the zone. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param zone_name: The name of the DNS zone (without a terminating dot). Required. + :type zone_name: str + :param parameters: Parameters supplied to the CreateOrUpdate operation. Is either a Zone type + or a IO type. Required. + :type parameters: ~azure.mgmt.dns.v2016_04_01.models.Zone or IO + :param if_match: The etag of the DNS zone. Omit this value to always overwrite the current + zone. Specify the last-seen etag value to prevent accidentally overwriting any concurrent + changes. Default value is None. :type if_match: str :param if_none_match: Set to '*' to allow a new DNS zone to be created, but to prevent updating - an existing zone. Other values will be ignored. + an existing zone. 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: Zone, or the result of cls(response) + :return: Zone or the result of cls(response) :rtype: ~azure.mgmt.dns.v2016_04_01.models.Zone - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Zone"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2016-04-01" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.create_or_update.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), - 'zoneName': self._serialize.url("zone_name", zone_name, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - if if_match is not None: - header_parameters['If-Match'] = self._serialize.header("if_match", if_match, 'str') - if if_none_match is not None: - header_parameters['If-None-Match'] = self._serialize.header("if_none_match", if_none_match, 'str') - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(parameters, 'Zone') - body_content_kwargs['content'] = body_content - request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + 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: Literal["2016-04-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-04-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.Zone] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "Zone") + + request = build_create_or_update_request( + resource_group_name=resource_group_name, + zone_name=zone_name, + subscription_id=self._config.subscription_id, + if_match=if_match, + if_none_match=if_none_match, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create_or_update.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response if response.status_code not in [200, 201]: @@ -120,54 +394,54 @@ def create_or_update( raise HttpResponseError(response=response, error_format=ARMErrorFormat) if response.status_code == 200: - deserialized = self._deserialize('Zone', pipeline_response) + deserialized = self._deserialize("Zone", pipeline_response) if response.status_code == 201: - deserialized = self._deserialize('Zone', pipeline_response) + deserialized = self._deserialize("Zone", pipeline_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}'} # type: ignore + return deserialized # type: ignore + + create_or_update.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}" + } def _delete_initial( - self, - resource_group_name, # type: str - zone_name, # type: str - if_match=None, # type: Optional[str] - **kwargs # type: Any - ): - # type: (...) -> Optional["_models.ZoneDeleteResult"] - cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.ZoneDeleteResult"]] + self, resource_group_name: str, zone_name: str, if_match: Optional[str] = None, **kwargs: Any + ) -> Optional[_models.ZoneDeleteResult]: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2016-04-01" - accept = "application/json" - - # Construct URL - url = self._delete_initial.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), - 'zoneName': self._serialize.url("zone_name", zone_name, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-04-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-04-01")) + cls: ClsType[Optional[_models.ZoneDeleteResult]] = kwargs.pop("cls", None) + + request = build_delete_request( + resource_group_name=resource_group_name, + zone_name=zone_name, + subscription_id=self._config.subscription_id, + if_match=if_match, + api_version=api_version, + template_url=self._delete_initial.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) - # Construct headers - header_parameters = {} # type: Dict[str, Any] - if if_match is not None: - header_parameters['If-Match'] = self._serialize.header("if_match", if_match, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.delete(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: @@ -176,211 +450,230 @@ def _delete_initial( deserialized = None if response.status_code == 200: - deserialized = self._deserialize('ZoneDeleteResult', pipeline_response) + deserialized = self._deserialize("ZoneDeleteResult", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - _delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}'} # type: ignore + _delete_initial.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}" + } + + @distributed_trace def begin_delete( - self, - resource_group_name, # type: str - zone_name, # type: str - if_match=None, # type: Optional[str] - **kwargs # type: Any - ): - # type: (...) -> LROPoller["_models.ZoneDeleteResult"] + self, resource_group_name: str, zone_name: str, if_match: Optional[str] = None, **kwargs: Any + ) -> LROPoller[_models.ZoneDeleteResult]: """Deletes a DNS zone. WARNING: All DNS records in the zone will also be deleted. This operation cannot be undone. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param zone_name: The name of the DNS zone (without a terminating dot). + :param zone_name: The name of the DNS zone (without a terminating dot). Required. :type zone_name: str :param if_match: The etag of the DNS zone. Omit this value to always delete the current zone. Specify the last-seen etag value to prevent accidentally deleting any concurrent changes. + Default value is None. :type if_match: 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: Pass in True if you'd like the ARMPolling polling method, - False for no polling, or your own initialized polling object for a personal polling strategy. + :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 ZoneDeleteResult or the result of cls(response) + :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 ZoneDeleteResult or the result of + cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.dns.v2016_04_01.models.ZoneDeleteResult] :raises ~azure.core.exceptions.HttpResponseError: """ - polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType["_models.ZoneDeleteResult"] - 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: Literal["2016-04-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-04-01")) + cls: ClsType[_models.ZoneDeleteResult] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) if cont_token is None: raw_result = self._delete_initial( resource_group_name=resource_group_name, zone_name=zone_name, if_match=if_match, - cls=lambda x,y,z: x, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - - kwargs.pop('error_map', None) - kwargs.pop('content_type', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - deserialized = self._deserialize('ZoneDeleteResult', pipeline_response) - + deserialized = self._deserialize("ZoneDeleteResult", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - path_format_arguments = { - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), - 'zoneName': self._serialize.url("zone_name", zone_name, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), - } - - if polling is True: polling_method = ARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) - elif polling is False: polling_method = NoPolling() - else: polling_method = polling + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - else: - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}'} # type: ignore + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - def get( - self, - resource_group_name, # type: str - zone_name, # type: str - **kwargs # type: Any - ): - # type: (...) -> "_models.Zone" + begin_delete.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}" + } + + @distributed_trace + def get(self, resource_group_name: str, zone_name: str, **kwargs: Any) -> _models.Zone: """Gets a DNS zone. Retrieves the zone properties, but not the record sets within the zone. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param zone_name: The name of the DNS zone (without a terminating dot). + :param zone_name: The name of the DNS zone (without a terminating dot). Required. :type zone_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: Zone, or the result of cls(response) + :return: Zone or the result of cls(response) :rtype: ~azure.mgmt.dns.v2016_04_01.models.Zone - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Zone"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2016-04-01" - accept = "application/json" - - # Construct URL - url = self.get.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), - 'zoneName': self._serialize.url("zone_name", zone_name, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-04-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-04-01")) + cls: ClsType[_models.Zone] = kwargs.pop("cls", None) + + request = build_get_request( + resource_group_name=resource_group_name, + zone_name=zone_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('Zone', pipeline_response) + deserialized = self._deserialize("Zone", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}'} # type: ignore + get.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}" + } + + @distributed_trace def list_by_resource_group( - self, - resource_group_name, # type: str - top=None, # type: Optional[int] - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.ZoneListResult"] + self, resource_group_name: str, top: Optional[int] = None, **kwargs: Any + ) -> Iterable["_models.Zone"]: """Lists the DNS zones within a resource group. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str :param top: The maximum number of record sets to return. If not specified, returns up to 100 - record sets. + record sets. Default value is None. :type top: int :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either ZoneListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.dns.v2016_04_01.models.ZoneListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either Zone or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.dns.v2016_04_01.models.Zone] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.ZoneListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-04-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-04-01")) + cls: ClsType[_models.ZoneListResult] = kwargs.pop("cls", None) + 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 = "2016-04-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_by_resource_group.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - if top is not None: - query_parameters['$top'] = self._serialize.query("top", top, 'int') - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_by_resource_group_request( + resource_group_name=resource_group_name, + subscription_id=self._config.subscription_id, + top=top, + api_version=api_version, + template_url=self.list_by_resource_group.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('ZoneListResult', pipeline_response) + deserialized = self._deserialize("ZoneListResult", pipeline_response) list_of_elem = deserialized.value if cls: - list_of_elem = cls(list_of_elem) + list_of_elem = cls(list_of_elem) # type: ignore return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: @@ -389,71 +682,83 @@ def get_next(next_link=None): return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list_by_resource_group.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones'} # type: ignore + return ItemPaged(get_next, extract_data) - def list( - self, - top=None, # type: Optional[int] - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.ZoneListResult"] + list_by_resource_group.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones" + } + + @distributed_trace + def list(self, top: Optional[int] = None, **kwargs: Any) -> Iterable["_models.Zone"]: """Lists the DNS zones in all resource groups in a subscription. :param top: The maximum number of DNS zones to return. If not specified, returns up to 100 - zones. + zones. Default value is None. :type top: int :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either ZoneListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.dns.v2016_04_01.models.ZoneListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either Zone or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.dns.v2016_04_01.models.Zone] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.ZoneListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-04-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-04-01")) + cls: ClsType[_models.ZoneListResult] = kwargs.pop("cls", None) + 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 = "2016-04-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list.metadata['url'] # type: ignore - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - if top is not None: - query_parameters['$top'] = self._serialize.query("top", top, 'int') - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_request( + subscription_id=self._config.subscription_id, + top=top, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('ZoneListResult', pipeline_response) + deserialized = self._deserialize("ZoneListResult", pipeline_response) list_of_elem = deserialized.value if cls: - list_of_elem = cls(list_of_elem) + list_of_elem = cls(list_of_elem) # type: ignore return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: @@ -462,7 +767,6 @@ def get_next(next_link=None): return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Network/dnszones'} # type: ignore + return ItemPaged(get_next, extract_data) + + list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Network/dnszones"} diff --git a/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_03_01_preview/__init__.py b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_03_01_preview/__init__.py index a21e1fdf48bb..23ee0cabde53 100644 --- a/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_03_01_preview/__init__.py +++ b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_03_01_preview/__init__.py @@ -10,10 +10,17 @@ from ._version import VERSION __version__ = VERSION -__all__ = ['DnsManagementClient'] try: - from ._patch import patch_sdk # type: ignore - patch_sdk() + from ._patch import __all__ as _patch_all + from ._patch import * # pylint: disable=unused-wildcard-import except ImportError: - pass + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "DnsManagementClient", +] +__all__.extend([p for p in _patch_all if p not in __all__]) + +_patch_sdk() diff --git a/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_03_01_preview/_configuration.py b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_03_01_preview/_configuration.py index cb498028e61d..5766bb8f5eff 100644 --- a/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_03_01_preview/_configuration.py +++ b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_03_01_preview/_configuration.py @@ -6,66 +6,67 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING +import sys +from typing import Any, TYPE_CHECKING from azure.core.configuration import Configuration from azure.core.pipeline import policies -from azure.mgmt.core.policies import ARMHttpLoggingPolicy +from azure.mgmt.core.policies import ARMChallengeAuthenticationPolicy, ARMHttpLoggingPolicy 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 typing import Any - from azure.core.credentials import TokenCredential -class DnsManagementClientConfiguration(Configuration): +class DnsManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes """Configuration for DnsManagementClient. 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 ID of the target subscription. + :param subscription_id: The ID of the target subscription. Required. :type subscription_id: str + :keyword api_version: Api Version. Default value is "2018-03-01-preview". Note that overriding + this default value may result in unsupported behavior. + :paramtype api_version: str """ - def __init__( - self, - credential, # type: "TokenCredential" - subscription_id, # type: str - **kwargs # type: Any - ): - # type: (...) -> None + def __init__(self, credential: "TokenCredential", subscription_id: str, **kwargs: Any) -> None: + super(DnsManagementClientConfiguration, self).__init__(**kwargs) + api_version: Literal["2018-03-01-preview"] = kwargs.pop("api_version", "2018-03-01-preview") + if credential is None: raise ValueError("Parameter 'credential' must not be None.") if subscription_id is None: raise ValueError("Parameter 'subscription_id' must not be None.") - super(DnsManagementClientConfiguration, self).__init__(**kwargs) self.credential = credential self.subscription_id = subscription_id - self.api_version = "2018-03-01-preview" - self.credential_scopes = kwargs.pop('credential_scopes', ['https://management.azure.com/.default']) - kwargs.setdefault('sdk_moniker', 'mgmt-dns/{}'.format(VERSION)) + self.api_version = api_version + self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "mgmt-dns/{}".format(VERSION)) self._configure(**kwargs) - def _configure( - self, - **kwargs # type: Any - ): - # type: (...) -> None - self.user_agent_policy = kwargs.get('user_agent_policy') or policies.UserAgentPolicy(**kwargs) - self.headers_policy = kwargs.get('headers_policy') or policies.HeadersPolicy(**kwargs) - self.proxy_policy = kwargs.get('proxy_policy') or policies.ProxyPolicy(**kwargs) - self.logging_policy = kwargs.get('logging_policy') or policies.NetworkTraceLoggingPolicy(**kwargs) - self.http_logging_policy = kwargs.get('http_logging_policy') or ARMHttpLoggingPolicy(**kwargs) - self.retry_policy = kwargs.get('retry_policy') or policies.RetryPolicy(**kwargs) - self.custom_hook_policy = kwargs.get('custom_hook_policy') or policies.CustomHookPolicy(**kwargs) - self.redirect_policy = kwargs.get('redirect_policy') or policies.RedirectPolicy(**kwargs) - self.authentication_policy = kwargs.get('authentication_policy') + def _configure(self, **kwargs: Any) -> None: + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.RetryPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.RedirectPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") if self.credential and not self.authentication_policy: - self.authentication_policy = policies.BearerTokenCredentialPolicy(self.credential, *self.credential_scopes, **kwargs) + self.authentication_policy = ARMChallengeAuthenticationPolicy( + self.credential, *self.credential_scopes, **kwargs + ) diff --git a/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_03_01_preview/_dns_management_client.py b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_03_01_preview/_dns_management_client.py index efccda800ec4..423b91643e60 100644 --- a/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_03_01_preview/_dns_management_client.py +++ b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_03_01_preview/_dns_management_client.py @@ -6,89 +6,89 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING +from copy import deepcopy +from typing import Any, TYPE_CHECKING +from azure.core.rest import HttpRequest, HttpResponse from azure.mgmt.core import ARMPipelineClient -from msrest import Deserializer, Serializer + +from . import models as _models +from .._serialization import Deserializer, Serializer +from ._configuration import DnsManagementClientConfiguration +from .operations import RecordSetsOperations, ZonesOperations if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Optional - from azure.core.credentials import TokenCredential - from azure.core.pipeline.transport import HttpRequest, HttpResponse - -from ._configuration import DnsManagementClientConfiguration -from .operations import RecordSetsOperations -from .operations import ZonesOperations -from . import models -class DnsManagementClient(object): +class DnsManagementClient: # pylint: disable=client-accepts-api-version-keyword """The DNS Management Client. :ivar record_sets: RecordSetsOperations operations :vartype record_sets: azure.mgmt.dns.v2018_03_01_preview.operations.RecordSetsOperations :ivar zones: ZonesOperations operations :vartype zones: azure.mgmt.dns.v2018_03_01_preview.operations.ZonesOperations - :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 ID of the target subscription. + :param subscription_id: The ID of the target subscription. Required. :type subscription_id: str - :param str base_url: Service URL - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :param base_url: Service URL. Default value is "https://management.azure.com". + :type base_url: str + :keyword api_version: Api Version. Default value is "2018-03-01-preview". Note that overriding + this default value may result in unsupported behavior. + :paramtype api_version: str + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. """ def __init__( self, - credential, # type: "TokenCredential" - subscription_id, # type: str - base_url=None, # type: Optional[str] - **kwargs # type: Any - ): - # type: (...) -> None - if not base_url: - base_url = 'https://management.azure.com' - self._config = DnsManagementClientConfiguration(credential, subscription_id, **kwargs) + credential: "TokenCredential", + subscription_id: str, + base_url: str = "https://management.azure.com", + **kwargs: Any + ) -> None: + self._config = DnsManagementClientConfiguration( + 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)} + client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)} self._serialize = Serializer(client_models) - self._serialize.client_side_validation = False self._deserialize = Deserializer(client_models) + self._serialize.client_side_validation = False + self.record_sets = RecordSetsOperations(self._client, self._config, self._serialize, self._deserialize) + self.zones = ZonesOperations(self._client, self._config, self._serialize, self._deserialize) - self.record_sets = RecordSetsOperations( - self._client, self._config, self._serialize, self._deserialize) - self.zones = ZonesOperations( - self._client, self._config, self._serialize, self._deserialize) - - def _send_request(self, http_request, **kwargs): - # type: (HttpRequest, Any) -> HttpResponse + def _send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: """Runs the network request through the client's chained policies. - :param http_request: The network request you want to make. Required. - :type http_request: ~azure.core.pipeline.transport.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to True. + >>> from azure.core.rest import HttpRequest + >>> request = HttpRequest("GET", "https://www.example.org/") + + >>> response = client._send_request(request) + + + For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request + + :param request: The network request you want to make. Required. + :type request: ~azure.core.rest.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to False. :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.pipeline.transport.HttpResponse + :rtype: ~azure.core.rest.HttpResponse """ - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), - } - http_request.url = self._client.format_url(http_request.url, **path_format_arguments) - stream = kwargs.pop("stream", True) - pipeline_response = self._client._pipeline.run(http_request, stream=stream, **kwargs) - return pipeline_response.http_response - - def close(self): - # type: () -> None + + request_copy = deepcopy(request) + request_copy.url = self._client.format_url(request_copy.url) + return self._client.send_request(request_copy, **kwargs) + + def close(self) -> None: self._client.close() - def __enter__(self): - # type: () -> DnsManagementClient + def __enter__(self) -> "DnsManagementClient": self._client.__enter__() return self - def __exit__(self, *exc_details): - # type: (Any) -> None + def __exit__(self, *exc_details: Any) -> None: self._client.__exit__(*exc_details) diff --git a/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_03_01_preview/_metadata.json b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_03_01_preview/_metadata.json index 688974d9598e..00de73bf9064 100644 --- a/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_03_01_preview/_metadata.json +++ b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_03_01_preview/_metadata.json @@ -5,39 +5,41 @@ "name": "DnsManagementClient", "filename": "_dns_management_client", "description": "The DNS Management Client.", - "base_url": "\u0027https://management.azure.com\u0027", - "custom_base_url": null, + "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\"], \"msrest\": [\"Deserializer\", \"Serializer\"], \"azure.mgmt.core\": [\"ARMPipelineClient\"]}, \"local\": {\"._configuration\": [\"DnsManagementClientConfiguration\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}, \"azurecore\": {\"azure.core.pipeline.transport\": [\"HttpRequest\", \"HttpResponse\"]}}}", - "async_imports": "{\"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}, \"regular\": {\"azurecore\": {\"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"], \"msrest\": [\"Deserializer\", \"Serializer\"], \"azure.mgmt.core\": [\"AsyncARMPipelineClient\"]}, \"local\": {\"._configuration\": [\"DnsManagementClientConfiguration\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}, \"azurecore\": {\"azure.core.pipeline.transport\": [\"AsyncHttpResponse\", \"HttpRequest\"]}}}" + "sync_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"azurecore\": {\"azure.mgmt.core\": [\"ARMPipelineClient\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"DnsManagementClientConfiguration\"], \".._serialization\": [\"Deserializer\", \"Serializer\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", + "async_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"azurecore\": {\"azure.mgmt.core\": [\"AsyncARMPipelineClient\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"DnsManagementClientConfiguration\"], \"..._serialization\": [\"Deserializer\", \"Serializer\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" }, "global_parameters": { "sync": { "credential": { - "signature": "credential, # type: \"TokenCredential\"", - "description": "Credential needed for the client to connect to Azure.", + "signature": "credential: \"TokenCredential\",", + "description": "Credential needed for the client to connect to Azure. Required.", "docstring_type": "~azure.core.credentials.TokenCredential", - "required": true + "required": true, + "method_location": "positional" }, "subscription_id": { - "signature": "subscription_id, # type: str", - "description": "The ID of the target subscription.", + "signature": "subscription_id: str,", + "description": "The ID of the target subscription. Required.", "docstring_type": "str", - "required": true + "required": true, + "method_location": "positional" } }, "async": { "credential": { "signature": "credential: \"AsyncTokenCredential\",", - "description": "Credential needed for the client to connect to Azure.", + "description": "Credential needed for the client to connect to Azure. Required.", "docstring_type": "~azure.core.credentials_async.AsyncTokenCredential", "required": true }, "subscription_id": { "signature": "subscription_id: str,", - "description": "The ID of the target subscription.", + "description": "The ID of the target subscription. Required.", "docstring_type": "str", "required": true } @@ -48,22 +50,25 @@ "service_client_specific": { "sync": { "api_version": { - "signature": "api_version=None, # type: Optional[str]", + "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 + "required": false, + "method_location": "positional" }, "base_url": { - "signature": "base_url=None, # type: Optional[str]", + "signature": "base_url: str = \"https://management.azure.com\",", "description": "Service URL", "docstring_type": "str", - "required": false + "required": false, + "method_location": "positional" }, "profile": { - "signature": "profile=KnownProfiles.default, # type: KnownProfiles", + "signature": "profile: KnownProfiles=KnownProfiles.default,", "description": "A profile definition, from KnownProfiles to dict.", "docstring_type": "azure.profiles.KnownProfiles", - "required": false + "required": false, + "method_location": "positional" } }, "async": { @@ -71,19 +76,22 @@ "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 + "required": false, + "method_location": "positional" }, "base_url": { - "signature": "base_url: Optional[str] = None,", + "signature": "base_url: str = \"https://management.azure.com\",", "description": "Service URL", "docstring_type": "str", - "required": false + "required": false, + "method_location": "positional" }, "profile": { "signature": "profile: KnownProfiles = KnownProfiles.default,", "description": "A profile definition, from KnownProfiles to dict.", "docstring_type": "azure.profiles.KnownProfiles", - "required": false + "required": false, + "method_location": "positional" } } } @@ -91,14 +99,13 @@ "config": { "credential": true, "credential_scopes": ["https://management.azure.com/.default"], - "credential_default_policy_type": "BearerTokenCredentialPolicy", - "credential_default_policy_type_has_async_version": true, - "credential_key_header_name": null, - "sync_imports": "{\"regular\": {\"azurecore\": {\"azure.core.configuration\": [\"Configuration\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"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\"]}, \"local\": {\".._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" + "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": { "record_sets": "RecordSetsOperations", "zones": "ZonesOperations" } -} \ No newline at end of file +} diff --git a/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_03_01_preview/_patch.py b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_03_01_preview/_patch.py new file mode 100644 index 000000000000..f7dd32510333 --- /dev/null +++ b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_03_01_preview/_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/network/azure-mgmt-dns/azure/mgmt/dns/v2018_03_01_preview/_vendor.py b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_03_01_preview/_vendor.py new file mode 100644 index 000000000000..bd0df84f5319 --- /dev/null +++ b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_03_01_preview/_vendor.py @@ -0,0 +1,30 @@ +# -------------------------------------------------------------------------- +# 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 typing import List, cast + +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) + if files: + request.set_formdata_body(files) + return request + + +def _format_url_section(template, **kwargs): + components = template.split("/") + while components: + try: + return template.format(**kwargs) + except KeyError as key: + # Need the cast, as for some reasons "split" is typed as list[str | Any] + formatted_components = cast(List[str], template.split("/")) + components = [c for c in formatted_components if "{}".format(key.args[0]) not in c] + template = "/".join(components) diff --git a/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_03_01_preview/_version.py b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_03_01_preview/_version.py index 142a0420b39b..e5754a47ce68 100644 --- a/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_03_01_preview/_version.py +++ b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_03_01_preview/_version.py @@ -6,4 +6,4 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -VERSION = "8.0.0" +VERSION = "1.0.0b1" diff --git a/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_03_01_preview/aio/__init__.py b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_03_01_preview/aio/__init__.py index 1a93fabcef86..e94042023e78 100644 --- a/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_03_01_preview/aio/__init__.py +++ b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_03_01_preview/aio/__init__.py @@ -7,4 +7,17 @@ # -------------------------------------------------------------------------- from ._dns_management_client import DnsManagementClient -__all__ = ['DnsManagementClient'] + +try: + from ._patch import __all__ as _patch_all + from ._patch import * # pylint: disable=unused-wildcard-import +except ImportError: + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "DnsManagementClient", +] +__all__.extend([p for p in _patch_all if p not in __all__]) + +_patch_sdk() diff --git a/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_03_01_preview/aio/_configuration.py b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_03_01_preview/aio/_configuration.py index b16605df59f1..2f4da1e043d0 100644 --- a/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_03_01_preview/aio/_configuration.py +++ b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_03_01_preview/aio/_configuration.py @@ -6,62 +6,67 @@ # 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 from azure.core.pipeline import policies -from azure.mgmt.core.policies import ARMHttpLoggingPolicy +from azure.mgmt.core.policies import ARMHttpLoggingPolicy, AsyncARMChallengeAuthenticationPolicy 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 -class DnsManagementClientConfiguration(Configuration): +class DnsManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes """Configuration for DnsManagementClient. 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 ID of the target subscription. + :param subscription_id: The ID of the target subscription. Required. :type subscription_id: str + :keyword api_version: Api Version. Default value is "2018-03-01-preview". 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(DnsManagementClientConfiguration, self).__init__(**kwargs) + api_version: Literal["2018-03-01-preview"] = kwargs.pop("api_version", "2018-03-01-preview") + if credential is None: raise ValueError("Parameter 'credential' must not be None.") if subscription_id is None: raise ValueError("Parameter 'subscription_id' must not be None.") - super(DnsManagementClientConfiguration, self).__init__(**kwargs) self.credential = credential self.subscription_id = subscription_id - self.api_version = "2018-03-01-preview" - self.credential_scopes = kwargs.pop('credential_scopes', ['https://management.azure.com/.default']) - kwargs.setdefault('sdk_moniker', 'mgmt-dns/{}'.format(VERSION)) + self.api_version = api_version + self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "mgmt-dns/{}".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 = policies.AsyncBearerTokenCredentialPolicy(self.credential, *self.credential_scopes, **kwargs) + self.authentication_policy = AsyncARMChallengeAuthenticationPolicy( + self.credential, *self.credential_scopes, **kwargs + ) diff --git a/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_03_01_preview/aio/_dns_management_client.py b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_03_01_preview/aio/_dns_management_client.py index acf324682771..9108f843bbe9 100644 --- a/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_03_01_preview/aio/_dns_management_client.py +++ b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_03_01_preview/aio/_dns_management_client.py @@ -6,75 +6,82 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, Optional, TYPE_CHECKING +from copy import deepcopy +from typing import Any, Awaitable, TYPE_CHECKING -from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.rest import AsyncHttpResponse, HttpRequest from azure.mgmt.core import AsyncARMPipelineClient -from msrest import Deserializer, Serializer + +from .. import models as _models +from ..._serialization import Deserializer, Serializer +from ._configuration import DnsManagementClientConfiguration +from .operations import RecordSetsOperations, ZonesOperations if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential -from ._configuration import DnsManagementClientConfiguration -from .operations import RecordSetsOperations -from .operations import ZonesOperations -from .. import models - -class DnsManagementClient(object): +class DnsManagementClient: # pylint: disable=client-accepts-api-version-keyword """The DNS Management Client. :ivar record_sets: RecordSetsOperations operations :vartype record_sets: azure.mgmt.dns.v2018_03_01_preview.aio.operations.RecordSetsOperations :ivar zones: ZonesOperations operations :vartype zones: azure.mgmt.dns.v2018_03_01_preview.aio.operations.ZonesOperations - :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 ID of the target subscription. + :param subscription_id: The ID of the target subscription. Required. :type subscription_id: str - :param str base_url: Service URL - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :param base_url: Service URL. Default value is "https://management.azure.com". + :type base_url: str + :keyword api_version: Api Version. Default value is "2018-03-01-preview". Note that overriding + this default value may result in unsupported behavior. + :paramtype api_version: str + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. """ def __init__( self, credential: "AsyncTokenCredential", subscription_id: str, - base_url: Optional[str] = None, + base_url: str = "https://management.azure.com", **kwargs: Any ) -> None: - if not base_url: - base_url = 'https://management.azure.com' - self._config = DnsManagementClientConfiguration(credential, subscription_id, **kwargs) + self._config = DnsManagementClientConfiguration( + 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)} + client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)} self._serialize = Serializer(client_models) - self._serialize.client_side_validation = False self._deserialize = Deserializer(client_models) + self._serialize.client_side_validation = False + self.record_sets = RecordSetsOperations(self._client, self._config, self._serialize, self._deserialize) + self.zones = ZonesOperations(self._client, self._config, self._serialize, self._deserialize) - self.record_sets = RecordSetsOperations( - self._client, self._config, self._serialize, self._deserialize) - self.zones = ZonesOperations( - self._client, self._config, self._serialize, self._deserialize) - - async def _send_request(self, http_request: HttpRequest, **kwargs: Any) -> AsyncHttpResponse: + def _send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]: """Runs the network request through the client's chained policies. - :param http_request: The network request you want to make. Required. - :type http_request: ~azure.core.pipeline.transport.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to True. + >>> from azure.core.rest import HttpRequest + >>> request = HttpRequest("GET", "https://www.example.org/") + + >>> response = await client._send_request(request) + + + For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request + + :param request: The network request you want to make. Required. + :type request: ~azure.core.rest.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to False. :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.pipeline.transport.AsyncHttpResponse + :rtype: ~azure.core.rest.AsyncHttpResponse """ - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), - } - http_request.url = self._client.format_url(http_request.url, **path_format_arguments) - stream = kwargs.pop("stream", True) - pipeline_response = await self._client._pipeline.run(http_request, stream=stream, **kwargs) - return pipeline_response.http_response + + request_copy = deepcopy(request) + request_copy.url = self._client.format_url(request_copy.url) + return self._client.send_request(request_copy, **kwargs) async def close(self) -> None: await self._client.close() @@ -83,5 +90,5 @@ async def __aenter__(self) -> "DnsManagementClient": await self._client.__aenter__() return self - async def __aexit__(self, *exc_details) -> None: + async def __aexit__(self, *exc_details: Any) -> None: await self._client.__aexit__(*exc_details) diff --git a/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_03_01_preview/aio/_patch.py b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_03_01_preview/aio/_patch.py new file mode 100644 index 000000000000..f7dd32510333 --- /dev/null +++ b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_03_01_preview/aio/_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/network/azure-mgmt-dns/azure/mgmt/dns/v2018_03_01_preview/aio/operations/__init__.py b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_03_01_preview/aio/operations/__init__.py index caab83d882c4..c12bcc6610ed 100644 --- a/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_03_01_preview/aio/operations/__init__.py +++ b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_03_01_preview/aio/operations/__init__.py @@ -9,7 +9,13 @@ from ._record_sets_operations import RecordSetsOperations from ._zones_operations import ZonesOperations +from ._patch import __all__ as _patch_all +from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import patch_sdk as _patch_sdk + __all__ = [ - 'RecordSetsOperations', - 'ZonesOperations', + "RecordSetsOperations", + "ZonesOperations", ] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_03_01_preview/aio/operations/_patch.py b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_03_01_preview/aio/operations/_patch.py new file mode 100644 index 000000000000..f7dd32510333 --- /dev/null +++ b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_03_01_preview/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/network/azure-mgmt-dns/azure/mgmt/dns/v2018_03_01_preview/aio/operations/_record_sets_operations.py b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_03_01_preview/aio/operations/_record_sets_operations.py index bccc0caaa891..ef1cf62c87ef 100644 --- a/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_03_01_preview/aio/operations/_record_sets_operations.py +++ b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_03_01_preview/aio/operations/_record_sets_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,197 +6,435 @@ # 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, Generic, Optional, TypeVar, Union -import warnings +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, HttpRequest +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 - -T = TypeVar('T') +from ..._vendor import _convert_request +from ...operations._record_sets_operations import ( + build_create_or_update_request, + build_delete_request, + build_get_request, + build_list_all_by_dns_zone_request, + build_list_by_dns_zone_request, + build_list_by_type_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 RecordSetsOperations: - """RecordSetsOperations 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 RecordSetsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.dns.v2018_03_01_preview.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.dns.v2018_03_01_preview.aio.DnsManagementClient`'s + :attr:`record_sets` 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") + @overload async def update( self, resource_group_name: str, zone_name: str, relative_record_set_name: str, - record_type: Union[str, "_models.RecordType"], - parameters: "_models.RecordSet", + record_type: Union[str, _models.RecordType], + parameters: _models.RecordSet, if_match: Optional[str] = None, - **kwargs - ) -> "_models.RecordSet": + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RecordSet: """Updates a record set within a DNS zone. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param zone_name: The name of the DNS zone (without a terminating dot). + :param zone_name: The name of the DNS zone (without a terminating dot). Required. :type zone_name: str :param relative_record_set_name: The name of the record set, relative to the name of the zone. + Required. :type relative_record_set_name: str - :param record_type: The type of DNS record in this record set. + :param record_type: The type of DNS record in this record set. Known values are: "A", "AAAA", + "CAA", "CNAME", "MX", "NS", "PTR", "SOA", "SRV", and "TXT". Required. :type record_type: str or ~azure.mgmt.dns.v2018_03_01_preview.models.RecordType - :param parameters: Parameters supplied to the Update operation. + :param parameters: Parameters supplied to the Update operation. Required. :type parameters: ~azure.mgmt.dns.v2018_03_01_preview.models.RecordSet :param if_match: The etag of the record set. Omit this value to always overwrite the current record set. Specify the last-seen etag value to prevent accidentally overwriting concurrent - changes. + changes. 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: RecordSet or the result of cls(response) + :rtype: ~azure.mgmt.dns.v2018_03_01_preview.models.RecordSet + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def update( + self, + resource_group_name: str, + zone_name: str, + relative_record_set_name: str, + record_type: Union[str, _models.RecordType], + parameters: IO, + if_match: Optional[str] = None, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RecordSet: + """Updates a record set within a DNS zone. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param zone_name: The name of the DNS zone (without a terminating dot). Required. + :type zone_name: str + :param relative_record_set_name: The name of the record set, relative to the name of the zone. + Required. + :type relative_record_set_name: str + :param record_type: The type of DNS record in this record set. Known values are: "A", "AAAA", + "CAA", "CNAME", "MX", "NS", "PTR", "SOA", "SRV", and "TXT". Required. + :type record_type: str or ~azure.mgmt.dns.v2018_03_01_preview.models.RecordType + :param parameters: Parameters supplied to the Update operation. Required. + :type parameters: IO + :param if_match: The etag of the record set. Omit this value to always overwrite the current + record set. Specify the last-seen etag value to prevent accidentally overwriting concurrent + changes. 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: RecordSet or the result of cls(response) + :rtype: ~azure.mgmt.dns.v2018_03_01_preview.models.RecordSet + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def update( + self, + resource_group_name: str, + zone_name: str, + relative_record_set_name: str, + record_type: Union[str, _models.RecordType], + parameters: Union[_models.RecordSet, IO], + if_match: Optional[str] = None, + **kwargs: Any + ) -> _models.RecordSet: + """Updates a record set within a DNS zone. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param zone_name: The name of the DNS zone (without a terminating dot). Required. + :type zone_name: str + :param relative_record_set_name: The name of the record set, relative to the name of the zone. + Required. + :type relative_record_set_name: str + :param record_type: The type of DNS record in this record set. Known values are: "A", "AAAA", + "CAA", "CNAME", "MX", "NS", "PTR", "SOA", "SRV", and "TXT". Required. + :type record_type: str or ~azure.mgmt.dns.v2018_03_01_preview.models.RecordType + :param parameters: Parameters supplied to the Update operation. Is either a RecordSet type or a + IO type. Required. + :type parameters: ~azure.mgmt.dns.v2018_03_01_preview.models.RecordSet or IO + :param if_match: The etag of the record set. Omit this value to always overwrite the current + record set. Specify the last-seen etag value to prevent accidentally overwriting concurrent + changes. 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: RecordSet, or the result of cls(response) + :return: RecordSet or the result of cls(response) :rtype: ~azure.mgmt.dns.v2018_03_01_preview.models.RecordSet - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RecordSet"] 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 = "2018-03-01-preview" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.update.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), - 'zoneName': self._serialize.url("zone_name", zone_name, 'str'), - 'relativeRecordSetName': self._serialize.url("relative_record_set_name", relative_record_set_name, 'str', skip_quote=True), - 'recordType': self._serialize.url("record_type", record_type, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - if if_match is not None: - header_parameters['If-Match'] = self._serialize.header("if_match", if_match, 'str') - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(parameters, 'RecordSet') - body_content_kwargs['content'] = body_content - request = self._client.patch(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + 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: Literal["2018-03-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2018-03-01-preview") + ) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.RecordSet] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "RecordSet") + + request = build_update_request( + resource_group_name=resource_group_name, + zone_name=zone_name, + relative_record_set_name=relative_record_set_name, + record_type=record_type, + subscription_id=self._config.subscription_id, + if_match=if_match, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.update.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = 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('RecordSet', pipeline_response) + deserialized = self._deserialize("RecordSet", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}/{recordType}/{relativeRecordSetName}'} # type: ignore + update.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}/{recordType}/{relativeRecordSetName}" + } + + @overload async def create_or_update( self, resource_group_name: str, zone_name: str, relative_record_set_name: str, - record_type: Union[str, "_models.RecordType"], - parameters: "_models.RecordSet", + record_type: Union[str, _models.RecordType], + parameters: _models.RecordSet, if_match: Optional[str] = None, if_none_match: Optional[str] = None, - **kwargs - ) -> "_models.RecordSet": + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RecordSet: """Creates or updates a record set within a DNS zone. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param zone_name: The name of the DNS zone (without a terminating dot). + :param zone_name: The name of the DNS zone (without a terminating dot). Required. :type zone_name: str :param relative_record_set_name: The name of the record set, relative to the name of the zone. + Required. :type relative_record_set_name: str :param record_type: The type of DNS record in this record set. Record sets of type SOA can be - updated but not created (they are created when the DNS zone is created). + updated but not created (they are created when the DNS zone is created). Known values are: "A", + "AAAA", "CAA", "CNAME", "MX", "NS", "PTR", "SOA", "SRV", and "TXT". Required. :type record_type: str or ~azure.mgmt.dns.v2018_03_01_preview.models.RecordType - :param parameters: Parameters supplied to the CreateOrUpdate operation. + :param parameters: Parameters supplied to the CreateOrUpdate operation. Required. :type parameters: ~azure.mgmt.dns.v2018_03_01_preview.models.RecordSet :param if_match: The etag of the record set. Omit this value to always overwrite the current record set. Specify the last-seen etag value to prevent accidentally overwriting any concurrent - changes. + changes. Default value is None. :type if_match: str :param if_none_match: Set to '*' to allow a new record set to be created, but to prevent - updating an existing record set. Other values will be ignored. + updating an existing record set. 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: RecordSet, or the result of cls(response) + :return: RecordSet or the result of cls(response) :rtype: ~azure.mgmt.dns.v2018_03_01_preview.models.RecordSet - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_or_update( + self, + resource_group_name: str, + zone_name: str, + relative_record_set_name: str, + record_type: Union[str, _models.RecordType], + parameters: IO, + if_match: Optional[str] = None, + if_none_match: Optional[str] = None, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RecordSet: + """Creates or updates a record set within a DNS zone. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param zone_name: The name of the DNS zone (without a terminating dot). Required. + :type zone_name: str + :param relative_record_set_name: The name of the record set, relative to the name of the zone. + Required. + :type relative_record_set_name: str + :param record_type: The type of DNS record in this record set. Record sets of type SOA can be + updated but not created (they are created when the DNS zone is created). Known values are: "A", + "AAAA", "CAA", "CNAME", "MX", "NS", "PTR", "SOA", "SRV", and "TXT". Required. + :type record_type: str or ~azure.mgmt.dns.v2018_03_01_preview.models.RecordType + :param parameters: Parameters supplied to the CreateOrUpdate operation. Required. + :type parameters: IO + :param if_match: The etag of the record set. Omit this value to always overwrite the current + record set. Specify the last-seen etag value to prevent accidentally overwriting any concurrent + changes. Default value is None. + :type if_match: str + :param if_none_match: Set to '*' to allow a new record set to be created, but to prevent + updating an existing record set. 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: RecordSet or the result of cls(response) + :rtype: ~azure.mgmt.dns.v2018_03_01_preview.models.RecordSet + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create_or_update( + self, + resource_group_name: str, + zone_name: str, + relative_record_set_name: str, + record_type: Union[str, _models.RecordType], + parameters: Union[_models.RecordSet, IO], + if_match: Optional[str] = None, + if_none_match: Optional[str] = None, + **kwargs: Any + ) -> _models.RecordSet: + """Creates or updates a record set within a DNS zone. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param zone_name: The name of the DNS zone (without a terminating dot). Required. + :type zone_name: str + :param relative_record_set_name: The name of the record set, relative to the name of the zone. + Required. + :type relative_record_set_name: str + :param record_type: The type of DNS record in this record set. Record sets of type SOA can be + updated but not created (they are created when the DNS zone is created). Known values are: "A", + "AAAA", "CAA", "CNAME", "MX", "NS", "PTR", "SOA", "SRV", and "TXT". Required. + :type record_type: str or ~azure.mgmt.dns.v2018_03_01_preview.models.RecordType + :param parameters: Parameters supplied to the CreateOrUpdate operation. Is either a RecordSet + type or a IO type. Required. + :type parameters: ~azure.mgmt.dns.v2018_03_01_preview.models.RecordSet or IO + :param if_match: The etag of the record set. Omit this value to always overwrite the current + record set. Specify the last-seen etag value to prevent accidentally overwriting any concurrent + changes. Default value is None. + :type if_match: str + :param if_none_match: Set to '*' to allow a new record set to be created, but to prevent + updating an existing record set. 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: RecordSet or the result of cls(response) + :rtype: ~azure.mgmt.dns.v2018_03_01_preview.models.RecordSet + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RecordSet"] 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 = "2018-03-01-preview" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.create_or_update.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), - 'zoneName': self._serialize.url("zone_name", zone_name, 'str'), - 'relativeRecordSetName': self._serialize.url("relative_record_set_name", relative_record_set_name, 'str', skip_quote=True), - 'recordType': self._serialize.url("record_type", record_type, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - if if_match is not None: - header_parameters['If-Match'] = self._serialize.header("if_match", if_match, 'str') - if if_none_match is not None: - header_parameters['If-None-Match'] = self._serialize.header("if_none_match", if_none_match, 'str') - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(parameters, 'RecordSet') - body_content_kwargs['content'] = body_content - request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + 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: Literal["2018-03-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2018-03-01-preview") + ) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.RecordSet] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "RecordSet") + + request = build_create_or_update_request( + resource_group_name=resource_group_name, + zone_name=zone_name, + relative_record_set_name=relative_record_set_name, + record_type=record_type, + subscription_id=self._config.subscription_id, + if_match=if_match, + if_none_match=if_none_match, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create_or_update.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response if response.status_code not in [200, 201]: @@ -203,77 +442,88 @@ async def create_or_update( raise HttpResponseError(response=response, error_format=ARMErrorFormat) if response.status_code == 200: - deserialized = self._deserialize('RecordSet', pipeline_response) + deserialized = self._deserialize("RecordSet", pipeline_response) if response.status_code == 201: - deserialized = self._deserialize('RecordSet', pipeline_response) + deserialized = self._deserialize("RecordSet", pipeline_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}/{recordType}/{relativeRecordSetName}'} # type: ignore + return deserialized # type: ignore + + create_or_update.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}/{recordType}/{relativeRecordSetName}" + } - async def delete( + @distributed_trace_async + async def delete( # pylint: disable=inconsistent-return-statements self, resource_group_name: str, zone_name: str, relative_record_set_name: str, - record_type: Union[str, "_models.RecordType"], + record_type: Union[str, _models.RecordType], if_match: Optional[str] = None, - **kwargs + **kwargs: Any ) -> None: """Deletes a record set from a DNS zone. This operation cannot be undone. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param zone_name: The name of the DNS zone (without a terminating dot). + :param zone_name: The name of the DNS zone (without a terminating dot). Required. :type zone_name: str :param relative_record_set_name: The name of the record set, relative to the name of the zone. + Required. :type relative_record_set_name: str :param record_type: The type of DNS record in this record set. Record sets of type SOA cannot - be deleted (they are deleted when the DNS zone is deleted). + be deleted (they are deleted when the DNS zone is deleted). Known values are: "A", "AAAA", + "CAA", "CNAME", "MX", "NS", "PTR", "SOA", "SRV", and "TXT". Required. :type record_type: str or ~azure.mgmt.dns.v2018_03_01_preview.models.RecordType :param if_match: The etag of the record set. Omit this value to always delete the current record set. Specify the last-seen etag value to prevent accidentally deleting any concurrent - changes. + changes. Default value is None. :type if_match: 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 - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-03-01-preview" - accept = "application/json" - - # Construct URL - url = self.delete.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), - 'zoneName': self._serialize.url("zone_name", zone_name, 'str'), - 'relativeRecordSetName': self._serialize.url("relative_record_set_name", relative_record_set_name, 'str', skip_quote=True), - 'recordType': self._serialize.url("record_type", record_type, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2018-03-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2018-03-01-preview") + ) + cls: ClsType[None] = kwargs.pop("cls", None) + + request = build_delete_request( + resource_group_name=resource_group_name, + zone_name=zone_name, + relative_record_set_name=relative_record_set_name, + record_type=record_type, + subscription_id=self._config.subscription_id, + if_match=if_match, + api_version=api_version, + template_url=self.delete.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) - # Construct headers - header_parameters = {} # type: Dict[str, Any] - if if_match is not None: - header_parameters['If-Match'] = self._serialize.header("if_match", if_match, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.delete(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 204]: @@ -283,152 +533,186 @@ async def delete( if cls: return cls(pipeline_response, None, {}) - delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}/{recordType}/{relativeRecordSetName}'} # type: ignore + delete.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}/{recordType}/{relativeRecordSetName}" + } + @distributed_trace_async async def get( self, resource_group_name: str, zone_name: str, relative_record_set_name: str, - record_type: Union[str, "_models.RecordType"], - **kwargs - ) -> "_models.RecordSet": + record_type: Union[str, _models.RecordType], + **kwargs: Any + ) -> _models.RecordSet: """Gets a record set. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param zone_name: The name of the DNS zone (without a terminating dot). + :param zone_name: The name of the DNS zone (without a terminating dot). Required. :type zone_name: str :param relative_record_set_name: The name of the record set, relative to the name of the zone. + Required. :type relative_record_set_name: str - :param record_type: The type of DNS record in this record set. + :param record_type: The type of DNS record in this record set. Known values are: "A", "AAAA", + "CAA", "CNAME", "MX", "NS", "PTR", "SOA", "SRV", and "TXT". Required. :type record_type: str or ~azure.mgmt.dns.v2018_03_01_preview.models.RecordType :keyword callable cls: A custom type or function that will be passed the direct response - :return: RecordSet, or the result of cls(response) + :return: RecordSet or the result of cls(response) :rtype: ~azure.mgmt.dns.v2018_03_01_preview.models.RecordSet - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RecordSet"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-03-01-preview" - accept = "application/json" - - # Construct URL - url = self.get.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), - 'zoneName': self._serialize.url("zone_name", zone_name, 'str'), - 'relativeRecordSetName': self._serialize.url("relative_record_set_name", relative_record_set_name, 'str', skip_quote=True), - 'recordType': self._serialize.url("record_type", record_type, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + api_version: Literal["2018-03-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2018-03-01-preview") + ) + cls: ClsType[_models.RecordSet] = kwargs.pop("cls", None) + + request = build_get_request( + resource_group_name=resource_group_name, + zone_name=zone_name, + relative_record_set_name=relative_record_set_name, + record_type=record_type, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('RecordSet', pipeline_response) + deserialized = self._deserialize("RecordSet", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}/{recordType}/{relativeRecordSetName}'} # type: ignore + get.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}/{recordType}/{relativeRecordSetName}" + } + + @distributed_trace def list_by_type( self, resource_group_name: str, zone_name: str, - record_type: Union[str, "_models.RecordType"], + record_type: Union[str, _models.RecordType], top: Optional[int] = None, recordsetnamesuffix: Optional[str] = None, - **kwargs - ) -> AsyncIterable["_models.RecordSetListResult"]: + **kwargs: Any + ) -> AsyncIterable["_models.RecordSet"]: """Lists the record sets of a specified type in a DNS zone. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param zone_name: The name of the DNS zone (without a terminating dot). + :param zone_name: The name of the DNS zone (without a terminating dot). Required. :type zone_name: str - :param record_type: The type of record sets to enumerate. + :param record_type: The type of record sets to enumerate. Known values are: "A", "AAAA", "CAA", + "CNAME", "MX", "NS", "PTR", "SOA", "SRV", and "TXT". Required. :type record_type: str or ~azure.mgmt.dns.v2018_03_01_preview.models.RecordType :param top: The maximum number of record sets to return. If not specified, returns up to 100 - record sets. + record sets. Default value is None. :type top: int :param recordsetnamesuffix: The suffix label of the record set name that has to be used to filter the record set enumerations. If this parameter is specified, Enumeration will return - only records that end with .:code:``. + only records that end with .:code:``. Default value is None. :type recordsetnamesuffix: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either RecordSetListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.dns.v2018_03_01_preview.models.RecordSetListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either RecordSet or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.dns.v2018_03_01_preview.models.RecordSet] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RecordSetListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2018-03-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2018-03-01-preview") + ) + cls: ClsType[_models.RecordSetListResult] = kwargs.pop("cls", None) + 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 = "2018-03-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_by_type.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), - 'zoneName': self._serialize.url("zone_name", zone_name, 'str'), - 'recordType': self._serialize.url("record_type", record_type, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - if top is not None: - query_parameters['$top'] = self._serialize.query("top", top, 'int') - if recordsetnamesuffix is not None: - query_parameters['$recordsetnamesuffix'] = self._serialize.query("recordsetnamesuffix", recordsetnamesuffix, 'str') - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_by_type_request( + resource_group_name=resource_group_name, + zone_name=zone_name, + record_type=record_type, + subscription_id=self._config.subscription_id, + top=top, + recordsetnamesuffix=recordsetnamesuffix, + api_version=api_version, + template_url=self.list_by_type.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('RecordSetListResult', pipeline_response) + deserialized = self._deserialize("RecordSetListResult", pipeline_response) list_of_elem = deserialized.value if cls: - list_of_elem = cls(list_of_elem) + list_of_elem = cls(list_of_elem) # type: ignore return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: @@ -437,85 +721,105 @@ async def get_next(next_link=None): return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list_by_type.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}/{recordType}'} # type: ignore + return AsyncItemPaged(get_next, extract_data) + + list_by_type.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}/{recordType}" + } + @distributed_trace def list_by_dns_zone( self, resource_group_name: str, zone_name: str, top: Optional[int] = None, recordsetnamesuffix: Optional[str] = None, - **kwargs - ) -> AsyncIterable["_models.RecordSetListResult"]: + **kwargs: Any + ) -> AsyncIterable["_models.RecordSet"]: """Lists all record sets in a DNS zone. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param zone_name: The name of the DNS zone (without a terminating dot). + :param zone_name: The name of the DNS zone (without a terminating dot). Required. :type zone_name: str :param top: The maximum number of record sets to return. If not specified, returns up to 100 - record sets. + record sets. Default value is None. :type top: int :param recordsetnamesuffix: The suffix label of the record set name that has to be used to filter the record set enumerations. If this parameter is specified, Enumeration will return - only records that end with .:code:``. + only records that end with .:code:``. Default value is None. :type recordsetnamesuffix: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either RecordSetListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.dns.v2018_03_01_preview.models.RecordSetListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either RecordSet or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.dns.v2018_03_01_preview.models.RecordSet] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RecordSetListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2018-03-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2018-03-01-preview") + ) + cls: ClsType[_models.RecordSetListResult] = kwargs.pop("cls", None) + 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 = "2018-03-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_by_dns_zone.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), - 'zoneName': self._serialize.url("zone_name", zone_name, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - if top is not None: - query_parameters['$top'] = self._serialize.query("top", top, 'int') - if recordsetnamesuffix is not None: - query_parameters['$recordsetnamesuffix'] = self._serialize.query("recordsetnamesuffix", recordsetnamesuffix, 'str') - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_by_dns_zone_request( + resource_group_name=resource_group_name, + zone_name=zone_name, + subscription_id=self._config.subscription_id, + top=top, + recordsetnamesuffix=recordsetnamesuffix, + api_version=api_version, + template_url=self.list_by_dns_zone.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('RecordSetListResult', pipeline_response) + deserialized = self._deserialize("RecordSetListResult", pipeline_response) list_of_elem = deserialized.value if cls: - list_of_elem = cls(list_of_elem) + list_of_elem = cls(list_of_elem) # type: ignore return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: @@ -524,85 +828,105 @@ async def get_next(next_link=None): return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list_by_dns_zone.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}/recordsets'} # type: ignore + return AsyncItemPaged(get_next, extract_data) + list_by_dns_zone.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}/recordsets" + } + + @distributed_trace def list_all_by_dns_zone( self, resource_group_name: str, zone_name: str, top: Optional[int] = None, record_set_name_suffix: Optional[str] = None, - **kwargs - ) -> AsyncIterable["_models.RecordSetListResult"]: + **kwargs: Any + ) -> AsyncIterable["_models.RecordSet"]: """Lists all record sets in a DNS zone. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param zone_name: The name of the DNS zone (without a terminating dot). + :param zone_name: The name of the DNS zone (without a terminating dot). Required. :type zone_name: str :param top: The maximum number of record sets to return. If not specified, returns up to 100 - record sets. + record sets. Default value is None. :type top: int :param record_set_name_suffix: The suffix label of the record set name that has to be used to filter the record set enumerations. If this parameter is specified, Enumeration will return - only records that end with .:code:``. + only records that end with .:code:``. Default value is None. :type record_set_name_suffix: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either RecordSetListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.dns.v2018_03_01_preview.models.RecordSetListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either RecordSet or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.dns.v2018_03_01_preview.models.RecordSet] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RecordSetListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2018-03-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2018-03-01-preview") + ) + cls: ClsType[_models.RecordSetListResult] = kwargs.pop("cls", None) + 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 = "2018-03-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_all_by_dns_zone.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), - 'zoneName': self._serialize.url("zone_name", zone_name, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - if top is not None: - query_parameters['$top'] = self._serialize.query("top", top, 'int') - if record_set_name_suffix is not None: - query_parameters['$recordsetnamesuffix'] = self._serialize.query("record_set_name_suffix", record_set_name_suffix, 'str') - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_all_by_dns_zone_request( + resource_group_name=resource_group_name, + zone_name=zone_name, + subscription_id=self._config.subscription_id, + top=top, + record_set_name_suffix=record_set_name_suffix, + api_version=api_version, + template_url=self.list_all_by_dns_zone.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('RecordSetListResult', pipeline_response) + deserialized = self._deserialize("RecordSetListResult", pipeline_response) list_of_elem = deserialized.value if cls: - list_of_elem = cls(list_of_elem) + list_of_elem = cls(list_of_elem) # type: ignore return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: @@ -611,7 +935,8 @@ async def get_next(next_link=None): return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list_all_by_dns_zone.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}/all'} # type: ignore + return AsyncItemPaged(get_next, extract_data) + + list_all_by_dns_zone.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}/all" + } diff --git a/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_03_01_preview/aio/operations/_zones_operations.py b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_03_01_preview/aio/operations/_zones_operations.py index 0a8e5e605719..226e58f647ff 100644 --- a/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_03_01_preview/aio/operations/_zones_operations.py +++ b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_03_01_preview/aio/operations/_zones_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,109 +6,222 @@ # 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, Generic, Optional, TypeVar, Union -import warnings +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, HttpRequest +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 - -T = TypeVar('T') +from ..._vendor import _convert_request +from ...operations._zones_operations import ( + build_create_or_update_request, + build_delete_request, + build_get_request, + build_list_by_resource_group_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 ZonesOperations: - """ZonesOperations 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 ZonesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.dns.v2018_03_01_preview.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.dns.v2018_03_01_preview.aio.DnsManagementClient`'s + :attr:`zones` 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") + @overload async def create_or_update( self, resource_group_name: str, zone_name: str, - parameters: "_models.Zone", + parameters: _models.Zone, if_match: Optional[str] = None, if_none_match: Optional[str] = None, - **kwargs - ) -> "_models.Zone": + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Zone: """Creates or updates a DNS zone. Does not modify DNS records within the zone. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param zone_name: The name of the DNS zone (without a terminating dot). + :param zone_name: The name of the DNS zone (without a terminating dot). Required. :type zone_name: str - :param parameters: Parameters supplied to the CreateOrUpdate operation. + :param parameters: Parameters supplied to the CreateOrUpdate operation. Required. :type parameters: ~azure.mgmt.dns.v2018_03_01_preview.models.Zone :param if_match: The etag of the DNS zone. Omit this value to always overwrite the current zone. Specify the last-seen etag value to prevent accidentally overwriting any concurrent - changes. + changes. Default value is None. + :type if_match: str + :param if_none_match: Set to '*' to allow a new DNS zone to be created, but to prevent updating + an existing zone. 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: Zone or the result of cls(response) + :rtype: ~azure.mgmt.dns.v2018_03_01_preview.models.Zone + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_or_update( + self, + resource_group_name: str, + zone_name: str, + parameters: IO, + if_match: Optional[str] = None, + if_none_match: Optional[str] = None, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Zone: + """Creates or updates a DNS zone. Does not modify DNS records within the zone. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param zone_name: The name of the DNS zone (without a terminating dot). Required. + :type zone_name: str + :param parameters: Parameters supplied to the CreateOrUpdate operation. Required. + :type parameters: IO + :param if_match: The etag of the DNS zone. Omit this value to always overwrite the current + zone. Specify the last-seen etag value to prevent accidentally overwriting any concurrent + changes. Default value is None. + :type if_match: str + :param if_none_match: Set to '*' to allow a new DNS zone to be created, but to prevent updating + an existing zone. 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: Zone or the result of cls(response) + :rtype: ~azure.mgmt.dns.v2018_03_01_preview.models.Zone + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create_or_update( + self, + resource_group_name: str, + zone_name: str, + parameters: Union[_models.Zone, IO], + if_match: Optional[str] = None, + if_none_match: Optional[str] = None, + **kwargs: Any + ) -> _models.Zone: + """Creates or updates a DNS zone. Does not modify DNS records within the zone. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param zone_name: The name of the DNS zone (without a terminating dot). Required. + :type zone_name: str + :param parameters: Parameters supplied to the CreateOrUpdate operation. Is either a Zone type + or a IO type. Required. + :type parameters: ~azure.mgmt.dns.v2018_03_01_preview.models.Zone or IO + :param if_match: The etag of the DNS zone. Omit this value to always overwrite the current + zone. Specify the last-seen etag value to prevent accidentally overwriting any concurrent + changes. Default value is None. :type if_match: str :param if_none_match: Set to '*' to allow a new DNS zone to be created, but to prevent updating - an existing zone. Other values will be ignored. + an existing zone. 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: Zone, or the result of cls(response) + :return: Zone or the result of cls(response) :rtype: ~azure.mgmt.dns.v2018_03_01_preview.models.Zone - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Zone"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-03-01-preview" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.create_or_update.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), - 'zoneName': self._serialize.url("zone_name", zone_name, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - if if_match is not None: - header_parameters['If-Match'] = self._serialize.header("if_match", if_match, 'str') - if if_none_match is not None: - header_parameters['If-None-Match'] = self._serialize.header("if_none_match", if_none_match, 'str') - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(parameters, 'Zone') - body_content_kwargs['content'] = body_content - request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + 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: Literal["2018-03-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2018-03-01-preview") + ) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.Zone] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "Zone") + + request = build_create_or_update_request( + resource_group_name=resource_group_name, + zone_name=zone_name, + subscription_id=self._config.subscription_id, + if_match=if_match, + if_none_match=if_none_match, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create_or_update.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response if response.status_code not in [200, 201]: @@ -115,53 +229,56 @@ async def create_or_update( raise HttpResponseError(response=response, error_format=ARMErrorFormat) if response.status_code == 200: - deserialized = self._deserialize('Zone', pipeline_response) + deserialized = self._deserialize("Zone", pipeline_response) if response.status_code == 201: - deserialized = self._deserialize('Zone', pipeline_response) + deserialized = self._deserialize("Zone", pipeline_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}'} # type: ignore + return deserialized # type: ignore - async def _delete_initial( - self, - resource_group_name: str, - zone_name: str, - if_match: Optional[str] = None, - **kwargs + create_or_update.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}" + } + + async def _delete_initial( # pylint: disable=inconsistent-return-statements + self, resource_group_name: str, zone_name: str, if_match: Optional[str] = None, **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', {})) - api_version = "2018-03-01-preview" - accept = "application/json" - - # Construct URL - url = self._delete_initial.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), - 'zoneName': self._serialize.url("zone_name", zone_name, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), - } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + api_version: Literal["2018-03-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2018-03-01-preview") + ) + cls: ClsType[None] = kwargs.pop("cls", None) + + request = build_delete_request( + resource_group_name=resource_group_name, + zone_name=zone_name, + subscription_id=self._config.subscription_id, + if_match=if_match, + api_version=api_version, + template_url=self._delete_initial.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) - # Construct headers - header_parameters = {} # type: Dict[str, Any] - if if_match is not None: - header_parameters['If-Match'] = self._serialize.header("if_match", if_match, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.delete(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: @@ -171,272 +288,386 @@ async def _delete_initial( if cls: return cls(pipeline_response, None, {}) - _delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}'} # type: ignore + _delete_initial.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}" + } + @distributed_trace_async async def begin_delete( - self, - resource_group_name: str, - zone_name: str, - if_match: Optional[str] = None, - **kwargs + self, resource_group_name: str, zone_name: str, if_match: Optional[str] = None, **kwargs: Any ) -> AsyncLROPoller[None]: """Deletes a DNS zone. WARNING: All DNS records in the zone will also be deleted. This operation cannot be undone. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param zone_name: The name of the DNS zone (without a terminating dot). + :param zone_name: The name of the DNS zone (without a terminating dot). Required. :type zone_name: str :param if_match: The etag of the DNS zone. Omit this value to always delete the current zone. Specify the last-seen etag value to prevent accidentally deleting any concurrent changes. + Default value is None. :type if_match: 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: Pass in True if you'd like the AsyncARMPolling polling method, - False for no polling, or your own initialized polling object for a personal polling strategy. + :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. + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[None] :raises ~azure.core.exceptions.HttpResponseError: """ - polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType[None] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2018-03-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2018-03-01-preview") ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + cls: ClsType[None] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) if cont_token is None: - raw_result = await self._delete_initial( + raw_result = await self._delete_initial( # type: ignore resource_group_name=resource_group_name, zone_name=zone_name, if_match=if_match, - cls=lambda x,y,z: x, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) + kwargs.pop("error_map", None) - kwargs.pop('error_map', None) - kwargs.pop('content_type', 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, {}) - path_format_arguments = { - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), - 'zoneName': self._serialize.url("zone_name", zone_name, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), - } - - if polling is True: polling_method = AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) - elif polling is False: polling_method = AsyncNoPolling() - else: polling_method = polling + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - else: - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}'} # type: ignore + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - async def get( - self, - resource_group_name: str, - zone_name: str, - **kwargs - ) -> "_models.Zone": + begin_delete.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}" + } + + @distributed_trace_async + async def get(self, resource_group_name: str, zone_name: str, **kwargs: Any) -> _models.Zone: """Gets a DNS zone. Retrieves the zone properties, but not the record sets within the zone. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param zone_name: The name of the DNS zone (without a terminating dot). + :param zone_name: The name of the DNS zone (without a terminating dot). Required. :type zone_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: Zone, or the result of cls(response) + :return: Zone or the result of cls(response) :rtype: ~azure.mgmt.dns.v2018_03_01_preview.models.Zone - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Zone"] 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 = "2018-03-01-preview" - accept = "application/json" - - # Construct URL - url = self.get.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), - 'zoneName': self._serialize.url("zone_name", zone_name, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), - } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + api_version: Literal["2018-03-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2018-03-01-preview") + ) + cls: ClsType[_models.Zone] = kwargs.pop("cls", None) + + request = build_get_request( + resource_group_name=resource_group_name, + zone_name=zone_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('Zone', pipeline_response) + deserialized = self._deserialize("Zone", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}'} # type: ignore + get.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}" + } + + @overload async def update( self, resource_group_name: str, zone_name: str, - parameters: "_models.ZoneUpdate", + parameters: _models.ZoneUpdate, if_match: Optional[str] = None, - **kwargs - ) -> "_models.Zone": + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Zone: """Updates a DNS zone. Does not modify DNS records within the zone. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param zone_name: The name of the DNS zone (without a terminating dot). + :param zone_name: The name of the DNS zone (without a terminating dot). Required. :type zone_name: str - :param parameters: Parameters supplied to the Update operation. + :param parameters: Parameters supplied to the Update operation. Required. :type parameters: ~azure.mgmt.dns.v2018_03_01_preview.models.ZoneUpdate :param if_match: The etag of the DNS zone. Omit this value to always overwrite the current zone. Specify the last-seen etag value to prevent accidentally overwriting any concurrent - changes. + changes. 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: Zone or the result of cls(response) + :rtype: ~azure.mgmt.dns.v2018_03_01_preview.models.Zone + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def update( + self, + resource_group_name: str, + zone_name: str, + parameters: IO, + if_match: Optional[str] = None, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Zone: + """Updates a DNS zone. Does not modify DNS records within the zone. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param zone_name: The name of the DNS zone (without a terminating dot). Required. + :type zone_name: str + :param parameters: Parameters supplied to the Update operation. Required. + :type parameters: IO + :param if_match: The etag of the DNS zone. Omit this value to always overwrite the current + zone. Specify the last-seen etag value to prevent accidentally overwriting any concurrent + changes. 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: Zone, or the result of cls(response) + :return: Zone or the result of cls(response) :rtype: ~azure.mgmt.dns.v2018_03_01_preview.models.Zone - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def update( + self, + resource_group_name: str, + zone_name: str, + parameters: Union[_models.ZoneUpdate, IO], + if_match: Optional[str] = None, + **kwargs: Any + ) -> _models.Zone: + """Updates a DNS zone. Does not modify DNS records within the zone. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param zone_name: The name of the DNS zone (without a terminating dot). Required. + :type zone_name: str + :param parameters: Parameters supplied to the Update operation. Is either a ZoneUpdate type or + a IO type. Required. + :type parameters: ~azure.mgmt.dns.v2018_03_01_preview.models.ZoneUpdate or IO + :param if_match: The etag of the DNS zone. Omit this value to always overwrite the current + zone. Specify the last-seen etag value to prevent accidentally overwriting any concurrent + changes. 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: Zone or the result of cls(response) + :rtype: ~azure.mgmt.dns.v2018_03_01_preview.models.Zone + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Zone"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-03-01-preview" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.update.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), - 'zoneName': self._serialize.url("zone_name", zone_name, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - if if_match is not None: - header_parameters['If-Match'] = self._serialize.header("if_match", if_match, 'str') - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(parameters, 'ZoneUpdate') - body_content_kwargs['content'] = body_content - request = self._client.patch(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + 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: Literal["2018-03-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2018-03-01-preview") + ) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.Zone] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "ZoneUpdate") + + request = build_update_request( + resource_group_name=resource_group_name, + zone_name=zone_name, + subscription_id=self._config.subscription_id, + if_match=if_match, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.update.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = 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('Zone', pipeline_response) + deserialized = self._deserialize("Zone", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}'} # type: ignore + update.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}" + } + + @distributed_trace def list_by_resource_group( - self, - resource_group_name: str, - top: Optional[int] = None, - **kwargs - ) -> AsyncIterable["_models.ZoneListResult"]: + self, resource_group_name: str, top: Optional[int] = None, **kwargs: Any + ) -> AsyncIterable["_models.Zone"]: """Lists the DNS zones within a resource group. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str :param top: The maximum number of record sets to return. If not specified, returns up to 100 - record sets. + record sets. Default value is None. :type top: int :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either ZoneListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.dns.v2018_03_01_preview.models.ZoneListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either Zone or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.dns.v2018_03_01_preview.models.Zone] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.ZoneListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2018-03-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2018-03-01-preview") + ) + cls: ClsType[_models.ZoneListResult] = kwargs.pop("cls", None) + 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 = "2018-03-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_by_resource_group.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - if top is not None: - query_parameters['$top'] = self._serialize.query("top", top, 'int') - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_by_resource_group_request( + resource_group_name=resource_group_name, + subscription_id=self._config.subscription_id, + top=top, + api_version=api_version, + template_url=self.list_by_resource_group.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('ZoneListResult', pipeline_response) + deserialized = self._deserialize("ZoneListResult", pipeline_response) list_of_elem = deserialized.value if cls: - list_of_elem = cls(list_of_elem) + list_of_elem = cls(list_of_elem) # type: ignore return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: @@ -445,70 +676,86 @@ async def get_next(next_link=None): return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list_by_resource_group.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones'} # type: ignore + return AsyncItemPaged(get_next, extract_data) - def list( - self, - top: Optional[int] = None, - **kwargs - ) -> AsyncIterable["_models.ZoneListResult"]: + list_by_resource_group.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones" + } + + @distributed_trace + def list(self, top: Optional[int] = None, **kwargs: Any) -> AsyncIterable["_models.Zone"]: """Lists the DNS zones in all resource groups in a subscription. :param top: The maximum number of DNS zones to return. If not specified, returns up to 100 - zones. + zones. Default value is None. :type top: int :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either ZoneListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.dns.v2018_03_01_preview.models.ZoneListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either Zone or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.dns.v2018_03_01_preview.models.Zone] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.ZoneListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2018-03-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2018-03-01-preview") + ) + cls: ClsType[_models.ZoneListResult] = kwargs.pop("cls", None) + 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 = "2018-03-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list.metadata['url'] # type: ignore - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - if top is not None: - query_parameters['$top'] = self._serialize.query("top", top, 'int') - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_request( + subscription_id=self._config.subscription_id, + top=top, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('ZoneListResult', pipeline_response) + deserialized = self._deserialize("ZoneListResult", pipeline_response) list_of_elem = deserialized.value if cls: - list_of_elem = cls(list_of_elem) + list_of_elem = cls(list_of_elem) # type: ignore return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: @@ -517,7 +764,6 @@ async def get_next(next_link=None): return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Network/dnszones'} # type: ignore + return AsyncItemPaged(get_next, extract_data) + + list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Network/dnszones"} diff --git a/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_03_01_preview/models/__init__.py b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_03_01_preview/models/__init__.py index 3d5d2b3afee4..c3693356ba8b 100644 --- a/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_03_01_preview/models/__init__.py +++ b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_03_01_preview/models/__init__.py @@ -6,75 +6,56 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -try: - from ._models_py3 import ARecord - from ._models_py3 import AaaaRecord - from ._models_py3 import CaaRecord - from ._models_py3 import CloudErrorBody - from ._models_py3 import CnameRecord - from ._models_py3 import MxRecord - from ._models_py3 import NsRecord - from ._models_py3 import PtrRecord - from ._models_py3 import RecordSet - from ._models_py3 import RecordSetListResult - from ._models_py3 import RecordSetUpdateParameters - from ._models_py3 import Resource - from ._models_py3 import SoaRecord - from ._models_py3 import SrvRecord - from ._models_py3 import SubResource - from ._models_py3 import TrackedResource - from ._models_py3 import TxtRecord - from ._models_py3 import Zone - from ._models_py3 import ZoneListResult - from ._models_py3 import ZoneUpdate -except (SyntaxError, ImportError): - from ._models import ARecord # type: ignore - from ._models import AaaaRecord # type: ignore - from ._models import CaaRecord # type: ignore - from ._models import CloudErrorBody # type: ignore - from ._models import CnameRecord # type: ignore - from ._models import MxRecord # type: ignore - from ._models import NsRecord # type: ignore - from ._models import PtrRecord # type: ignore - from ._models import RecordSet # type: ignore - from ._models import RecordSetListResult # type: ignore - from ._models import RecordSetUpdateParameters # type: ignore - from ._models import Resource # type: ignore - from ._models import SoaRecord # type: ignore - from ._models import SrvRecord # type: ignore - from ._models import SubResource # type: ignore - from ._models import TrackedResource # type: ignore - from ._models import TxtRecord # type: ignore - from ._models import Zone # type: ignore - from ._models import ZoneListResult # type: ignore - from ._models import ZoneUpdate # type: ignore +from ._models_py3 import ARecord +from ._models_py3 import AaaaRecord +from ._models_py3 import CaaRecord +from ._models_py3 import CloudErrorBody +from ._models_py3 import CnameRecord +from ._models_py3 import MxRecord +from ._models_py3 import NsRecord +from ._models_py3 import PtrRecord +from ._models_py3 import RecordSet +from ._models_py3 import RecordSetListResult +from ._models_py3 import RecordSetUpdateParameters +from ._models_py3 import Resource +from ._models_py3 import SoaRecord +from ._models_py3 import SrvRecord +from ._models_py3 import SubResource +from ._models_py3 import TrackedResource +from ._models_py3 import TxtRecord +from ._models_py3 import Zone +from ._models_py3 import ZoneListResult +from ._models_py3 import ZoneUpdate -from ._dns_management_client_enums import ( - RecordType, - ZoneType, -) +from ._dns_management_client_enums import RecordType +from ._dns_management_client_enums import ZoneType +from ._patch import __all__ as _patch_all +from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import patch_sdk as _patch_sdk __all__ = [ - 'ARecord', - 'AaaaRecord', - 'CaaRecord', - 'CloudErrorBody', - 'CnameRecord', - 'MxRecord', - 'NsRecord', - 'PtrRecord', - 'RecordSet', - 'RecordSetListResult', - 'RecordSetUpdateParameters', - 'Resource', - 'SoaRecord', - 'SrvRecord', - 'SubResource', - 'TrackedResource', - 'TxtRecord', - 'Zone', - 'ZoneListResult', - 'ZoneUpdate', - 'RecordType', - 'ZoneType', + "ARecord", + "AaaaRecord", + "CaaRecord", + "CloudErrorBody", + "CnameRecord", + "MxRecord", + "NsRecord", + "PtrRecord", + "RecordSet", + "RecordSetListResult", + "RecordSetUpdateParameters", + "Resource", + "SoaRecord", + "SrvRecord", + "SubResource", + "TrackedResource", + "TxtRecord", + "Zone", + "ZoneListResult", + "ZoneUpdate", + "RecordType", + "ZoneType", ] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_03_01_preview/models/_dns_management_client_enums.py b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_03_01_preview/models/_dns_management_client_enums.py index f2abeece2155..ca561301a0f6 100644 --- a/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_03_01_preview/models/_dns_management_client_enums.py +++ b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_03_01_preview/models/_dns_management_client_enums.py @@ -6,27 +6,12 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from enum import Enum, EnumMeta -from six import with_metaclass +from enum import Enum +from azure.core import CaseInsensitiveEnumMeta -class _CaseInsensitiveEnumMeta(EnumMeta): - def __getitem__(self, name): - return super().__getitem__(name.upper()) - def __getattr__(cls, name): - """Return the enum member matching `name` - We use __getattr__ instead of descriptors or inserting into the enum - class' __dict__ in order to support `name` and `value` being both - properties for enum members (which live in the class' __dict__) and - enum members themselves. - """ - try: - return cls._member_map_[name.upper()] - except KeyError: - raise AttributeError(name) - - -class RecordType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): +class RecordType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """RecordType.""" A = "A" AAAA = "AAAA" @@ -39,9 +24,9 @@ class RecordType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): SRV = "SRV" TXT = "TXT" -class ZoneType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """The type of this DNS zone (Public or Private). - """ + +class ZoneType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The type of this DNS zone (Public or Private).""" PUBLIC = "Public" PRIVATE = "Private" diff --git a/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_03_01_preview/models/_models.py b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_03_01_preview/models/_models.py deleted file mode 100644 index 11d7260189db..000000000000 --- a/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_03_01_preview/models/_models.py +++ /dev/null @@ -1,659 +0,0 @@ -# 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. -# -------------------------------------------------------------------------- - -import msrest.serialization - - -class AaaaRecord(msrest.serialization.Model): - """An AAAA record. - - :param ipv6_address: The IPv6 address of this AAAA record. - :type ipv6_address: str - """ - - _attribute_map = { - 'ipv6_address': {'key': 'ipv6Address', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(AaaaRecord, self).__init__(**kwargs) - self.ipv6_address = kwargs.get('ipv6_address', None) - - -class ARecord(msrest.serialization.Model): - """An A record. - - :param ipv4_address: The IPv4 address of this A record. - :type ipv4_address: str - """ - - _attribute_map = { - 'ipv4_address': {'key': 'ipv4Address', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(ARecord, self).__init__(**kwargs) - self.ipv4_address = kwargs.get('ipv4_address', None) - - -class CaaRecord(msrest.serialization.Model): - """A CAA record. - - :param flags: The flags for this CAA record as an integer between 0 and 255. - :type flags: int - :param tag: The tag for this CAA record. - :type tag: str - :param value: The value for this CAA record. - :type value: str - """ - - _attribute_map = { - 'flags': {'key': 'flags', 'type': 'int'}, - 'tag': {'key': 'tag', 'type': 'str'}, - 'value': {'key': 'value', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(CaaRecord, self).__init__(**kwargs) - self.flags = kwargs.get('flags', None) - self.tag = kwargs.get('tag', None) - self.value = kwargs.get('value', None) - - -class CloudErrorBody(msrest.serialization.Model): - """An error response from the service. - - :param code: An identifier for the error. Codes are invariant and are intended to be consumed - programmatically. - :type code: str - :param message: A message describing the error, intended to be suitable for display in a user - interface. - :type message: str - :param target: The target of the particular error. For example, the name of the property in - error. - :type target: str - :param details: A list of additional details about the error. - :type details: list[~azure.mgmt.dns.v2018_03_01_preview.models.CloudErrorBody] - """ - - _attribute_map = { - 'code': {'key': 'code', 'type': 'str'}, - 'message': {'key': 'message', 'type': 'str'}, - 'target': {'key': 'target', 'type': 'str'}, - 'details': {'key': 'details', 'type': '[CloudErrorBody]'}, - } - - def __init__( - self, - **kwargs - ): - super(CloudErrorBody, self).__init__(**kwargs) - self.code = kwargs.get('code', None) - self.message = kwargs.get('message', None) - self.target = kwargs.get('target', None) - self.details = kwargs.get('details', None) - - -class CnameRecord(msrest.serialization.Model): - """A CNAME record. - - :param cname: The canonical name for this CNAME record. - :type cname: str - """ - - _attribute_map = { - 'cname': {'key': 'cname', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(CnameRecord, self).__init__(**kwargs) - self.cname = kwargs.get('cname', None) - - -class MxRecord(msrest.serialization.Model): - """An MX record. - - :param preference: The preference value for this MX record. - :type preference: int - :param exchange: The domain name of the mail host for this MX record. - :type exchange: str - """ - - _attribute_map = { - 'preference': {'key': 'preference', 'type': 'int'}, - 'exchange': {'key': 'exchange', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(MxRecord, self).__init__(**kwargs) - self.preference = kwargs.get('preference', None) - self.exchange = kwargs.get('exchange', None) - - -class NsRecord(msrest.serialization.Model): - """An NS record. - - :param nsdname: The name server name for this NS record. - :type nsdname: str - """ - - _attribute_map = { - 'nsdname': {'key': 'nsdname', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(NsRecord, self).__init__(**kwargs) - self.nsdname = kwargs.get('nsdname', None) - - -class PtrRecord(msrest.serialization.Model): - """A PTR record. - - :param ptrdname: The PTR target domain name for this PTR record. - :type ptrdname: str - """ - - _attribute_map = { - 'ptrdname': {'key': 'ptrdname', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(PtrRecord, self).__init__(**kwargs) - self.ptrdname = kwargs.get('ptrdname', None) - - -class RecordSet(msrest.serialization.Model): - """Describes a DNS record set (a collection of DNS records with the same name and type). - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: The ID of the record set. - :vartype id: str - :ivar name: The name of the record set. - :vartype name: str - :ivar type: The type of the record set. - :vartype type: str - :param etag: The etag of the record set. - :type etag: str - :param metadata: The metadata attached to the record set. - :type metadata: dict[str, str] - :param ttl: The TTL (time-to-live) of the records in the record set. - :type ttl: long - :ivar fqdn: Fully qualified domain name of the record set. - :vartype fqdn: str - :param a_records: The list of A records in the record set. - :type a_records: list[~azure.mgmt.dns.v2018_03_01_preview.models.ARecord] - :param aaaa_records: The list of AAAA records in the record set. - :type aaaa_records: list[~azure.mgmt.dns.v2018_03_01_preview.models.AaaaRecord] - :param mx_records: The list of MX records in the record set. - :type mx_records: list[~azure.mgmt.dns.v2018_03_01_preview.models.MxRecord] - :param ns_records: The list of NS records in the record set. - :type ns_records: list[~azure.mgmt.dns.v2018_03_01_preview.models.NsRecord] - :param ptr_records: The list of PTR records in the record set. - :type ptr_records: list[~azure.mgmt.dns.v2018_03_01_preview.models.PtrRecord] - :param srv_records: The list of SRV records in the record set. - :type srv_records: list[~azure.mgmt.dns.v2018_03_01_preview.models.SrvRecord] - :param txt_records: The list of TXT records in the record set. - :type txt_records: list[~azure.mgmt.dns.v2018_03_01_preview.models.TxtRecord] - :param cname_record: The CNAME record in the record set. - :type cname_record: ~azure.mgmt.dns.v2018_03_01_preview.models.CnameRecord - :param soa_record: The SOA record in the record set. - :type soa_record: ~azure.mgmt.dns.v2018_03_01_preview.models.SoaRecord - :param caa_records: The list of CAA records in the record set. - :type caa_records: list[~azure.mgmt.dns.v2018_03_01_preview.models.CaaRecord] - """ - - _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'fqdn': {'readonly': True}, - } - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'etag': {'key': 'etag', 'type': 'str'}, - 'metadata': {'key': 'properties.metadata', 'type': '{str}'}, - 'ttl': {'key': 'properties.TTL', 'type': 'long'}, - 'fqdn': {'key': 'properties.fqdn', 'type': 'str'}, - 'a_records': {'key': 'properties.ARecords', 'type': '[ARecord]'}, - 'aaaa_records': {'key': 'properties.AAAARecords', 'type': '[AaaaRecord]'}, - 'mx_records': {'key': 'properties.MXRecords', 'type': '[MxRecord]'}, - 'ns_records': {'key': 'properties.NSRecords', 'type': '[NsRecord]'}, - 'ptr_records': {'key': 'properties.PTRRecords', 'type': '[PtrRecord]'}, - 'srv_records': {'key': 'properties.SRVRecords', 'type': '[SrvRecord]'}, - 'txt_records': {'key': 'properties.TXTRecords', 'type': '[TxtRecord]'}, - 'cname_record': {'key': 'properties.CNAMERecord', 'type': 'CnameRecord'}, - 'soa_record': {'key': 'properties.SOARecord', 'type': 'SoaRecord'}, - 'caa_records': {'key': 'properties.caaRecords', 'type': '[CaaRecord]'}, - } - - def __init__( - self, - **kwargs - ): - super(RecordSet, self).__init__(**kwargs) - self.id = None - self.name = None - self.type = None - self.etag = kwargs.get('etag', None) - self.metadata = kwargs.get('metadata', None) - self.ttl = kwargs.get('ttl', None) - self.fqdn = None - self.a_records = kwargs.get('a_records', None) - self.aaaa_records = kwargs.get('aaaa_records', None) - self.mx_records = kwargs.get('mx_records', None) - self.ns_records = kwargs.get('ns_records', None) - self.ptr_records = kwargs.get('ptr_records', None) - self.srv_records = kwargs.get('srv_records', None) - self.txt_records = kwargs.get('txt_records', None) - self.cname_record = kwargs.get('cname_record', None) - self.soa_record = kwargs.get('soa_record', None) - self.caa_records = kwargs.get('caa_records', None) - - -class RecordSetListResult(msrest.serialization.Model): - """The response to a record set List operation. - - Variables are only populated by the server, and will be ignored when sending a request. - - :param value: Information about the record sets in the response. - :type value: list[~azure.mgmt.dns.v2018_03_01_preview.models.RecordSet] - :ivar next_link: The continuation token for the next page of results. - :vartype next_link: str - """ - - _validation = { - 'next_link': {'readonly': True}, - } - - _attribute_map = { - 'value': {'key': 'value', 'type': '[RecordSet]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(RecordSetListResult, self).__init__(**kwargs) - self.value = kwargs.get('value', None) - self.next_link = None - - -class RecordSetUpdateParameters(msrest.serialization.Model): - """Parameters supplied to update a record set. - - :param record_set: Specifies information about the record set being updated. - :type record_set: ~azure.mgmt.dns.v2018_03_01_preview.models.RecordSet - """ - - _attribute_map = { - 'record_set': {'key': 'RecordSet', 'type': 'RecordSet'}, - } - - def __init__( - self, - **kwargs - ): - super(RecordSetUpdateParameters, self).__init__(**kwargs) - self.record_set = kwargs.get('record_set', None) - - -class Resource(msrest.serialization.Model): - """Common fields that are returned in the response for all Azure Resource Manager resources. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: Fully qualified resource ID for the resource. Ex - - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. - :vartype id: str - :ivar name: The name of the resource. - :vartype name: str - :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or - "Microsoft.Storage/storageAccounts". - :vartype type: str - """ - - _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - } - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(Resource, self).__init__(**kwargs) - self.id = None - self.name = None - self.type = None - - -class SoaRecord(msrest.serialization.Model): - """An SOA record. - - :param host: The domain name of the authoritative name server for this SOA record. - :type host: str - :param email: The email contact for this SOA record. - :type email: str - :param serial_number: The serial number for this SOA record. - :type serial_number: long - :param refresh_time: The refresh value for this SOA record. - :type refresh_time: long - :param retry_time: The retry time for this SOA record. - :type retry_time: long - :param expire_time: The expire time for this SOA record. - :type expire_time: long - :param minimum_ttl: The minimum value for this SOA record. By convention this is used to - determine the negative caching duration. - :type minimum_ttl: long - """ - - _attribute_map = { - 'host': {'key': 'host', 'type': 'str'}, - 'email': {'key': 'email', 'type': 'str'}, - 'serial_number': {'key': 'serialNumber', 'type': 'long'}, - 'refresh_time': {'key': 'refreshTime', 'type': 'long'}, - 'retry_time': {'key': 'retryTime', 'type': 'long'}, - 'expire_time': {'key': 'expireTime', 'type': 'long'}, - 'minimum_ttl': {'key': 'minimumTTL', 'type': 'long'}, - } - - def __init__( - self, - **kwargs - ): - super(SoaRecord, self).__init__(**kwargs) - self.host = kwargs.get('host', None) - self.email = kwargs.get('email', None) - self.serial_number = kwargs.get('serial_number', None) - self.refresh_time = kwargs.get('refresh_time', None) - self.retry_time = kwargs.get('retry_time', None) - self.expire_time = kwargs.get('expire_time', None) - self.minimum_ttl = kwargs.get('minimum_ttl', None) - - -class SrvRecord(msrest.serialization.Model): - """An SRV record. - - :param priority: The priority value for this SRV record. - :type priority: int - :param weight: The weight value for this SRV record. - :type weight: int - :param port: The port value for this SRV record. - :type port: int - :param target: The target domain name for this SRV record. - :type target: str - """ - - _attribute_map = { - 'priority': {'key': 'priority', 'type': 'int'}, - 'weight': {'key': 'weight', 'type': 'int'}, - 'port': {'key': 'port', 'type': 'int'}, - 'target': {'key': 'target', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(SrvRecord, self).__init__(**kwargs) - self.priority = kwargs.get('priority', None) - self.weight = kwargs.get('weight', None) - self.port = kwargs.get('port', None) - self.target = kwargs.get('target', None) - - -class SubResource(msrest.serialization.Model): - """A reference to a another resource. - - :param id: Resource Id. - :type id: str - """ - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(SubResource, self).__init__(**kwargs) - self.id = kwargs.get('id', None) - - -class TrackedResource(Resource): - """The resource model definition for an Azure Resource Manager tracked top level resource which has 'tags' and a 'location'. - - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to Azure. - - :ivar id: Fully qualified resource ID for the resource. Ex - - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. - :vartype id: str - :ivar name: The name of the resource. - :vartype name: str - :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or - "Microsoft.Storage/storageAccounts". - :vartype type: str - :param tags: A set of tags. Resource tags. - :type tags: dict[str, str] - :param location: Required. The geo-location where the resource lives. - :type location: str - """ - - _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'location': {'required': True}, - } - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'tags': {'key': 'tags', 'type': '{str}'}, - 'location': {'key': 'location', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(TrackedResource, self).__init__(**kwargs) - self.tags = kwargs.get('tags', None) - self.location = kwargs['location'] - - -class TxtRecord(msrest.serialization.Model): - """A TXT record. - - :param value: The text value of this TXT record. - :type value: list[str] - """ - - _attribute_map = { - 'value': {'key': 'value', 'type': '[str]'}, - } - - def __init__( - self, - **kwargs - ): - super(TxtRecord, self).__init__(**kwargs) - self.value = kwargs.get('value', None) - - -class Zone(TrackedResource): - """Describes a DNS zone. - - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to Azure. - - :ivar id: Fully qualified resource ID for the resource. Ex - - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. - :vartype id: str - :ivar name: The name of the resource. - :vartype name: str - :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or - "Microsoft.Storage/storageAccounts". - :vartype type: str - :param tags: A set of tags. Resource tags. - :type tags: dict[str, str] - :param location: Required. The geo-location where the resource lives. - :type location: str - :param etag: The etag of the zone. - :type etag: str - :ivar max_number_of_record_sets: The maximum number of record sets that can be created in this - DNS zone. This is a read-only property and any attempt to set this value will be ignored. - :vartype max_number_of_record_sets: long - :ivar max_number_of_records_per_record_set: The maximum number of records per record set that - can be created in this DNS zone. This is a read-only property and any attempt to set this - value will be ignored. - :vartype max_number_of_records_per_record_set: long - :ivar number_of_record_sets: The current number of record sets in this DNS zone. This is a - read-only property and any attempt to set this value will be ignored. - :vartype number_of_record_sets: long - :ivar name_servers: The name servers for this DNS zone. This is a read-only property and any - attempt to set this value will be ignored. - :vartype name_servers: list[str] - :param zone_type: The type of this DNS zone (Public or Private). Possible values include: - "Public", "Private". Default value: "Public". - :type zone_type: str or ~azure.mgmt.dns.v2018_03_01_preview.models.ZoneType - :param registration_virtual_networks: A list of references to virtual networks that register - hostnames in this DNS zone. This is a only when ZoneType is Private. - :type registration_virtual_networks: - list[~azure.mgmt.dns.v2018_03_01_preview.models.SubResource] - :param resolution_virtual_networks: A list of references to virtual networks that resolve - records in this DNS zone. This is a only when ZoneType is Private. - :type resolution_virtual_networks: list[~azure.mgmt.dns.v2018_03_01_preview.models.SubResource] - """ - - _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'location': {'required': True}, - 'max_number_of_record_sets': {'readonly': True}, - 'max_number_of_records_per_record_set': {'readonly': True}, - 'number_of_record_sets': {'readonly': True}, - 'name_servers': {'readonly': True}, - } - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'tags': {'key': 'tags', 'type': '{str}'}, - 'location': {'key': 'location', 'type': 'str'}, - 'etag': {'key': 'etag', 'type': 'str'}, - 'max_number_of_record_sets': {'key': 'properties.maxNumberOfRecordSets', 'type': 'long'}, - 'max_number_of_records_per_record_set': {'key': 'properties.maxNumberOfRecordsPerRecordSet', 'type': 'long'}, - 'number_of_record_sets': {'key': 'properties.numberOfRecordSets', 'type': 'long'}, - 'name_servers': {'key': 'properties.nameServers', 'type': '[str]'}, - 'zone_type': {'key': 'properties.zoneType', 'type': 'str'}, - 'registration_virtual_networks': {'key': 'properties.registrationVirtualNetworks', 'type': '[SubResource]'}, - 'resolution_virtual_networks': {'key': 'properties.resolutionVirtualNetworks', 'type': '[SubResource]'}, - } - - def __init__( - self, - **kwargs - ): - super(Zone, self).__init__(**kwargs) - self.etag = kwargs.get('etag', None) - self.max_number_of_record_sets = None - self.max_number_of_records_per_record_set = None - self.number_of_record_sets = None - self.name_servers = None - self.zone_type = kwargs.get('zone_type', "Public") - self.registration_virtual_networks = kwargs.get('registration_virtual_networks', None) - self.resolution_virtual_networks = kwargs.get('resolution_virtual_networks', None) - - -class ZoneListResult(msrest.serialization.Model): - """The response to a Zone List or ListAll operation. - - Variables are only populated by the server, and will be ignored when sending a request. - - :param value: Information about the DNS zones. - :type value: list[~azure.mgmt.dns.v2018_03_01_preview.models.Zone] - :ivar next_link: The continuation token for the next page of results. - :vartype next_link: str - """ - - _validation = { - 'next_link': {'readonly': True}, - } - - _attribute_map = { - 'value': {'key': 'value', 'type': '[Zone]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(ZoneListResult, self).__init__(**kwargs) - self.value = kwargs.get('value', None) - self.next_link = None - - -class ZoneUpdate(msrest.serialization.Model): - """Describes a request to update a DNS zone. - - :param tags: A set of tags. Resource tags. - :type tags: dict[str, str] - """ - - _attribute_map = { - 'tags': {'key': 'tags', 'type': '{str}'}, - } - - def __init__( - self, - **kwargs - ): - super(ZoneUpdate, self).__init__(**kwargs) - self.tags = kwargs.get('tags', None) diff --git a/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_03_01_preview/models/_models_py3.py b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_03_01_preview/models/_models_py3.py index 8288d18b8b61..d084c604b892 100644 --- a/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_03_01_preview/models/_models_py3.py +++ b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_03_01_preview/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. @@ -6,107 +7,110 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Dict, List, Optional, Union +from typing import Any, Dict, List, Optional, TYPE_CHECKING, Union -import msrest.serialization +from ... import _serialization -from ._dns_management_client_enums import * +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from .. import models as _models -class AaaaRecord(msrest.serialization.Model): +class AaaaRecord(_serialization.Model): """An AAAA record. - :param ipv6_address: The IPv6 address of this AAAA record. - :type ipv6_address: str + :ivar ipv6_address: The IPv6 address of this AAAA record. + :vartype ipv6_address: str """ _attribute_map = { - 'ipv6_address': {'key': 'ipv6Address', 'type': 'str'}, + "ipv6_address": {"key": "ipv6Address", "type": "str"}, } - def __init__( - self, - *, - ipv6_address: Optional[str] = None, - **kwargs - ): - super(AaaaRecord, self).__init__(**kwargs) + def __init__(self, *, ipv6_address: Optional[str] = None, **kwargs: Any) -> None: + """ + :keyword ipv6_address: The IPv6 address of this AAAA record. + :paramtype ipv6_address: str + """ + super().__init__(**kwargs) self.ipv6_address = ipv6_address -class ARecord(msrest.serialization.Model): +class ARecord(_serialization.Model): """An A record. - :param ipv4_address: The IPv4 address of this A record. - :type ipv4_address: str + :ivar ipv4_address: The IPv4 address of this A record. + :vartype ipv4_address: str """ _attribute_map = { - 'ipv4_address': {'key': 'ipv4Address', 'type': 'str'}, + "ipv4_address": {"key": "ipv4Address", "type": "str"}, } - def __init__( - self, - *, - ipv4_address: Optional[str] = None, - **kwargs - ): - super(ARecord, self).__init__(**kwargs) + def __init__(self, *, ipv4_address: Optional[str] = None, **kwargs: Any) -> None: + """ + :keyword ipv4_address: The IPv4 address of this A record. + :paramtype ipv4_address: str + """ + super().__init__(**kwargs) self.ipv4_address = ipv4_address -class CaaRecord(msrest.serialization.Model): +class CaaRecord(_serialization.Model): """A CAA record. - :param flags: The flags for this CAA record as an integer between 0 and 255. - :type flags: int - :param tag: The tag for this CAA record. - :type tag: str - :param value: The value for this CAA record. - :type value: str + :ivar flags: The flags for this CAA record as an integer between 0 and 255. + :vartype flags: int + :ivar tag: The tag for this CAA record. + :vartype tag: str + :ivar value: The value for this CAA record. + :vartype value: str """ _attribute_map = { - 'flags': {'key': 'flags', 'type': 'int'}, - 'tag': {'key': 'tag', 'type': 'str'}, - 'value': {'key': 'value', 'type': 'str'}, + "flags": {"key": "flags", "type": "int"}, + "tag": {"key": "tag", "type": "str"}, + "value": {"key": "value", "type": "str"}, } def __init__( - self, - *, - flags: Optional[int] = None, - tag: Optional[str] = None, - value: Optional[str] = None, - **kwargs - ): - super(CaaRecord, self).__init__(**kwargs) + self, *, flags: Optional[int] = None, tag: Optional[str] = None, value: Optional[str] = None, **kwargs: Any + ) -> None: + """ + :keyword flags: The flags for this CAA record as an integer between 0 and 255. + :paramtype flags: int + :keyword tag: The tag for this CAA record. + :paramtype tag: str + :keyword value: The value for this CAA record. + :paramtype value: str + """ + super().__init__(**kwargs) self.flags = flags self.tag = tag self.value = value -class CloudErrorBody(msrest.serialization.Model): +class CloudErrorBody(_serialization.Model): """An error response from the service. - :param code: An identifier for the error. Codes are invariant and are intended to be consumed + :ivar code: An identifier for the error. Codes are invariant and are intended to be consumed programmatically. - :type code: str - :param message: A message describing the error, intended to be suitable for display in a user + :vartype code: str + :ivar message: A message describing the error, intended to be suitable for display in a user interface. - :type message: str - :param target: The target of the particular error. For example, the name of the property in + :vartype message: str + :ivar target: The target of the particular error. For example, the name of the property in error. - :type target: str - :param details: A list of additional details about the error. - :type details: list[~azure.mgmt.dns.v2018_03_01_preview.models.CloudErrorBody] + :vartype target: str + :ivar details: A list of additional details about the error. + :vartype details: list[~azure.mgmt.dns.v2018_03_01_preview.models.CloudErrorBody] """ _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__( @@ -115,106 +119,116 @@ def __init__( code: Optional[str] = None, message: Optional[str] = None, target: Optional[str] = None, - details: Optional[List["CloudErrorBody"]] = None, - **kwargs - ): - super(CloudErrorBody, self).__init__(**kwargs) + details: Optional[List["_models.CloudErrorBody"]] = None, + **kwargs: Any + ) -> None: + """ + :keyword code: An identifier for the error. Codes are invariant and are intended to be consumed + programmatically. + :paramtype code: str + :keyword message: A message describing the error, intended to be suitable for display in a user + interface. + :paramtype message: str + :keyword target: The target of the particular error. For example, the name of the property in + error. + :paramtype target: str + :keyword details: A list of additional details about the error. + :paramtype details: list[~azure.mgmt.dns.v2018_03_01_preview.models.CloudErrorBody] + """ + super().__init__(**kwargs) self.code = code self.message = message self.target = target self.details = details -class CnameRecord(msrest.serialization.Model): +class CnameRecord(_serialization.Model): """A CNAME record. - :param cname: The canonical name for this CNAME record. - :type cname: str + :ivar cname: The canonical name for this CNAME record. + :vartype cname: str """ _attribute_map = { - 'cname': {'key': 'cname', 'type': 'str'}, + "cname": {"key": "cname", "type": "str"}, } - def __init__( - self, - *, - cname: Optional[str] = None, - **kwargs - ): - super(CnameRecord, self).__init__(**kwargs) + def __init__(self, *, cname: Optional[str] = None, **kwargs: Any) -> None: + """ + :keyword cname: The canonical name for this CNAME record. + :paramtype cname: str + """ + super().__init__(**kwargs) self.cname = cname -class MxRecord(msrest.serialization.Model): +class MxRecord(_serialization.Model): """An MX record. - :param preference: The preference value for this MX record. - :type preference: int - :param exchange: The domain name of the mail host for this MX record. - :type exchange: str + :ivar preference: The preference value for this MX record. + :vartype preference: int + :ivar exchange: The domain name of the mail host for this MX record. + :vartype exchange: str """ _attribute_map = { - 'preference': {'key': 'preference', 'type': 'int'}, - 'exchange': {'key': 'exchange', 'type': 'str'}, + "preference": {"key": "preference", "type": "int"}, + "exchange": {"key": "exchange", "type": "str"}, } - def __init__( - self, - *, - preference: Optional[int] = None, - exchange: Optional[str] = None, - **kwargs - ): - super(MxRecord, self).__init__(**kwargs) + def __init__(self, *, preference: Optional[int] = None, exchange: Optional[str] = None, **kwargs: Any) -> None: + """ + :keyword preference: The preference value for this MX record. + :paramtype preference: int + :keyword exchange: The domain name of the mail host for this MX record. + :paramtype exchange: str + """ + super().__init__(**kwargs) self.preference = preference self.exchange = exchange -class NsRecord(msrest.serialization.Model): +class NsRecord(_serialization.Model): """An NS record. - :param nsdname: The name server name for this NS record. - :type nsdname: str + :ivar nsdname: The name server name for this NS record. + :vartype nsdname: str """ _attribute_map = { - 'nsdname': {'key': 'nsdname', 'type': 'str'}, + "nsdname": {"key": "nsdname", "type": "str"}, } - def __init__( - self, - *, - nsdname: Optional[str] = None, - **kwargs - ): - super(NsRecord, self).__init__(**kwargs) + def __init__(self, *, nsdname: Optional[str] = None, **kwargs: Any) -> None: + """ + :keyword nsdname: The name server name for this NS record. + :paramtype nsdname: str + """ + super().__init__(**kwargs) self.nsdname = nsdname -class PtrRecord(msrest.serialization.Model): +class PtrRecord(_serialization.Model): """A PTR record. - :param ptrdname: The PTR target domain name for this PTR record. - :type ptrdname: str + :ivar ptrdname: The PTR target domain name for this PTR record. + :vartype ptrdname: str """ _attribute_map = { - 'ptrdname': {'key': 'ptrdname', 'type': 'str'}, + "ptrdname": {"key": "ptrdname", "type": "str"}, } - def __init__( - self, - *, - ptrdname: Optional[str] = None, - **kwargs - ): - super(PtrRecord, self).__init__(**kwargs) + def __init__(self, *, ptrdname: Optional[str] = None, **kwargs: Any) -> None: + """ + :keyword ptrdname: The PTR target domain name for this PTR record. + :paramtype ptrdname: str + """ + super().__init__(**kwargs) self.ptrdname = ptrdname -class RecordSet(msrest.serialization.Model): +class RecordSet(_serialization.Model): # pylint: disable=too-many-instance-attributes """Describes a DNS record set (a collection of DNS records with the same name and type). Variables are only populated by the server, and will be ignored when sending a request. @@ -225,61 +239,61 @@ class RecordSet(msrest.serialization.Model): :vartype name: str :ivar type: The type of the record set. :vartype type: str - :param etag: The etag of the record set. - :type etag: str - :param metadata: The metadata attached to the record set. - :type metadata: dict[str, str] - :param ttl: The TTL (time-to-live) of the records in the record set. - :type ttl: long + :ivar etag: The etag of the record set. + :vartype etag: str + :ivar metadata: The metadata attached to the record set. + :vartype metadata: dict[str, str] + :ivar ttl: The TTL (time-to-live) of the records in the record set. + :vartype ttl: int :ivar fqdn: Fully qualified domain name of the record set. :vartype fqdn: str - :param a_records: The list of A records in the record set. - :type a_records: list[~azure.mgmt.dns.v2018_03_01_preview.models.ARecord] - :param aaaa_records: The list of AAAA records in the record set. - :type aaaa_records: list[~azure.mgmt.dns.v2018_03_01_preview.models.AaaaRecord] - :param mx_records: The list of MX records in the record set. - :type mx_records: list[~azure.mgmt.dns.v2018_03_01_preview.models.MxRecord] - :param ns_records: The list of NS records in the record set. - :type ns_records: list[~azure.mgmt.dns.v2018_03_01_preview.models.NsRecord] - :param ptr_records: The list of PTR records in the record set. - :type ptr_records: list[~azure.mgmt.dns.v2018_03_01_preview.models.PtrRecord] - :param srv_records: The list of SRV records in the record set. - :type srv_records: list[~azure.mgmt.dns.v2018_03_01_preview.models.SrvRecord] - :param txt_records: The list of TXT records in the record set. - :type txt_records: list[~azure.mgmt.dns.v2018_03_01_preview.models.TxtRecord] - :param cname_record: The CNAME record in the record set. - :type cname_record: ~azure.mgmt.dns.v2018_03_01_preview.models.CnameRecord - :param soa_record: The SOA record in the record set. - :type soa_record: ~azure.mgmt.dns.v2018_03_01_preview.models.SoaRecord - :param caa_records: The list of CAA records in the record set. - :type caa_records: list[~azure.mgmt.dns.v2018_03_01_preview.models.CaaRecord] + :ivar a_records: The list of A records in the record set. + :vartype a_records: list[~azure.mgmt.dns.v2018_03_01_preview.models.ARecord] + :ivar aaaa_records: The list of AAAA records in the record set. + :vartype aaaa_records: list[~azure.mgmt.dns.v2018_03_01_preview.models.AaaaRecord] + :ivar mx_records: The list of MX records in the record set. + :vartype mx_records: list[~azure.mgmt.dns.v2018_03_01_preview.models.MxRecord] + :ivar ns_records: The list of NS records in the record set. + :vartype ns_records: list[~azure.mgmt.dns.v2018_03_01_preview.models.NsRecord] + :ivar ptr_records: The list of PTR records in the record set. + :vartype ptr_records: list[~azure.mgmt.dns.v2018_03_01_preview.models.PtrRecord] + :ivar srv_records: The list of SRV records in the record set. + :vartype srv_records: list[~azure.mgmt.dns.v2018_03_01_preview.models.SrvRecord] + :ivar txt_records: The list of TXT records in the record set. + :vartype txt_records: list[~azure.mgmt.dns.v2018_03_01_preview.models.TxtRecord] + :ivar cname_record: The CNAME record in the record set. + :vartype cname_record: ~azure.mgmt.dns.v2018_03_01_preview.models.CnameRecord + :ivar soa_record: The SOA record in the record set. + :vartype soa_record: ~azure.mgmt.dns.v2018_03_01_preview.models.SoaRecord + :ivar caa_records: The list of CAA records in the record set. + :vartype caa_records: list[~azure.mgmt.dns.v2018_03_01_preview.models.CaaRecord] """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'fqdn': {'readonly': True}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "fqdn": {"readonly": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'etag': {'key': 'etag', 'type': 'str'}, - 'metadata': {'key': 'properties.metadata', 'type': '{str}'}, - 'ttl': {'key': 'properties.TTL', 'type': 'long'}, - 'fqdn': {'key': 'properties.fqdn', 'type': 'str'}, - 'a_records': {'key': 'properties.ARecords', 'type': '[ARecord]'}, - 'aaaa_records': {'key': 'properties.AAAARecords', 'type': '[AaaaRecord]'}, - 'mx_records': {'key': 'properties.MXRecords', 'type': '[MxRecord]'}, - 'ns_records': {'key': 'properties.NSRecords', 'type': '[NsRecord]'}, - 'ptr_records': {'key': 'properties.PTRRecords', 'type': '[PtrRecord]'}, - 'srv_records': {'key': 'properties.SRVRecords', 'type': '[SrvRecord]'}, - 'txt_records': {'key': 'properties.TXTRecords', 'type': '[TxtRecord]'}, - 'cname_record': {'key': 'properties.CNAMERecord', 'type': 'CnameRecord'}, - 'soa_record': {'key': 'properties.SOARecord', 'type': 'SoaRecord'}, - 'caa_records': {'key': 'properties.caaRecords', 'type': '[CaaRecord]'}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "etag": {"key": "etag", "type": "str"}, + "metadata": {"key": "properties.metadata", "type": "{str}"}, + "ttl": {"key": "properties.TTL", "type": "int"}, + "fqdn": {"key": "properties.fqdn", "type": "str"}, + "a_records": {"key": "properties.ARecords", "type": "[ARecord]"}, + "aaaa_records": {"key": "properties.AAAARecords", "type": "[AaaaRecord]"}, + "mx_records": {"key": "properties.MXRecords", "type": "[MxRecord]"}, + "ns_records": {"key": "properties.NSRecords", "type": "[NsRecord]"}, + "ptr_records": {"key": "properties.PTRRecords", "type": "[PtrRecord]"}, + "srv_records": {"key": "properties.SRVRecords", "type": "[SrvRecord]"}, + "txt_records": {"key": "properties.TXTRecords", "type": "[TxtRecord]"}, + "cname_record": {"key": "properties.CNAMERecord", "type": "CnameRecord"}, + "soa_record": {"key": "properties.SOARecord", "type": "SoaRecord"}, + "caa_records": {"key": "properties.caaRecords", "type": "[CaaRecord]"}, } def __init__( @@ -288,19 +302,47 @@ def __init__( etag: Optional[str] = None, metadata: Optional[Dict[str, str]] = None, ttl: Optional[int] = None, - a_records: Optional[List["ARecord"]] = None, - aaaa_records: Optional[List["AaaaRecord"]] = None, - mx_records: Optional[List["MxRecord"]] = None, - ns_records: Optional[List["NsRecord"]] = None, - ptr_records: Optional[List["PtrRecord"]] = None, - srv_records: Optional[List["SrvRecord"]] = None, - txt_records: Optional[List["TxtRecord"]] = None, - cname_record: Optional["CnameRecord"] = None, - soa_record: Optional["SoaRecord"] = None, - caa_records: Optional[List["CaaRecord"]] = None, - **kwargs - ): - super(RecordSet, self).__init__(**kwargs) + a_records: Optional[List["_models.ARecord"]] = None, + aaaa_records: Optional[List["_models.AaaaRecord"]] = None, + mx_records: Optional[List["_models.MxRecord"]] = None, + ns_records: Optional[List["_models.NsRecord"]] = None, + ptr_records: Optional[List["_models.PtrRecord"]] = None, + srv_records: Optional[List["_models.SrvRecord"]] = None, + txt_records: Optional[List["_models.TxtRecord"]] = None, + cname_record: Optional["_models.CnameRecord"] = None, + soa_record: Optional["_models.SoaRecord"] = None, + caa_records: Optional[List["_models.CaaRecord"]] = None, + **kwargs: Any + ) -> None: + """ + :keyword etag: The etag of the record set. + :paramtype etag: str + :keyword metadata: The metadata attached to the record set. + :paramtype metadata: dict[str, str] + :keyword ttl: The TTL (time-to-live) of the records in the record set. + :paramtype ttl: int + :keyword a_records: The list of A records in the record set. + :paramtype a_records: list[~azure.mgmt.dns.v2018_03_01_preview.models.ARecord] + :keyword aaaa_records: The list of AAAA records in the record set. + :paramtype aaaa_records: list[~azure.mgmt.dns.v2018_03_01_preview.models.AaaaRecord] + :keyword mx_records: The list of MX records in the record set. + :paramtype mx_records: list[~azure.mgmt.dns.v2018_03_01_preview.models.MxRecord] + :keyword ns_records: The list of NS records in the record set. + :paramtype ns_records: list[~azure.mgmt.dns.v2018_03_01_preview.models.NsRecord] + :keyword ptr_records: The list of PTR records in the record set. + :paramtype ptr_records: list[~azure.mgmt.dns.v2018_03_01_preview.models.PtrRecord] + :keyword srv_records: The list of SRV records in the record set. + :paramtype srv_records: list[~azure.mgmt.dns.v2018_03_01_preview.models.SrvRecord] + :keyword txt_records: The list of TXT records in the record set. + :paramtype txt_records: list[~azure.mgmt.dns.v2018_03_01_preview.models.TxtRecord] + :keyword cname_record: The CNAME record in the record set. + :paramtype cname_record: ~azure.mgmt.dns.v2018_03_01_preview.models.CnameRecord + :keyword soa_record: The SOA record in the record set. + :paramtype soa_record: ~azure.mgmt.dns.v2018_03_01_preview.models.SoaRecord + :keyword caa_records: The list of CAA records in the record set. + :paramtype caa_records: list[~azure.mgmt.dns.v2018_03_01_preview.models.CaaRecord] + """ + super().__init__(**kwargs) self.id = None self.name = None self.type = None @@ -320,59 +362,57 @@ def __init__( self.caa_records = caa_records -class RecordSetListResult(msrest.serialization.Model): +class RecordSetListResult(_serialization.Model): """The response to a record set List operation. Variables are only populated by the server, and will be ignored when sending a request. - :param value: Information about the record sets in the response. - :type value: list[~azure.mgmt.dns.v2018_03_01_preview.models.RecordSet] + :ivar value: Information about the record sets in the response. + :vartype value: list[~azure.mgmt.dns.v2018_03_01_preview.models.RecordSet] :ivar next_link: The continuation token for the next page of results. :vartype next_link: str """ _validation = { - 'next_link': {'readonly': True}, + "next_link": {"readonly": True}, } _attribute_map = { - 'value': {'key': 'value', 'type': '[RecordSet]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "value": {"key": "value", "type": "[RecordSet]"}, + "next_link": {"key": "nextLink", "type": "str"}, } - def __init__( - self, - *, - value: Optional[List["RecordSet"]] = None, - **kwargs - ): - super(RecordSetListResult, self).__init__(**kwargs) + def __init__(self, *, value: Optional[List["_models.RecordSet"]] = None, **kwargs: Any) -> None: + """ + :keyword value: Information about the record sets in the response. + :paramtype value: list[~azure.mgmt.dns.v2018_03_01_preview.models.RecordSet] + """ + super().__init__(**kwargs) self.value = value self.next_link = None -class RecordSetUpdateParameters(msrest.serialization.Model): +class RecordSetUpdateParameters(_serialization.Model): """Parameters supplied to update a record set. - :param record_set: Specifies information about the record set being updated. - :type record_set: ~azure.mgmt.dns.v2018_03_01_preview.models.RecordSet + :ivar record_set: Specifies information about the record set being updated. + :vartype record_set: ~azure.mgmt.dns.v2018_03_01_preview.models.RecordSet """ _attribute_map = { - 'record_set': {'key': 'RecordSet', 'type': 'RecordSet'}, + "record_set": {"key": "RecordSet", "type": "RecordSet"}, } - def __init__( - self, - *, - record_set: Optional["RecordSet"] = None, - **kwargs - ): - super(RecordSetUpdateParameters, self).__init__(**kwargs) + def __init__(self, *, record_set: Optional["_models.RecordSet"] = None, **kwargs: Any) -> None: + """ + :keyword record_set: Specifies information about the record set being updated. + :paramtype record_set: ~azure.mgmt.dns.v2018_03_01_preview.models.RecordSet + """ + super().__init__(**kwargs) self.record_set = record_set -class Resource(msrest.serialization.Model): +class Resource(_serialization.Model): """Common fields that are returned in the response for all Azure Resource Manager resources. Variables are only populated by the server, and will be ignored when sending a request. @@ -388,55 +428,53 @@ class Resource(msrest.serialization.Model): """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, } - def __init__( - self, - **kwargs - ): - super(Resource, self).__init__(**kwargs) + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) self.id = None self.name = None self.type = None -class SoaRecord(msrest.serialization.Model): +class SoaRecord(_serialization.Model): """An SOA record. - :param host: The domain name of the authoritative name server for this SOA record. - :type host: str - :param email: The email contact for this SOA record. - :type email: str - :param serial_number: The serial number for this SOA record. - :type serial_number: long - :param refresh_time: The refresh value for this SOA record. - :type refresh_time: long - :param retry_time: The retry time for this SOA record. - :type retry_time: long - :param expire_time: The expire time for this SOA record. - :type expire_time: long - :param minimum_ttl: The minimum value for this SOA record. By convention this is used to + :ivar host: The domain name of the authoritative name server for this SOA record. + :vartype host: str + :ivar email: The email contact for this SOA record. + :vartype email: str + :ivar serial_number: The serial number for this SOA record. + :vartype serial_number: int + :ivar refresh_time: The refresh value for this SOA record. + :vartype refresh_time: int + :ivar retry_time: The retry time for this SOA record. + :vartype retry_time: int + :ivar expire_time: The expire time for this SOA record. + :vartype expire_time: int + :ivar minimum_ttl: The minimum value for this SOA record. By convention this is used to determine the negative caching duration. - :type minimum_ttl: long + :vartype minimum_ttl: int """ _attribute_map = { - 'host': {'key': 'host', 'type': 'str'}, - 'email': {'key': 'email', 'type': 'str'}, - 'serial_number': {'key': 'serialNumber', 'type': 'long'}, - 'refresh_time': {'key': 'refreshTime', 'type': 'long'}, - 'retry_time': {'key': 'retryTime', 'type': 'long'}, - 'expire_time': {'key': 'expireTime', 'type': 'long'}, - 'minimum_ttl': {'key': 'minimumTTL', 'type': 'long'}, + "host": {"key": "host", "type": "str"}, + "email": {"key": "email", "type": "str"}, + "serial_number": {"key": "serialNumber", "type": "int"}, + "refresh_time": {"key": "refreshTime", "type": "int"}, + "retry_time": {"key": "retryTime", "type": "int"}, + "expire_time": {"key": "expireTime", "type": "int"}, + "minimum_ttl": {"key": "minimumTTL", "type": "int"}, } def __init__( @@ -449,9 +487,26 @@ def __init__( retry_time: Optional[int] = None, expire_time: Optional[int] = None, minimum_ttl: Optional[int] = None, - **kwargs - ): - super(SoaRecord, self).__init__(**kwargs) + **kwargs: Any + ) -> None: + """ + :keyword host: The domain name of the authoritative name server for this SOA record. + :paramtype host: str + :keyword email: The email contact for this SOA record. + :paramtype email: str + :keyword serial_number: The serial number for this SOA record. + :paramtype serial_number: int + :keyword refresh_time: The refresh value for this SOA record. + :paramtype refresh_time: int + :keyword retry_time: The retry time for this SOA record. + :paramtype retry_time: int + :keyword expire_time: The expire time for this SOA record. + :paramtype expire_time: int + :keyword minimum_ttl: The minimum value for this SOA record. By convention this is used to + determine the negative caching duration. + :paramtype minimum_ttl: int + """ + super().__init__(**kwargs) self.host = host self.email = email self.serial_number = serial_number @@ -461,24 +516,24 @@ def __init__( self.minimum_ttl = minimum_ttl -class SrvRecord(msrest.serialization.Model): +class SrvRecord(_serialization.Model): """An SRV record. - :param priority: The priority value for this SRV record. - :type priority: int - :param weight: The weight value for this SRV record. - :type weight: int - :param port: The port value for this SRV record. - :type port: int - :param target: The target domain name for this SRV record. - :type target: str + :ivar priority: The priority value for this SRV record. + :vartype priority: int + :ivar weight: The weight value for this SRV record. + :vartype weight: int + :ivar port: The port value for this SRV record. + :vartype port: int + :ivar target: The target domain name for this SRV record. + :vartype target: str """ _attribute_map = { - 'priority': {'key': 'priority', 'type': 'int'}, - 'weight': {'key': 'weight', 'type': 'int'}, - 'port': {'key': 'port', 'type': 'int'}, - 'target': {'key': 'target', 'type': 'str'}, + "priority": {"key": "priority", "type": "int"}, + "weight": {"key": "weight", "type": "int"}, + "port": {"key": "port", "type": "int"}, + "target": {"key": "target", "type": "str"}, } def __init__( @@ -488,38 +543,48 @@ def __init__( weight: Optional[int] = None, port: Optional[int] = None, target: Optional[str] = None, - **kwargs - ): - super(SrvRecord, self).__init__(**kwargs) + **kwargs: Any + ) -> None: + """ + :keyword priority: The priority value for this SRV record. + :paramtype priority: int + :keyword weight: The weight value for this SRV record. + :paramtype weight: int + :keyword port: The port value for this SRV record. + :paramtype port: int + :keyword target: The target domain name for this SRV record. + :paramtype target: str + """ + super().__init__(**kwargs) self.priority = priority self.weight = weight self.port = port self.target = target -class SubResource(msrest.serialization.Model): +class SubResource(_serialization.Model): """A reference to a another resource. - :param id: Resource Id. - :type id: str + :ivar id: Resource Id. + :vartype id: str """ _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, + "id": {"key": "id", "type": "str"}, } - def __init__( - self, - *, - id: Optional[str] = None, - **kwargs - ): - super(SubResource, self).__init__(**kwargs) + def __init__(self, *, id: Optional[str] = None, **kwargs: Any) -> None: # pylint: disable=redefined-builtin + """ + :keyword id: Resource Id. + :paramtype id: str + """ + super().__init__(**kwargs) self.id = id class TrackedResource(Resource): - """The resource model definition for an Azure Resource Manager tracked top level resource which has 'tags' and a 'location'. + """The resource model definition for an Azure Resource Manager tracked top level resource which + has 'tags' and a 'location'. Variables are only populated by the server, and will be ignored when sending a request. @@ -533,61 +598,60 @@ class TrackedResource(Resource): :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts". :vartype type: str - :param tags: A set of tags. Resource tags. - :type tags: dict[str, str] - :param location: Required. The geo-location where the resource lives. - :type location: str + :ivar tags: Resource tags. + :vartype tags: dict[str, str] + :ivar location: The geo-location where the resource lives. Required. + :vartype location: str """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'location': {'required': True}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "location": {"required": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'tags': {'key': 'tags', 'type': '{str}'}, - 'location': {'key': 'location', 'type': 'str'}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "tags": {"key": "tags", "type": "{str}"}, + "location": {"key": "location", "type": "str"}, } - def __init__( - self, - *, - location: str, - tags: Optional[Dict[str, str]] = None, - **kwargs - ): - super(TrackedResource, self).__init__(**kwargs) + def __init__(self, *, location: str, tags: Optional[Dict[str, str]] = None, **kwargs: Any) -> None: + """ + :keyword tags: Resource tags. + :paramtype tags: dict[str, str] + :keyword location: The geo-location where the resource lives. Required. + :paramtype location: str + """ + super().__init__(**kwargs) self.tags = tags self.location = location -class TxtRecord(msrest.serialization.Model): +class TxtRecord(_serialization.Model): """A TXT record. - :param value: The text value of this TXT record. - :type value: list[str] + :ivar value: The text value of this TXT record. + :vartype value: list[str] """ _attribute_map = { - 'value': {'key': 'value', 'type': '[str]'}, + "value": {"key": "value", "type": "[str]"}, } - def __init__( - self, - *, - value: Optional[List[str]] = None, - **kwargs - ): - super(TxtRecord, self).__init__(**kwargs) + def __init__(self, *, value: Optional[List[str]] = None, **kwargs: Any) -> None: + """ + :keyword value: The text value of this TXT record. + :paramtype value: list[str] + """ + super().__init__(**kwargs) self.value = value -class Zone(TrackedResource): +class Zone(TrackedResource): # pylint: disable=too-many-instance-attributes """Describes a DNS zone. Variables are only populated by the server, and will be ignored when sending a request. @@ -602,62 +666,63 @@ class Zone(TrackedResource): :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts". :vartype type: str - :param tags: A set of tags. Resource tags. - :type tags: dict[str, str] - :param location: Required. The geo-location where the resource lives. - :type location: str - :param etag: The etag of the zone. - :type etag: str + :ivar tags: Resource tags. + :vartype tags: dict[str, str] + :ivar location: The geo-location where the resource lives. Required. + :vartype location: str + :ivar etag: The etag of the zone. + :vartype etag: str :ivar max_number_of_record_sets: The maximum number of record sets that can be created in this DNS zone. This is a read-only property and any attempt to set this value will be ignored. - :vartype max_number_of_record_sets: long + :vartype max_number_of_record_sets: int :ivar max_number_of_records_per_record_set: The maximum number of records per record set that can be created in this DNS zone. This is a read-only property and any attempt to set this value will be ignored. - :vartype max_number_of_records_per_record_set: long + :vartype max_number_of_records_per_record_set: int :ivar number_of_record_sets: The current number of record sets in this DNS zone. This is a read-only property and any attempt to set this value will be ignored. - :vartype number_of_record_sets: long + :vartype number_of_record_sets: int :ivar name_servers: The name servers for this DNS zone. This is a read-only property and any attempt to set this value will be ignored. :vartype name_servers: list[str] - :param zone_type: The type of this DNS zone (Public or Private). Possible values include: - "Public", "Private". Default value: "Public". - :type zone_type: str or ~azure.mgmt.dns.v2018_03_01_preview.models.ZoneType - :param registration_virtual_networks: A list of references to virtual networks that register + :ivar zone_type: The type of this DNS zone (Public or Private). Known values are: "Public" and + "Private". + :vartype zone_type: str or ~azure.mgmt.dns.v2018_03_01_preview.models.ZoneType + :ivar registration_virtual_networks: A list of references to virtual networks that register hostnames in this DNS zone. This is a only when ZoneType is Private. - :type registration_virtual_networks: + :vartype registration_virtual_networks: list[~azure.mgmt.dns.v2018_03_01_preview.models.SubResource] - :param resolution_virtual_networks: A list of references to virtual networks that resolve + :ivar resolution_virtual_networks: A list of references to virtual networks that resolve records in this DNS zone. This is a only when ZoneType is Private. - :type resolution_virtual_networks: list[~azure.mgmt.dns.v2018_03_01_preview.models.SubResource] + :vartype resolution_virtual_networks: + list[~azure.mgmt.dns.v2018_03_01_preview.models.SubResource] """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'location': {'required': True}, - 'max_number_of_record_sets': {'readonly': True}, - 'max_number_of_records_per_record_set': {'readonly': True}, - 'number_of_record_sets': {'readonly': True}, - 'name_servers': {'readonly': True}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "location": {"required": True}, + "max_number_of_record_sets": {"readonly": True}, + "max_number_of_records_per_record_set": {"readonly": True}, + "number_of_record_sets": {"readonly": True}, + "name_servers": {"readonly": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'tags': {'key': 'tags', 'type': '{str}'}, - 'location': {'key': 'location', 'type': 'str'}, - 'etag': {'key': 'etag', 'type': 'str'}, - 'max_number_of_record_sets': {'key': 'properties.maxNumberOfRecordSets', 'type': 'long'}, - 'max_number_of_records_per_record_set': {'key': 'properties.maxNumberOfRecordsPerRecordSet', 'type': 'long'}, - 'number_of_record_sets': {'key': 'properties.numberOfRecordSets', 'type': 'long'}, - 'name_servers': {'key': 'properties.nameServers', 'type': '[str]'}, - 'zone_type': {'key': 'properties.zoneType', 'type': 'str'}, - 'registration_virtual_networks': {'key': 'properties.registrationVirtualNetworks', 'type': '[SubResource]'}, - 'resolution_virtual_networks': {'key': 'properties.resolutionVirtualNetworks', 'type': '[SubResource]'}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "tags": {"key": "tags", "type": "{str}"}, + "location": {"key": "location", "type": "str"}, + "etag": {"key": "etag", "type": "str"}, + "max_number_of_record_sets": {"key": "properties.maxNumberOfRecordSets", "type": "int"}, + "max_number_of_records_per_record_set": {"key": "properties.maxNumberOfRecordsPerRecordSet", "type": "int"}, + "number_of_record_sets": {"key": "properties.numberOfRecordSets", "type": "int"}, + "name_servers": {"key": "properties.nameServers", "type": "[str]"}, + "zone_type": {"key": "properties.zoneType", "type": "str"}, + "registration_virtual_networks": {"key": "properties.registrationVirtualNetworks", "type": "[SubResource]"}, + "resolution_virtual_networks": {"key": "properties.resolutionVirtualNetworks", "type": "[SubResource]"}, } def __init__( @@ -666,12 +731,31 @@ def __init__( location: str, tags: Optional[Dict[str, str]] = None, etag: Optional[str] = None, - zone_type: Optional[Union[str, "ZoneType"]] = "Public", - registration_virtual_networks: Optional[List["SubResource"]] = None, - resolution_virtual_networks: Optional[List["SubResource"]] = None, - **kwargs - ): - super(Zone, self).__init__(tags=tags, location=location, **kwargs) + zone_type: Union[str, "_models.ZoneType"] = "Public", + registration_virtual_networks: Optional[List["_models.SubResource"]] = None, + resolution_virtual_networks: Optional[List["_models.SubResource"]] = None, + **kwargs: Any + ) -> None: + """ + :keyword tags: Resource tags. + :paramtype tags: dict[str, str] + :keyword location: The geo-location where the resource lives. Required. + :paramtype location: str + :keyword etag: The etag of the zone. + :paramtype etag: str + :keyword zone_type: The type of this DNS zone (Public or Private). Known values are: "Public" + and "Private". + :paramtype zone_type: str or ~azure.mgmt.dns.v2018_03_01_preview.models.ZoneType + :keyword registration_virtual_networks: A list of references to virtual networks that register + hostnames in this DNS zone. This is a only when ZoneType is Private. + :paramtype registration_virtual_networks: + list[~azure.mgmt.dns.v2018_03_01_preview.models.SubResource] + :keyword resolution_virtual_networks: A list of references to virtual networks that resolve + records in this DNS zone. This is a only when ZoneType is Private. + :paramtype resolution_virtual_networks: + list[~azure.mgmt.dns.v2018_03_01_preview.models.SubResource] + """ + super().__init__(tags=tags, location=location, **kwargs) self.etag = etag self.max_number_of_record_sets = None self.max_number_of_records_per_record_set = None @@ -682,53 +766,51 @@ def __init__( self.resolution_virtual_networks = resolution_virtual_networks -class ZoneListResult(msrest.serialization.Model): +class ZoneListResult(_serialization.Model): """The response to a Zone List or ListAll operation. Variables are only populated by the server, and will be ignored when sending a request. - :param value: Information about the DNS zones. - :type value: list[~azure.mgmt.dns.v2018_03_01_preview.models.Zone] + :ivar value: Information about the DNS zones. + :vartype value: list[~azure.mgmt.dns.v2018_03_01_preview.models.Zone] :ivar next_link: The continuation token for the next page of results. :vartype next_link: str """ _validation = { - 'next_link': {'readonly': True}, + "next_link": {"readonly": True}, } _attribute_map = { - 'value': {'key': 'value', 'type': '[Zone]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "value": {"key": "value", "type": "[Zone]"}, + "next_link": {"key": "nextLink", "type": "str"}, } - def __init__( - self, - *, - value: Optional[List["Zone"]] = None, - **kwargs - ): - super(ZoneListResult, self).__init__(**kwargs) + def __init__(self, *, value: Optional[List["_models.Zone"]] = None, **kwargs: Any) -> None: + """ + :keyword value: Information about the DNS zones. + :paramtype value: list[~azure.mgmt.dns.v2018_03_01_preview.models.Zone] + """ + super().__init__(**kwargs) self.value = value self.next_link = None -class ZoneUpdate(msrest.serialization.Model): +class ZoneUpdate(_serialization.Model): """Describes a request to update a DNS zone. - :param tags: A set of tags. Resource tags. - :type tags: dict[str, str] + :ivar tags: Resource tags. + :vartype tags: dict[str, str] """ _attribute_map = { - 'tags': {'key': 'tags', 'type': '{str}'}, + "tags": {"key": "tags", "type": "{str}"}, } - def __init__( - self, - *, - tags: Optional[Dict[str, str]] = None, - **kwargs - ): - super(ZoneUpdate, self).__init__(**kwargs) + def __init__(self, *, tags: Optional[Dict[str, str]] = None, **kwargs: Any) -> None: + """ + :keyword tags: Resource tags. + :paramtype tags: dict[str, str] + """ + super().__init__(**kwargs) self.tags = tags diff --git a/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_03_01_preview/models/_patch.py b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_03_01_preview/models/_patch.py new file mode 100644 index 000000000000..f7dd32510333 --- /dev/null +++ b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_03_01_preview/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/network/azure-mgmt-dns/azure/mgmt/dns/v2018_03_01_preview/operations/__init__.py b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_03_01_preview/operations/__init__.py index caab83d882c4..c12bcc6610ed 100644 --- a/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_03_01_preview/operations/__init__.py +++ b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_03_01_preview/operations/__init__.py @@ -9,7 +9,13 @@ from ._record_sets_operations import RecordSetsOperations from ._zones_operations import ZonesOperations +from ._patch import __all__ as _patch_all +from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import patch_sdk as _patch_sdk + __all__ = [ - 'RecordSetsOperations', - 'ZonesOperations', + "RecordSetsOperations", + "ZonesOperations", ] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_03_01_preview/operations/_patch.py b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_03_01_preview/operations/_patch.py new file mode 100644 index 000000000000..f7dd32510333 --- /dev/null +++ b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_03_01_preview/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/network/azure-mgmt-dns/azure/mgmt/dns/v2018_03_01_preview/operations/_record_sets_operations.py b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_03_01_preview/operations/_record_sets_operations.py index b23b481345cb..4dc617cae04f 100644 --- a/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_03_01_preview/operations/_record_sets_operations.py +++ b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_03_01_preview/operations/_record_sets_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,203 +6,763 @@ # 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 TYPE_CHECKING -import warnings - -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 HttpRequest, HttpResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from ..._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_update_request( + resource_group_name: str, + zone_name: str, + relative_record_set_name: str, + record_type: Union[str, _models.RecordType], + subscription_id: str, + *, + if_match: Optional[str] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2018-03-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2018-03-01-preview") + ) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}/{recordType}/{relativeRecordSetName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "zoneName": _SERIALIZER.url("zone_name", zone_name, "str"), + "relativeRecordSetName": _SERIALIZER.url( + "relative_record_set_name", relative_record_set_name, "str", skip_quote=True + ), + "recordType": _SERIALIZER.url("record_type", record_type, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if if_match is not None: + _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_create_or_update_request( + resource_group_name: str, + zone_name: str, + relative_record_set_name: str, + record_type: Union[str, _models.RecordType], + subscription_id: str, + *, + if_match: Optional[str] = None, + if_none_match: Optional[str] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2018-03-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2018-03-01-preview") + ) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}/{recordType}/{relativeRecordSetName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "zoneName": _SERIALIZER.url("zone_name", zone_name, "str"), + "relativeRecordSetName": _SERIALIZER.url( + "relative_record_set_name", relative_record_set_name, "str", skip_quote=True + ), + "recordType": _SERIALIZER.url("record_type", record_type, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if if_match is not None: + _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") + if if_none_match is not None: + _headers["If-None-Match"] = _SERIALIZER.header("if_none_match", if_none_match, "str") + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_delete_request( + resource_group_name: str, + zone_name: str, + relative_record_set_name: str, + record_type: Union[str, _models.RecordType], + subscription_id: str, + *, + if_match: Optional[str] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2018-03-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2018-03-01-preview") + ) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}/{recordType}/{relativeRecordSetName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "zoneName": _SERIALIZER.url("zone_name", zone_name, "str"), + "relativeRecordSetName": _SERIALIZER.url( + "relative_record_set_name", relative_record_set_name, "str", skip_quote=True + ), + "recordType": _SERIALIZER.url("record_type", record_type, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if if_match is not None: + _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") + _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, + zone_name: str, + relative_record_set_name: str, + record_type: Union[str, _models.RecordType], + subscription_id: str, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2018-03-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2018-03-01-preview") + ) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}/{recordType}/{relativeRecordSetName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "zoneName": _SERIALIZER.url("zone_name", zone_name, "str"), + "relativeRecordSetName": _SERIALIZER.url( + "relative_record_set_name", relative_record_set_name, "str", skip_quote=True + ), + "recordType": _SERIALIZER.url("record_type", record_type, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_by_type_request( + resource_group_name: str, + zone_name: str, + record_type: Union[str, _models.RecordType], + subscription_id: str, + *, + top: Optional[int] = None, + recordsetnamesuffix: Optional[str] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2018-03-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2018-03-01-preview") + ) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}/{recordType}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "zoneName": _SERIALIZER.url("zone_name", zone_name, "str"), + "recordType": _SERIALIZER.url("record_type", record_type, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + if top is not None: + _params["$top"] = _SERIALIZER.query("top", top, "int") + if recordsetnamesuffix is not None: + _params["$recordsetnamesuffix"] = _SERIALIZER.query("recordsetnamesuffix", recordsetnamesuffix, "str") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_by_dns_zone_request( + resource_group_name: str, + zone_name: str, + subscription_id: str, + *, + top: Optional[int] = None, + recordsetnamesuffix: Optional[str] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2018-03-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2018-03-01-preview") + ) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}/recordsets", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "zoneName": _SERIALIZER.url("zone_name", zone_name, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + if top is not None: + _params["$top"] = _SERIALIZER.query("top", top, "int") + if recordsetnamesuffix is not None: + _params["$recordsetnamesuffix"] = _SERIALIZER.query("recordsetnamesuffix", recordsetnamesuffix, "str") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_all_by_dns_zone_request( + resource_group_name: str, + zone_name: str, + subscription_id: str, + *, + top: Optional[int] = None, + record_set_name_suffix: Optional[str] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2018-03-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2018-03-01-preview") + ) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}/all", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "zoneName": _SERIALIZER.url("zone_name", zone_name, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + if top is not None: + _params["$top"] = _SERIALIZER.query("top", top, "int") + if record_set_name_suffix is not None: + _params["$recordsetnamesuffix"] = _SERIALIZER.query("record_set_name_suffix", record_set_name_suffix, "str") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class RecordSetsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar, Union + Instead, you should access the following operations through + :class:`~azure.mgmt.dns.v2018_03_01_preview.DnsManagementClient`'s + :attr:`record_sets` attribute. + """ - T = TypeVar('T') - ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + models = _models -class RecordSetsOperations(object): - """RecordSetsOperations operations. + 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") - 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. + @overload + def update( + self, + resource_group_name: str, + zone_name: str, + relative_record_set_name: str, + record_type: Union[str, _models.RecordType], + parameters: _models.RecordSet, + if_match: Optional[str] = None, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RecordSet: + """Updates a record set within a DNS zone. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.dns.v2018_03_01_preview.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. - """ + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param zone_name: The name of the DNS zone (without a terminating dot). Required. + :type zone_name: str + :param relative_record_set_name: The name of the record set, relative to the name of the zone. + Required. + :type relative_record_set_name: str + :param record_type: The type of DNS record in this record set. Known values are: "A", "AAAA", + "CAA", "CNAME", "MX", "NS", "PTR", "SOA", "SRV", and "TXT". Required. + :type record_type: str or ~azure.mgmt.dns.v2018_03_01_preview.models.RecordType + :param parameters: Parameters supplied to the Update operation. Required. + :type parameters: ~azure.mgmt.dns.v2018_03_01_preview.models.RecordSet + :param if_match: The etag of the record set. Omit this value to always overwrite the current + record set. Specify the last-seen etag value to prevent accidentally overwriting concurrent + changes. 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: RecordSet or the result of cls(response) + :rtype: ~azure.mgmt.dns.v2018_03_01_preview.models.RecordSet + :raises ~azure.core.exceptions.HttpResponseError: + """ - models = _models + @overload + def update( + self, + resource_group_name: str, + zone_name: str, + relative_record_set_name: str, + record_type: Union[str, _models.RecordType], + parameters: IO, + if_match: Optional[str] = None, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RecordSet: + """Updates a record set within a DNS zone. - def __init__(self, client, config, serializer, deserializer): - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param zone_name: The name of the DNS zone (without a terminating dot). Required. + :type zone_name: str + :param relative_record_set_name: The name of the record set, relative to the name of the zone. + Required. + :type relative_record_set_name: str + :param record_type: The type of DNS record in this record set. Known values are: "A", "AAAA", + "CAA", "CNAME", "MX", "NS", "PTR", "SOA", "SRV", and "TXT". Required. + :type record_type: str or ~azure.mgmt.dns.v2018_03_01_preview.models.RecordType + :param parameters: Parameters supplied to the Update operation. Required. + :type parameters: IO + :param if_match: The etag of the record set. Omit this value to always overwrite the current + record set. Specify the last-seen etag value to prevent accidentally overwriting concurrent + changes. 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: RecordSet or the result of cls(response) + :rtype: ~azure.mgmt.dns.v2018_03_01_preview.models.RecordSet + :raises ~azure.core.exceptions.HttpResponseError: + """ + @distributed_trace def update( self, - resource_group_name, # type: str - zone_name, # type: str - relative_record_set_name, # type: str - record_type, # type: Union[str, "_models.RecordType"] - parameters, # type: "_models.RecordSet" - if_match=None, # type: Optional[str] - **kwargs # type: Any - ): - # type: (...) -> "_models.RecordSet" + resource_group_name: str, + zone_name: str, + relative_record_set_name: str, + record_type: Union[str, _models.RecordType], + parameters: Union[_models.RecordSet, IO], + if_match: Optional[str] = None, + **kwargs: Any + ) -> _models.RecordSet: """Updates a record set within a DNS zone. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param zone_name: The name of the DNS zone (without a terminating dot). + :param zone_name: The name of the DNS zone (without a terminating dot). Required. :type zone_name: str :param relative_record_set_name: The name of the record set, relative to the name of the zone. + Required. :type relative_record_set_name: str - :param record_type: The type of DNS record in this record set. + :param record_type: The type of DNS record in this record set. Known values are: "A", "AAAA", + "CAA", "CNAME", "MX", "NS", "PTR", "SOA", "SRV", and "TXT". Required. :type record_type: str or ~azure.mgmt.dns.v2018_03_01_preview.models.RecordType - :param parameters: Parameters supplied to the Update operation. - :type parameters: ~azure.mgmt.dns.v2018_03_01_preview.models.RecordSet + :param parameters: Parameters supplied to the Update operation. Is either a RecordSet type or a + IO type. Required. + :type parameters: ~azure.mgmt.dns.v2018_03_01_preview.models.RecordSet or IO :param if_match: The etag of the record set. Omit this value to always overwrite the current record set. Specify the last-seen etag value to prevent accidentally overwriting concurrent - changes. + changes. 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: RecordSet, or the result of cls(response) + :return: RecordSet or the result of cls(response) :rtype: ~azure.mgmt.dns.v2018_03_01_preview.models.RecordSet - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RecordSet"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-03-01-preview" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.update.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), - 'zoneName': self._serialize.url("zone_name", zone_name, 'str'), - 'relativeRecordSetName': self._serialize.url("relative_record_set_name", relative_record_set_name, 'str', skip_quote=True), - 'recordType': self._serialize.url("record_type", record_type, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - if if_match is not None: - header_parameters['If-Match'] = self._serialize.header("if_match", if_match, 'str') - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(parameters, 'RecordSet') - body_content_kwargs['content'] = body_content - request = self._client.patch(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + 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: Literal["2018-03-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2018-03-01-preview") + ) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.RecordSet] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "RecordSet") + + request = build_update_request( + resource_group_name=resource_group_name, + zone_name=zone_name, + relative_record_set_name=relative_record_set_name, + record_type=record_type, + subscription_id=self._config.subscription_id, + if_match=if_match, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.update.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = 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('RecordSet', pipeline_response) + deserialized = self._deserialize("RecordSet", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}/{recordType}/{relativeRecordSetName}'} # type: ignore + update.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}/{recordType}/{relativeRecordSetName}" + } + + @overload def create_or_update( self, - resource_group_name, # type: str - zone_name, # type: str - relative_record_set_name, # type: str - record_type, # type: Union[str, "_models.RecordType"] - parameters, # type: "_models.RecordSet" - if_match=None, # type: Optional[str] - if_none_match=None, # type: Optional[str] - **kwargs # type: Any - ): - # type: (...) -> "_models.RecordSet" + resource_group_name: str, + zone_name: str, + relative_record_set_name: str, + record_type: Union[str, _models.RecordType], + parameters: _models.RecordSet, + if_match: Optional[str] = None, + if_none_match: Optional[str] = None, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RecordSet: """Creates or updates a record set within a DNS zone. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param zone_name: The name of the DNS zone (without a terminating dot). + :param zone_name: The name of the DNS zone (without a terminating dot). Required. :type zone_name: str :param relative_record_set_name: The name of the record set, relative to the name of the zone. + Required. :type relative_record_set_name: str :param record_type: The type of DNS record in this record set. Record sets of type SOA can be - updated but not created (they are created when the DNS zone is created). + updated but not created (they are created when the DNS zone is created). Known values are: "A", + "AAAA", "CAA", "CNAME", "MX", "NS", "PTR", "SOA", "SRV", and "TXT". Required. :type record_type: str or ~azure.mgmt.dns.v2018_03_01_preview.models.RecordType - :param parameters: Parameters supplied to the CreateOrUpdate operation. + :param parameters: Parameters supplied to the CreateOrUpdate operation. Required. :type parameters: ~azure.mgmt.dns.v2018_03_01_preview.models.RecordSet :param if_match: The etag of the record set. Omit this value to always overwrite the current record set. Specify the last-seen etag value to prevent accidentally overwriting any concurrent - changes. + changes. Default value is None. + :type if_match: str + :param if_none_match: Set to '*' to allow a new record set to be created, but to prevent + updating an existing record set. 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: RecordSet or the result of cls(response) + :rtype: ~azure.mgmt.dns.v2018_03_01_preview.models.RecordSet + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_or_update( + self, + resource_group_name: str, + zone_name: str, + relative_record_set_name: str, + record_type: Union[str, _models.RecordType], + parameters: IO, + if_match: Optional[str] = None, + if_none_match: Optional[str] = None, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RecordSet: + """Creates or updates a record set within a DNS zone. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param zone_name: The name of the DNS zone (without a terminating dot). Required. + :type zone_name: str + :param relative_record_set_name: The name of the record set, relative to the name of the zone. + Required. + :type relative_record_set_name: str + :param record_type: The type of DNS record in this record set. Record sets of type SOA can be + updated but not created (they are created when the DNS zone is created). Known values are: "A", + "AAAA", "CAA", "CNAME", "MX", "NS", "PTR", "SOA", "SRV", and "TXT". Required. + :type record_type: str or ~azure.mgmt.dns.v2018_03_01_preview.models.RecordType + :param parameters: Parameters supplied to the CreateOrUpdate operation. Required. + :type parameters: IO + :param if_match: The etag of the record set. Omit this value to always overwrite the current + record set. Specify the last-seen etag value to prevent accidentally overwriting any concurrent + changes. Default value is None. :type if_match: str :param if_none_match: Set to '*' to allow a new record set to be created, but to prevent - updating an existing record set. Other values will be ignored. + updating an existing record set. 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: RecordSet, or the result of cls(response) + :return: RecordSet or the result of cls(response) :rtype: ~azure.mgmt.dns.v2018_03_01_preview.models.RecordSet - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create_or_update( + self, + resource_group_name: str, + zone_name: str, + relative_record_set_name: str, + record_type: Union[str, _models.RecordType], + parameters: Union[_models.RecordSet, IO], + if_match: Optional[str] = None, + if_none_match: Optional[str] = None, + **kwargs: Any + ) -> _models.RecordSet: + """Creates or updates a record set within a DNS zone. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param zone_name: The name of the DNS zone (without a terminating dot). Required. + :type zone_name: str + :param relative_record_set_name: The name of the record set, relative to the name of the zone. + Required. + :type relative_record_set_name: str + :param record_type: The type of DNS record in this record set. Record sets of type SOA can be + updated but not created (they are created when the DNS zone is created). Known values are: "A", + "AAAA", "CAA", "CNAME", "MX", "NS", "PTR", "SOA", "SRV", and "TXT". Required. + :type record_type: str or ~azure.mgmt.dns.v2018_03_01_preview.models.RecordType + :param parameters: Parameters supplied to the CreateOrUpdate operation. Is either a RecordSet + type or a IO type. Required. + :type parameters: ~azure.mgmt.dns.v2018_03_01_preview.models.RecordSet or IO + :param if_match: The etag of the record set. Omit this value to always overwrite the current + record set. Specify the last-seen etag value to prevent accidentally overwriting any concurrent + changes. Default value is None. + :type if_match: str + :param if_none_match: Set to '*' to allow a new record set to be created, but to prevent + updating an existing record set. 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: RecordSet or the result of cls(response) + :rtype: ~azure.mgmt.dns.v2018_03_01_preview.models.RecordSet + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RecordSet"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-03-01-preview" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.create_or_update.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), - 'zoneName': self._serialize.url("zone_name", zone_name, 'str'), - 'relativeRecordSetName': self._serialize.url("relative_record_set_name", relative_record_set_name, 'str', skip_quote=True), - 'recordType': self._serialize.url("record_type", record_type, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - if if_match is not None: - header_parameters['If-Match'] = self._serialize.header("if_match", if_match, 'str') - if if_none_match is not None: - header_parameters['If-None-Match'] = self._serialize.header("if_none_match", if_none_match, 'str') - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(parameters, 'RecordSet') - body_content_kwargs['content'] = body_content - request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + 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: Literal["2018-03-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2018-03-01-preview") + ) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.RecordSet] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "RecordSet") + + request = build_create_or_update_request( + resource_group_name=resource_group_name, + zone_name=zone_name, + relative_record_set_name=relative_record_set_name, + record_type=record_type, + subscription_id=self._config.subscription_id, + if_match=if_match, + if_none_match=if_none_match, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create_or_update.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response if response.status_code not in [200, 201]: @@ -209,78 +770,88 @@ def create_or_update( raise HttpResponseError(response=response, error_format=ARMErrorFormat) if response.status_code == 200: - deserialized = self._deserialize('RecordSet', pipeline_response) + deserialized = self._deserialize("RecordSet", pipeline_response) if response.status_code == 201: - deserialized = self._deserialize('RecordSet', pipeline_response) + deserialized = self._deserialize("RecordSet", pipeline_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}/{recordType}/{relativeRecordSetName}'} # type: ignore + return deserialized # type: ignore + + create_or_update.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}/{recordType}/{relativeRecordSetName}" + } - def delete( + @distributed_trace + def delete( # pylint: disable=inconsistent-return-statements self, - resource_group_name, # type: str - zone_name, # type: str - relative_record_set_name, # type: str - record_type, # type: Union[str, "_models.RecordType"] - if_match=None, # type: Optional[str] - **kwargs # type: Any - ): - # type: (...) -> None + resource_group_name: str, + zone_name: str, + relative_record_set_name: str, + record_type: Union[str, _models.RecordType], + if_match: Optional[str] = None, + **kwargs: Any + ) -> None: """Deletes a record set from a DNS zone. This operation cannot be undone. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param zone_name: The name of the DNS zone (without a terminating dot). + :param zone_name: The name of the DNS zone (without a terminating dot). Required. :type zone_name: str :param relative_record_set_name: The name of the record set, relative to the name of the zone. + Required. :type relative_record_set_name: str :param record_type: The type of DNS record in this record set. Record sets of type SOA cannot - be deleted (they are deleted when the DNS zone is deleted). + be deleted (they are deleted when the DNS zone is deleted). Known values are: "A", "AAAA", + "CAA", "CNAME", "MX", "NS", "PTR", "SOA", "SRV", and "TXT". Required. :type record_type: str or ~azure.mgmt.dns.v2018_03_01_preview.models.RecordType :param if_match: The etag of the record set. Omit this value to always delete the current record set. Specify the last-seen etag value to prevent accidentally deleting any concurrent - changes. + changes. Default value is None. :type if_match: 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', {})) - api_version = "2018-03-01-preview" - accept = "application/json" - - # Construct URL - url = self.delete.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), - 'zoneName': self._serialize.url("zone_name", zone_name, 'str'), - 'relativeRecordSetName': self._serialize.url("relative_record_set_name", relative_record_set_name, 'str', skip_quote=True), - 'recordType': self._serialize.url("record_type", record_type, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), - } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + api_version: Literal["2018-03-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2018-03-01-preview") + ) + cls: ClsType[None] = kwargs.pop("cls", None) + + request = build_delete_request( + resource_group_name=resource_group_name, + zone_name=zone_name, + relative_record_set_name=relative_record_set_name, + record_type=record_type, + subscription_id=self._config.subscription_id, + if_match=if_match, + api_version=api_version, + template_url=self.delete.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) - # Construct headers - header_parameters = {} # type: Dict[str, Any] - if if_match is not None: - header_parameters['If-Match'] = self._serialize.header("if_match", if_match, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.delete(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 204]: @@ -290,154 +861,185 @@ def delete( if cls: return cls(pipeline_response, None, {}) - delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}/{recordType}/{relativeRecordSetName}'} # type: ignore + delete.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}/{recordType}/{relativeRecordSetName}" + } + @distributed_trace def get( self, - resource_group_name, # type: str - zone_name, # type: str - relative_record_set_name, # type: str - record_type, # type: Union[str, "_models.RecordType"] - **kwargs # type: Any - ): - # type: (...) -> "_models.RecordSet" + resource_group_name: str, + zone_name: str, + relative_record_set_name: str, + record_type: Union[str, _models.RecordType], + **kwargs: Any + ) -> _models.RecordSet: """Gets a record set. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param zone_name: The name of the DNS zone (without a terminating dot). + :param zone_name: The name of the DNS zone (without a terminating dot). Required. :type zone_name: str :param relative_record_set_name: The name of the record set, relative to the name of the zone. + Required. :type relative_record_set_name: str - :param record_type: The type of DNS record in this record set. + :param record_type: The type of DNS record in this record set. Known values are: "A", "AAAA", + "CAA", "CNAME", "MX", "NS", "PTR", "SOA", "SRV", and "TXT". Required. :type record_type: str or ~azure.mgmt.dns.v2018_03_01_preview.models.RecordType :keyword callable cls: A custom type or function that will be passed the direct response - :return: RecordSet, or the result of cls(response) + :return: RecordSet or the result of cls(response) :rtype: ~azure.mgmt.dns.v2018_03_01_preview.models.RecordSet - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RecordSet"] 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 = "2018-03-01-preview" - accept = "application/json" - - # Construct URL - url = self.get.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), - 'zoneName': self._serialize.url("zone_name", zone_name, 'str'), - 'relativeRecordSetName': self._serialize.url("relative_record_set_name", relative_record_set_name, 'str', skip_quote=True), - 'recordType': self._serialize.url("record_type", record_type, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), - } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + api_version: Literal["2018-03-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2018-03-01-preview") + ) + cls: ClsType[_models.RecordSet] = kwargs.pop("cls", None) + + request = build_get_request( + resource_group_name=resource_group_name, + zone_name=zone_name, + relative_record_set_name=relative_record_set_name, + record_type=record_type, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('RecordSet', pipeline_response) + deserialized = self._deserialize("RecordSet", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}/{recordType}/{relativeRecordSetName}'} # type: ignore + get.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}/{recordType}/{relativeRecordSetName}" + } + + @distributed_trace def list_by_type( self, - resource_group_name, # type: str - zone_name, # type: str - record_type, # type: Union[str, "_models.RecordType"] - top=None, # type: Optional[int] - recordsetnamesuffix=None, # type: Optional[str] - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.RecordSetListResult"] + resource_group_name: str, + zone_name: str, + record_type: Union[str, _models.RecordType], + top: Optional[int] = None, + recordsetnamesuffix: Optional[str] = None, + **kwargs: Any + ) -> Iterable["_models.RecordSet"]: """Lists the record sets of a specified type in a DNS zone. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param zone_name: The name of the DNS zone (without a terminating dot). + :param zone_name: The name of the DNS zone (without a terminating dot). Required. :type zone_name: str - :param record_type: The type of record sets to enumerate. + :param record_type: The type of record sets to enumerate. Known values are: "A", "AAAA", "CAA", + "CNAME", "MX", "NS", "PTR", "SOA", "SRV", and "TXT". Required. :type record_type: str or ~azure.mgmt.dns.v2018_03_01_preview.models.RecordType :param top: The maximum number of record sets to return. If not specified, returns up to 100 - record sets. + record sets. Default value is None. :type top: int :param recordsetnamesuffix: The suffix label of the record set name that has to be used to filter the record set enumerations. If this parameter is specified, Enumeration will return - only records that end with .:code:``. + only records that end with .:code:``. Default value is None. :type recordsetnamesuffix: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either RecordSetListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.dns.v2018_03_01_preview.models.RecordSetListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either RecordSet or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.dns.v2018_03_01_preview.models.RecordSet] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RecordSetListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2018-03-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2018-03-01-preview") + ) + cls: ClsType[_models.RecordSetListResult] = kwargs.pop("cls", None) + 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 = "2018-03-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_by_type.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), - 'zoneName': self._serialize.url("zone_name", zone_name, 'str'), - 'recordType': self._serialize.url("record_type", record_type, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - if top is not None: - query_parameters['$top'] = self._serialize.query("top", top, 'int') - if recordsetnamesuffix is not None: - query_parameters['$recordsetnamesuffix'] = self._serialize.query("recordsetnamesuffix", recordsetnamesuffix, 'str') - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_by_type_request( + resource_group_name=resource_group_name, + zone_name=zone_name, + record_type=record_type, + subscription_id=self._config.subscription_id, + top=top, + recordsetnamesuffix=recordsetnamesuffix, + api_version=api_version, + template_url=self.list_by_type.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('RecordSetListResult', pipeline_response) + deserialized = self._deserialize("RecordSetListResult", pipeline_response) list_of_elem = deserialized.value if cls: - list_of_elem = cls(list_of_elem) + list_of_elem = cls(list_of_elem) # type: ignore return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: @@ -446,86 +1048,104 @@ def get_next(next_link=None): return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list_by_type.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}/{recordType}'} # type: ignore + return ItemPaged(get_next, extract_data) + + list_by_type.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}/{recordType}" + } + @distributed_trace def list_by_dns_zone( self, - resource_group_name, # type: str - zone_name, # type: str - top=None, # type: Optional[int] - recordsetnamesuffix=None, # type: Optional[str] - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.RecordSetListResult"] + resource_group_name: str, + zone_name: str, + top: Optional[int] = None, + recordsetnamesuffix: Optional[str] = None, + **kwargs: Any + ) -> Iterable["_models.RecordSet"]: """Lists all record sets in a DNS zone. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param zone_name: The name of the DNS zone (without a terminating dot). + :param zone_name: The name of the DNS zone (without a terminating dot). Required. :type zone_name: str :param top: The maximum number of record sets to return. If not specified, returns up to 100 - record sets. + record sets. Default value is None. :type top: int :param recordsetnamesuffix: The suffix label of the record set name that has to be used to filter the record set enumerations. If this parameter is specified, Enumeration will return - only records that end with .:code:``. + only records that end with .:code:``. Default value is None. :type recordsetnamesuffix: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either RecordSetListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.dns.v2018_03_01_preview.models.RecordSetListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either RecordSet or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.dns.v2018_03_01_preview.models.RecordSet] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RecordSetListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2018-03-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2018-03-01-preview") + ) + cls: ClsType[_models.RecordSetListResult] = kwargs.pop("cls", None) + 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 = "2018-03-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_by_dns_zone.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), - 'zoneName': self._serialize.url("zone_name", zone_name, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - if top is not None: - query_parameters['$top'] = self._serialize.query("top", top, 'int') - if recordsetnamesuffix is not None: - query_parameters['$recordsetnamesuffix'] = self._serialize.query("recordsetnamesuffix", recordsetnamesuffix, 'str') - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_by_dns_zone_request( + resource_group_name=resource_group_name, + zone_name=zone_name, + subscription_id=self._config.subscription_id, + top=top, + recordsetnamesuffix=recordsetnamesuffix, + api_version=api_version, + template_url=self.list_by_dns_zone.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('RecordSetListResult', pipeline_response) + deserialized = self._deserialize("RecordSetListResult", pipeline_response) list_of_elem = deserialized.value if cls: - list_of_elem = cls(list_of_elem) + list_of_elem = cls(list_of_elem) # type: ignore return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: @@ -534,86 +1154,104 @@ def get_next(next_link=None): return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list_by_dns_zone.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}/recordsets'} # type: ignore + return ItemPaged(get_next, extract_data) + + list_by_dns_zone.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}/recordsets" + } + @distributed_trace def list_all_by_dns_zone( self, - resource_group_name, # type: str - zone_name, # type: str - top=None, # type: Optional[int] - record_set_name_suffix=None, # type: Optional[str] - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.RecordSetListResult"] + resource_group_name: str, + zone_name: str, + top: Optional[int] = None, + record_set_name_suffix: Optional[str] = None, + **kwargs: Any + ) -> Iterable["_models.RecordSet"]: """Lists all record sets in a DNS zone. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param zone_name: The name of the DNS zone (without a terminating dot). + :param zone_name: The name of the DNS zone (without a terminating dot). Required. :type zone_name: str :param top: The maximum number of record sets to return. If not specified, returns up to 100 - record sets. + record sets. Default value is None. :type top: int :param record_set_name_suffix: The suffix label of the record set name that has to be used to filter the record set enumerations. If this parameter is specified, Enumeration will return - only records that end with .:code:``. + only records that end with .:code:``. Default value is None. :type record_set_name_suffix: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either RecordSetListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.dns.v2018_03_01_preview.models.RecordSetListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either RecordSet or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.dns.v2018_03_01_preview.models.RecordSet] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RecordSetListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2018-03-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2018-03-01-preview") + ) + cls: ClsType[_models.RecordSetListResult] = kwargs.pop("cls", None) + 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 = "2018-03-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_all_by_dns_zone.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), - 'zoneName': self._serialize.url("zone_name", zone_name, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - if top is not None: - query_parameters['$top'] = self._serialize.query("top", top, 'int') - if record_set_name_suffix is not None: - query_parameters['$recordsetnamesuffix'] = self._serialize.query("record_set_name_suffix", record_set_name_suffix, 'str') - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_all_by_dns_zone_request( + resource_group_name=resource_group_name, + zone_name=zone_name, + subscription_id=self._config.subscription_id, + top=top, + record_set_name_suffix=record_set_name_suffix, + api_version=api_version, + template_url=self.list_all_by_dns_zone.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('RecordSetListResult', pipeline_response) + deserialized = self._deserialize("RecordSetListResult", pipeline_response) list_of_elem = deserialized.value if cls: - list_of_elem = cls(list_of_elem) + list_of_elem = cls(list_of_elem) # type: ignore return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: @@ -622,7 +1260,8 @@ def get_next(next_link=None): return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list_all_by_dns_zone.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}/all'} # type: ignore + return ItemPaged(get_next, extract_data) + + list_all_by_dns_zone.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}/all" + } diff --git a/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_03_01_preview/operations/_zones_operations.py b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_03_01_preview/operations/_zones_operations.py index 0ff736df2b55..7faf06a9991d 100644 --- a/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_03_01_preview/operations/_zones_operations.py +++ b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_03_01_preview/operations/_zones_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,114 +6,439 @@ # 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 TYPE_CHECKING -import warnings - -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 HttpRequest, HttpResponse +from azure.core.pipeline.transport import HttpResponse from azure.core.polling import LROPoller, NoPolling, PollingMethod +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.arm_polling import ARMPolling from .. import models as _models +from ..._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_create_or_update_request( + resource_group_name: str, + zone_name: str, + subscription_id: str, + *, + if_match: Optional[str] = None, + if_none_match: Optional[str] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2018-03-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2018-03-01-preview") + ) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "zoneName": _SERIALIZER.url("zone_name", zone_name, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if if_match is not None: + _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") + if if_none_match is not None: + _headers["If-None-Match"] = _SERIALIZER.header("if_none_match", if_none_match, "str") + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_delete_request( + resource_group_name: str, zone_name: str, subscription_id: str, *, if_match: Optional[str] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2018-03-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2018-03-01-preview") + ) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "zoneName": _SERIALIZER.url("zone_name", zone_name, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if if_match is not None: + _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") + _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, zone_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: Literal["2018-03-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2018-03-01-preview") + ) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "zoneName": _SERIALIZER.url("zone_name", zone_name, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_update_request( + resource_group_name: str, zone_name: str, subscription_id: str, *, if_match: Optional[str] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2018-03-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2018-03-01-preview") + ) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "zoneName": _SERIALIZER.url("zone_name", zone_name, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if if_match is not None: + _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_by_resource_group_request( + resource_group_name: str, subscription_id: str, *, top: Optional[int] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2018-03-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2018-03-01-preview") + ) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + } -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar, Union + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + if top is not None: + _params["$top"] = _SERIALIZER.query("top", top, "int") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_request(subscription_id: str, *, top: Optional[int] = None, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2018-03-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2018-03-01-preview") + ) + accept = _headers.pop("Accept", "application/json") - T = TypeVar('T') - ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + # Construct URL + _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Network/dnszones") + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + } -class ZonesOperations(object): - """ZonesOperations operations. + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore - 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. + # Construct parameters + if top is not None: + _params["$top"] = _SERIALIZER.query("top", top, "int") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class ZonesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.dns.v2018_03_01_preview.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.dns.v2018_03_01_preview.DnsManagementClient`'s + :attr:`zones` 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") + @overload def create_or_update( self, - resource_group_name, # type: str - zone_name, # type: str - parameters, # type: "_models.Zone" - if_match=None, # type: Optional[str] - if_none_match=None, # type: Optional[str] - **kwargs # type: Any - ): - # type: (...) -> "_models.Zone" + resource_group_name: str, + zone_name: str, + parameters: _models.Zone, + if_match: Optional[str] = None, + if_none_match: Optional[str] = None, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Zone: """Creates or updates a DNS zone. Does not modify DNS records within the zone. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param zone_name: The name of the DNS zone (without a terminating dot). + :param zone_name: The name of the DNS zone (without a terminating dot). Required. :type zone_name: str - :param parameters: Parameters supplied to the CreateOrUpdate operation. + :param parameters: Parameters supplied to the CreateOrUpdate operation. Required. :type parameters: ~azure.mgmt.dns.v2018_03_01_preview.models.Zone :param if_match: The etag of the DNS zone. Omit this value to always overwrite the current zone. Specify the last-seen etag value to prevent accidentally overwriting any concurrent - changes. + changes. Default value is None. + :type if_match: str + :param if_none_match: Set to '*' to allow a new DNS zone to be created, but to prevent updating + an existing zone. 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: Zone or the result of cls(response) + :rtype: ~azure.mgmt.dns.v2018_03_01_preview.models.Zone + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_or_update( + self, + resource_group_name: str, + zone_name: str, + parameters: IO, + if_match: Optional[str] = None, + if_none_match: Optional[str] = None, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Zone: + """Creates or updates a DNS zone. Does not modify DNS records within the zone. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param zone_name: The name of the DNS zone (without a terminating dot). Required. + :type zone_name: str + :param parameters: Parameters supplied to the CreateOrUpdate operation. Required. + :type parameters: IO + :param if_match: The etag of the DNS zone. Omit this value to always overwrite the current + zone. Specify the last-seen etag value to prevent accidentally overwriting any concurrent + changes. Default value is None. + :type if_match: str + :param if_none_match: Set to '*' to allow a new DNS zone to be created, but to prevent updating + an existing zone. 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: Zone or the result of cls(response) + :rtype: ~azure.mgmt.dns.v2018_03_01_preview.models.Zone + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create_or_update( + self, + resource_group_name: str, + zone_name: str, + parameters: Union[_models.Zone, IO], + if_match: Optional[str] = None, + if_none_match: Optional[str] = None, + **kwargs: Any + ) -> _models.Zone: + """Creates or updates a DNS zone. Does not modify DNS records within the zone. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param zone_name: The name of the DNS zone (without a terminating dot). Required. + :type zone_name: str + :param parameters: Parameters supplied to the CreateOrUpdate operation. Is either a Zone type + or a IO type. Required. + :type parameters: ~azure.mgmt.dns.v2018_03_01_preview.models.Zone or IO + :param if_match: The etag of the DNS zone. Omit this value to always overwrite the current + zone. Specify the last-seen etag value to prevent accidentally overwriting any concurrent + changes. Default value is None. :type if_match: str :param if_none_match: Set to '*' to allow a new DNS zone to be created, but to prevent updating - an existing zone. Other values will be ignored. + an existing zone. 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: Zone, or the result of cls(response) + :return: Zone or the result of cls(response) :rtype: ~azure.mgmt.dns.v2018_03_01_preview.models.Zone - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Zone"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-03-01-preview" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.create_or_update.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), - 'zoneName': self._serialize.url("zone_name", zone_name, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - if if_match is not None: - header_parameters['If-Match'] = self._serialize.header("if_match", if_match, 'str') - if if_none_match is not None: - header_parameters['If-None-Match'] = self._serialize.header("if_none_match", if_none_match, 'str') - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(parameters, 'Zone') - body_content_kwargs['content'] = body_content - request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + 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: Literal["2018-03-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2018-03-01-preview") + ) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.Zone] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "Zone") + + request = build_create_or_update_request( + resource_group_name=resource_group_name, + zone_name=zone_name, + subscription_id=self._config.subscription_id, + if_match=if_match, + if_none_match=if_none_match, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create_or_update.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response if response.status_code not in [200, 201]: @@ -120,54 +446,56 @@ def create_or_update( raise HttpResponseError(response=response, error_format=ARMErrorFormat) if response.status_code == 200: - deserialized = self._deserialize('Zone', pipeline_response) + deserialized = self._deserialize("Zone", pipeline_response) if response.status_code == 201: - deserialized = self._deserialize('Zone', pipeline_response) + deserialized = self._deserialize("Zone", pipeline_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}'} # type: ignore + return deserialized # type: ignore - def _delete_initial( - self, - resource_group_name, # type: str - zone_name, # type: str - if_match=None, # type: Optional[str] - **kwargs # type: Any - ): - # type: (...) -> None - cls = kwargs.pop('cls', None) # type: ClsType[None] + create_or_update.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}" + } + + def _delete_initial( # pylint: disable=inconsistent-return-statements + self, resource_group_name: str, zone_name: str, if_match: Optional[str] = None, **kwargs: Any + ) -> None: 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 = "2018-03-01-preview" - accept = "application/json" - - # Construct URL - url = self._delete_initial.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), - 'zoneName': self._serialize.url("zone_name", zone_name, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), - } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct headers - header_parameters = {} # type: Dict[str, Any] - if if_match is not None: - header_parameters['If-Match'] = self._serialize.header("if_match", if_match, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + api_version: Literal["2018-03-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2018-03-01-preview") + ) + cls: ClsType[None] = kwargs.pop("cls", None) + + request = build_delete_request( + resource_group_name=resource_group_name, + zone_name=zone_name, + subscription_id=self._config.subscription_id, + if_match=if_match, + api_version=api_version, + template_url=self._delete_initial.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.delete(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: @@ -177,276 +505,385 @@ def _delete_initial( if cls: return cls(pipeline_response, None, {}) - _delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}'} # type: ignore + _delete_initial.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}" + } + @distributed_trace def begin_delete( - self, - resource_group_name, # type: str - zone_name, # type: str - if_match=None, # type: Optional[str] - **kwargs # type: Any - ): - # type: (...) -> LROPoller[None] + self, resource_group_name: str, zone_name: str, if_match: Optional[str] = None, **kwargs: Any + ) -> LROPoller[None]: """Deletes a DNS zone. WARNING: All DNS records in the zone will also be deleted. This operation cannot be undone. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param zone_name: The name of the DNS zone (without a terminating dot). + :param zone_name: The name of the DNS zone (without a terminating dot). Required. :type zone_name: str :param if_match: The etag of the DNS zone. Omit this value to always delete the current zone. Specify the last-seen etag value to prevent accidentally deleting any concurrent changes. + Default value is None. :type if_match: 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: Pass in True if you'd like the ARMPolling polling method, - False for no polling, or your own initialized polling object for a personal polling strategy. + :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. + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. :return: An instance of LROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[None] :raises ~azure.core.exceptions.HttpResponseError: """ - polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType[None] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2018-03-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2018-03-01-preview") ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + cls: ClsType[None] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) if cont_token is None: - raw_result = self._delete_initial( + raw_result = self._delete_initial( # type: ignore resource_group_name=resource_group_name, zone_name=zone_name, if_match=if_match, - cls=lambda x,y,z: x, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) + kwargs.pop("error_map", None) - kwargs.pop('error_map', None) - kwargs.pop('content_type', 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, {}) - path_format_arguments = { - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), - 'zoneName': self._serialize.url("zone_name", zone_name, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), - } - - if polling is True: polling_method = ARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) - elif polling is False: polling_method = NoPolling() - else: polling_method = polling + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - else: - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}'} # type: ignore + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - def get( - self, - resource_group_name, # type: str - zone_name, # type: str - **kwargs # type: Any - ): - # type: (...) -> "_models.Zone" + begin_delete.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}" + } + + @distributed_trace + def get(self, resource_group_name: str, zone_name: str, **kwargs: Any) -> _models.Zone: """Gets a DNS zone. Retrieves the zone properties, but not the record sets within the zone. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param zone_name: The name of the DNS zone (without a terminating dot). + :param zone_name: The name of the DNS zone (without a terminating dot). Required. :type zone_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: Zone, or the result of cls(response) + :return: Zone or the result of cls(response) :rtype: ~azure.mgmt.dns.v2018_03_01_preview.models.Zone - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Zone"] 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 = "2018-03-01-preview" - accept = "application/json" - - # Construct URL - url = self.get.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), - 'zoneName': self._serialize.url("zone_name", zone_name, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), - } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + api_version: Literal["2018-03-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2018-03-01-preview") + ) + cls: ClsType[_models.Zone] = kwargs.pop("cls", None) + + request = build_get_request( + resource_group_name=resource_group_name, + zone_name=zone_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('Zone', pipeline_response) + deserialized = self._deserialize("Zone", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}'} # type: ignore + get.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}" + } + + @overload def update( self, - resource_group_name, # type: str - zone_name, # type: str - parameters, # type: "_models.ZoneUpdate" - if_match=None, # type: Optional[str] - **kwargs # type: Any - ): - # type: (...) -> "_models.Zone" + resource_group_name: str, + zone_name: str, + parameters: _models.ZoneUpdate, + if_match: Optional[str] = None, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Zone: """Updates a DNS zone. Does not modify DNS records within the zone. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param zone_name: The name of the DNS zone (without a terminating dot). + :param zone_name: The name of the DNS zone (without a terminating dot). Required. :type zone_name: str - :param parameters: Parameters supplied to the Update operation. + :param parameters: Parameters supplied to the Update operation. Required. :type parameters: ~azure.mgmt.dns.v2018_03_01_preview.models.ZoneUpdate :param if_match: The etag of the DNS zone. Omit this value to always overwrite the current zone. Specify the last-seen etag value to prevent accidentally overwriting any concurrent - changes. + changes. 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: Zone or the result of cls(response) + :rtype: ~azure.mgmt.dns.v2018_03_01_preview.models.Zone + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def update( + self, + resource_group_name: str, + zone_name: str, + parameters: IO, + if_match: Optional[str] = None, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Zone: + """Updates a DNS zone. Does not modify DNS records within the zone. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param zone_name: The name of the DNS zone (without a terminating dot). Required. + :type zone_name: str + :param parameters: Parameters supplied to the Update operation. Required. + :type parameters: IO + :param if_match: The etag of the DNS zone. Omit this value to always overwrite the current + zone. Specify the last-seen etag value to prevent accidentally overwriting any concurrent + changes. 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: Zone, or the result of cls(response) + :return: Zone or the result of cls(response) :rtype: ~azure.mgmt.dns.v2018_03_01_preview.models.Zone - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def update( + self, + resource_group_name: str, + zone_name: str, + parameters: Union[_models.ZoneUpdate, IO], + if_match: Optional[str] = None, + **kwargs: Any + ) -> _models.Zone: + """Updates a DNS zone. Does not modify DNS records within the zone. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param zone_name: The name of the DNS zone (without a terminating dot). Required. + :type zone_name: str + :param parameters: Parameters supplied to the Update operation. Is either a ZoneUpdate type or + a IO type. Required. + :type parameters: ~azure.mgmt.dns.v2018_03_01_preview.models.ZoneUpdate or IO + :param if_match: The etag of the DNS zone. Omit this value to always overwrite the current + zone. Specify the last-seen etag value to prevent accidentally overwriting any concurrent + changes. 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: Zone or the result of cls(response) + :rtype: ~azure.mgmt.dns.v2018_03_01_preview.models.Zone + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Zone"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-03-01-preview" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.update.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), - 'zoneName': self._serialize.url("zone_name", zone_name, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - if if_match is not None: - header_parameters['If-Match'] = self._serialize.header("if_match", if_match, 'str') - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(parameters, 'ZoneUpdate') - body_content_kwargs['content'] = body_content - request = self._client.patch(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + 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: Literal["2018-03-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2018-03-01-preview") + ) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.Zone] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "ZoneUpdate") + + request = build_update_request( + resource_group_name=resource_group_name, + zone_name=zone_name, + subscription_id=self._config.subscription_id, + if_match=if_match, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.update.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = 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('Zone', pipeline_response) + deserialized = self._deserialize("Zone", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}'} # type: ignore + update.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}" + } + + @distributed_trace def list_by_resource_group( - self, - resource_group_name, # type: str - top=None, # type: Optional[int] - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.ZoneListResult"] + self, resource_group_name: str, top: Optional[int] = None, **kwargs: Any + ) -> Iterable["_models.Zone"]: """Lists the DNS zones within a resource group. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str :param top: The maximum number of record sets to return. If not specified, returns up to 100 - record sets. + record sets. Default value is None. :type top: int :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either ZoneListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.dns.v2018_03_01_preview.models.ZoneListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either Zone or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.dns.v2018_03_01_preview.models.Zone] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.ZoneListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2018-03-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2018-03-01-preview") + ) + cls: ClsType[_models.ZoneListResult] = kwargs.pop("cls", None) + 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 = "2018-03-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_by_resource_group.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - if top is not None: - query_parameters['$top'] = self._serialize.query("top", top, 'int') - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_by_resource_group_request( + resource_group_name=resource_group_name, + subscription_id=self._config.subscription_id, + top=top, + api_version=api_version, + template_url=self.list_by_resource_group.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('ZoneListResult', pipeline_response) + deserialized = self._deserialize("ZoneListResult", pipeline_response) list_of_elem = deserialized.value if cls: - list_of_elem = cls(list_of_elem) + list_of_elem = cls(list_of_elem) # type: ignore return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: @@ -455,71 +892,85 @@ def get_next(next_link=None): return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list_by_resource_group.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones'} # type: ignore + return ItemPaged(get_next, extract_data) - def list( - self, - top=None, # type: Optional[int] - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.ZoneListResult"] + list_by_resource_group.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones" + } + + @distributed_trace + def list(self, top: Optional[int] = None, **kwargs: Any) -> Iterable["_models.Zone"]: """Lists the DNS zones in all resource groups in a subscription. :param top: The maximum number of DNS zones to return. If not specified, returns up to 100 - zones. + zones. Default value is None. :type top: int :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either ZoneListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.dns.v2018_03_01_preview.models.ZoneListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either Zone or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.dns.v2018_03_01_preview.models.Zone] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.ZoneListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2018-03-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2018-03-01-preview") + ) + cls: ClsType[_models.ZoneListResult] = kwargs.pop("cls", None) + 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 = "2018-03-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list.metadata['url'] # type: ignore - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - if top is not None: - query_parameters['$top'] = self._serialize.query("top", top, 'int') - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_request( + subscription_id=self._config.subscription_id, + top=top, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('ZoneListResult', pipeline_response) + deserialized = self._deserialize("ZoneListResult", pipeline_response) list_of_elem = deserialized.value if cls: - list_of_elem = cls(list_of_elem) + list_of_elem = cls(list_of_elem) # type: ignore return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: @@ -528,7 +979,6 @@ def get_next(next_link=None): return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Network/dnszones'} # type: ignore + return ItemPaged(get_next, extract_data) + + list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Network/dnszones"} diff --git a/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_05_01/__init__.py b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_05_01/__init__.py index a21e1fdf48bb..23ee0cabde53 100644 --- a/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_05_01/__init__.py +++ b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_05_01/__init__.py @@ -10,10 +10,17 @@ from ._version import VERSION __version__ = VERSION -__all__ = ['DnsManagementClient'] try: - from ._patch import patch_sdk # type: ignore - patch_sdk() + from ._patch import __all__ as _patch_all + from ._patch import * # pylint: disable=unused-wildcard-import except ImportError: - pass + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "DnsManagementClient", +] +__all__.extend([p for p in _patch_all if p not in __all__]) + +_patch_sdk() diff --git a/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_05_01/_configuration.py b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_05_01/_configuration.py index c046b7b9737d..ccd82e5d7606 100644 --- a/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_05_01/_configuration.py +++ b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_05_01/_configuration.py @@ -6,66 +6,68 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING +import sys +from typing import Any, TYPE_CHECKING from azure.core.configuration import Configuration from azure.core.pipeline import policies -from azure.mgmt.core.policies import ARMHttpLoggingPolicy +from azure.mgmt.core.policies import ARMChallengeAuthenticationPolicy, ARMHttpLoggingPolicy 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 typing import Any - from azure.core.credentials import TokenCredential -class DnsManagementClientConfiguration(Configuration): +class DnsManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes """Configuration for DnsManagementClient. 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: Specifies the Azure subscription ID, which uniquely identifies the Microsoft Azure subscription. + :param subscription_id: Specifies the Azure subscription ID, which uniquely identifies the + Microsoft Azure subscription. Required. :type subscription_id: str + :keyword api_version: Api Version. Default value is "2018-05-01". Note that overriding this + default value may result in unsupported behavior. + :paramtype api_version: str """ - def __init__( - self, - credential, # type: "TokenCredential" - subscription_id, # type: str - **kwargs # type: Any - ): - # type: (...) -> None + def __init__(self, credential: "TokenCredential", subscription_id: str, **kwargs: Any) -> None: + super(DnsManagementClientConfiguration, self).__init__(**kwargs) + api_version: Literal["2018-05-01"] = kwargs.pop("api_version", "2018-05-01") + if credential is None: raise ValueError("Parameter 'credential' must not be None.") if subscription_id is None: raise ValueError("Parameter 'subscription_id' must not be None.") - super(DnsManagementClientConfiguration, self).__init__(**kwargs) self.credential = credential self.subscription_id = subscription_id - self.api_version = "2018-05-01" - self.credential_scopes = kwargs.pop('credential_scopes', ['https://management.azure.com/.default']) - kwargs.setdefault('sdk_moniker', 'mgmt-dns/{}'.format(VERSION)) + self.api_version = api_version + self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "mgmt-dns/{}".format(VERSION)) self._configure(**kwargs) - def _configure( - self, - **kwargs # type: Any - ): - # type: (...) -> None - self.user_agent_policy = kwargs.get('user_agent_policy') or policies.UserAgentPolicy(**kwargs) - self.headers_policy = kwargs.get('headers_policy') or policies.HeadersPolicy(**kwargs) - self.proxy_policy = kwargs.get('proxy_policy') or policies.ProxyPolicy(**kwargs) - self.logging_policy = kwargs.get('logging_policy') or policies.NetworkTraceLoggingPolicy(**kwargs) - self.http_logging_policy = kwargs.get('http_logging_policy') or ARMHttpLoggingPolicy(**kwargs) - self.retry_policy = kwargs.get('retry_policy') or policies.RetryPolicy(**kwargs) - self.custom_hook_policy = kwargs.get('custom_hook_policy') or policies.CustomHookPolicy(**kwargs) - self.redirect_policy = kwargs.get('redirect_policy') or policies.RedirectPolicy(**kwargs) - self.authentication_policy = kwargs.get('authentication_policy') + def _configure(self, **kwargs: Any) -> None: + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.RetryPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.RedirectPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") if self.credential and not self.authentication_policy: - self.authentication_policy = policies.BearerTokenCredentialPolicy(self.credential, *self.credential_scopes, **kwargs) + self.authentication_policy = ARMChallengeAuthenticationPolicy( + self.credential, *self.credential_scopes, **kwargs + ) diff --git a/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_05_01/_dns_management_client.py b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_05_01/_dns_management_client.py index 089a1436d217..4cf3a3dbc29d 100644 --- a/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_05_01/_dns_management_client.py +++ b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_05_01/_dns_management_client.py @@ -6,26 +6,23 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING +from copy import deepcopy +from typing import Any, TYPE_CHECKING +from azure.core.rest import HttpRequest, HttpResponse from azure.mgmt.core import ARMPipelineClient -from msrest import Deserializer, Serializer + +from . import models as _models +from .._serialization import Deserializer, Serializer +from ._configuration import DnsManagementClientConfiguration +from .operations import DnsResourceReferenceOperations, RecordSetsOperations, ZonesOperations if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Optional - from azure.core.credentials import TokenCredential - from azure.core.pipeline.transport import HttpRequest, HttpResponse - -from ._configuration import DnsManagementClientConfiguration -from .operations import RecordSetsOperations -from .operations import ZonesOperations -from .operations import DnsResourceReferenceOperations -from . import models -class DnsManagementClient(object): +class DnsManagementClient: # pylint: disable=client-accepts-api-version-keyword """The DNS Management Client. :ivar record_sets: RecordSetsOperations operations @@ -33,67 +30,72 @@ class DnsManagementClient(object): :ivar zones: ZonesOperations operations :vartype zones: azure.mgmt.dns.v2018_05_01.operations.ZonesOperations :ivar dns_resource_reference: DnsResourceReferenceOperations operations - :vartype dns_resource_reference: azure.mgmt.dns.v2018_05_01.operations.DnsResourceReferenceOperations - :param credential: Credential needed for the client to connect to Azure. + :vartype dns_resource_reference: + azure.mgmt.dns.v2018_05_01.operations.DnsResourceReferenceOperations + :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials.TokenCredential - :param subscription_id: Specifies the Azure subscription ID, which uniquely identifies the Microsoft Azure subscription. + :param subscription_id: Specifies the Azure subscription ID, which uniquely identifies the + Microsoft Azure subscription. Required. :type subscription_id: str - :param str base_url: Service URL - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :param base_url: Service URL. Default value is "https://management.azure.com". + :type base_url: str + :keyword api_version: Api Version. Default value is "2018-05-01". Note that overriding this + default value may result in unsupported behavior. + :paramtype api_version: str + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. """ def __init__( self, - credential, # type: "TokenCredential" - subscription_id, # type: str - base_url=None, # type: Optional[str] - **kwargs # type: Any - ): - # type: (...) -> None - if not base_url: - base_url = 'https://management.azure.com' - self._config = DnsManagementClientConfiguration(credential, subscription_id, **kwargs) + credential: "TokenCredential", + subscription_id: str, + base_url: str = "https://management.azure.com", + **kwargs: Any + ) -> None: + self._config = DnsManagementClientConfiguration( + 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)} + client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)} self._serialize = Serializer(client_models) - self._serialize.client_side_validation = False self._deserialize = Deserializer(client_models) - - self.record_sets = RecordSetsOperations( - self._client, self._config, self._serialize, self._deserialize) - self.zones = ZonesOperations( - self._client, self._config, self._serialize, self._deserialize) + self._serialize.client_side_validation = False + self.record_sets = RecordSetsOperations(self._client, self._config, self._serialize, self._deserialize) + self.zones = ZonesOperations(self._client, self._config, self._serialize, self._deserialize) self.dns_resource_reference = DnsResourceReferenceOperations( - self._client, self._config, self._serialize, self._deserialize) + self._client, self._config, self._serialize, self._deserialize + ) - def _send_request(self, http_request, **kwargs): - # type: (HttpRequest, Any) -> HttpResponse + def _send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: """Runs the network request through the client's chained policies. - :param http_request: The network request you want to make. Required. - :type http_request: ~azure.core.pipeline.transport.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to True. + >>> from azure.core.rest import HttpRequest + >>> request = HttpRequest("GET", "https://www.example.org/") + + >>> response = client._send_request(request) + + + For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request + + :param request: The network request you want to make. Required. + :type request: ~azure.core.rest.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to False. :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.pipeline.transport.HttpResponse + :rtype: ~azure.core.rest.HttpResponse """ - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), - } - http_request.url = self._client.format_url(http_request.url, **path_format_arguments) - stream = kwargs.pop("stream", True) - pipeline_response = self._client._pipeline.run(http_request, stream=stream, **kwargs) - return pipeline_response.http_response - - def close(self): - # type: () -> None + + request_copy = deepcopy(request) + request_copy.url = self._client.format_url(request_copy.url) + return self._client.send_request(request_copy, **kwargs) + + def close(self) -> None: self._client.close() - def __enter__(self): - # type: () -> DnsManagementClient + def __enter__(self) -> "DnsManagementClient": self._client.__enter__() return self - def __exit__(self, *exc_details): - # type: (Any) -> None + def __exit__(self, *exc_details: Any) -> None: self._client.__exit__(*exc_details) diff --git a/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_05_01/_metadata.json b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_05_01/_metadata.json index 6715ff309d7c..d6413dd44215 100644 --- a/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_05_01/_metadata.json +++ b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_05_01/_metadata.json @@ -5,39 +5,41 @@ "name": "DnsManagementClient", "filename": "_dns_management_client", "description": "The DNS Management Client.", - "base_url": "\u0027https://management.azure.com\u0027", - "custom_base_url": null, + "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\"], \"msrest\": [\"Deserializer\", \"Serializer\"], \"azure.mgmt.core\": [\"ARMPipelineClient\"]}, \"local\": {\"._configuration\": [\"DnsManagementClientConfiguration\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}, \"azurecore\": {\"azure.core.pipeline.transport\": [\"HttpRequest\", \"HttpResponse\"]}}}", - "async_imports": "{\"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}, \"regular\": {\"azurecore\": {\"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"], \"msrest\": [\"Deserializer\", \"Serializer\"], \"azure.mgmt.core\": [\"AsyncARMPipelineClient\"]}, \"local\": {\"._configuration\": [\"DnsManagementClientConfiguration\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}, \"azurecore\": {\"azure.core.pipeline.transport\": [\"AsyncHttpResponse\", \"HttpRequest\"]}}}" + "sync_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"azurecore\": {\"azure.mgmt.core\": [\"ARMPipelineClient\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"DnsManagementClientConfiguration\"], \".._serialization\": [\"Deserializer\", \"Serializer\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", + "async_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"azurecore\": {\"azure.mgmt.core\": [\"AsyncARMPipelineClient\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"DnsManagementClientConfiguration\"], \"..._serialization\": [\"Deserializer\", \"Serializer\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" }, "global_parameters": { "sync": { "credential": { - "signature": "credential, # type: \"TokenCredential\"", - "description": "Credential needed for the client to connect to Azure.", + "signature": "credential: \"TokenCredential\",", + "description": "Credential needed for the client to connect to Azure. Required.", "docstring_type": "~azure.core.credentials.TokenCredential", - "required": true + "required": true, + "method_location": "positional" }, "subscription_id": { - "signature": "subscription_id, # type: str", - "description": "Specifies the Azure subscription ID, which uniquely identifies the Microsoft Azure subscription.", + "signature": "subscription_id: str,", + "description": "Specifies the Azure subscription ID, which uniquely identifies the Microsoft Azure subscription. Required.", "docstring_type": "str", - "required": true + "required": true, + "method_location": "positional" } }, "async": { "credential": { "signature": "credential: \"AsyncTokenCredential\",", - "description": "Credential needed for the client to connect to Azure.", + "description": "Credential needed for the client to connect to Azure. Required.", "docstring_type": "~azure.core.credentials_async.AsyncTokenCredential", "required": true }, "subscription_id": { "signature": "subscription_id: str,", - "description": "Specifies the Azure subscription ID, which uniquely identifies the Microsoft Azure subscription.", + "description": "Specifies the Azure subscription ID, which uniquely identifies the Microsoft Azure subscription. Required.", "docstring_type": "str", "required": true } @@ -48,22 +50,25 @@ "service_client_specific": { "sync": { "api_version": { - "signature": "api_version=None, # type: Optional[str]", + "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 + "required": false, + "method_location": "positional" }, "base_url": { - "signature": "base_url=None, # type: Optional[str]", + "signature": "base_url: str = \"https://management.azure.com\",", "description": "Service URL", "docstring_type": "str", - "required": false + "required": false, + "method_location": "positional" }, "profile": { - "signature": "profile=KnownProfiles.default, # type: KnownProfiles", + "signature": "profile: KnownProfiles=KnownProfiles.default,", "description": "A profile definition, from KnownProfiles to dict.", "docstring_type": "azure.profiles.KnownProfiles", - "required": false + "required": false, + "method_location": "positional" } }, "async": { @@ -71,19 +76,22 @@ "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 + "required": false, + "method_location": "positional" }, "base_url": { - "signature": "base_url: Optional[str] = None,", + "signature": "base_url: str = \"https://management.azure.com\",", "description": "Service URL", "docstring_type": "str", - "required": false + "required": false, + "method_location": "positional" }, "profile": { "signature": "profile: KnownProfiles = KnownProfiles.default,", "description": "A profile definition, from KnownProfiles to dict.", "docstring_type": "azure.profiles.KnownProfiles", - "required": false + "required": false, + "method_location": "positional" } } } @@ -91,15 +99,14 @@ "config": { "credential": true, "credential_scopes": ["https://management.azure.com/.default"], - "credential_default_policy_type": "BearerTokenCredentialPolicy", - "credential_default_policy_type_has_async_version": true, - "credential_key_header_name": null, - "sync_imports": "{\"regular\": {\"azurecore\": {\"azure.core.configuration\": [\"Configuration\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"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\"]}, \"local\": {\".._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" + "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": { "record_sets": "RecordSetsOperations", "zones": "ZonesOperations", "dns_resource_reference": "DnsResourceReferenceOperations" } -} \ No newline at end of file +} diff --git a/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_05_01/_patch.py b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_05_01/_patch.py new file mode 100644 index 000000000000..f7dd32510333 --- /dev/null +++ b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_05_01/_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/network/azure-mgmt-dns/azure/mgmt/dns/v2018_05_01/_vendor.py b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_05_01/_vendor.py new file mode 100644 index 000000000000..bd0df84f5319 --- /dev/null +++ b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_05_01/_vendor.py @@ -0,0 +1,30 @@ +# -------------------------------------------------------------------------- +# 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 typing import List, cast + +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) + if files: + request.set_formdata_body(files) + return request + + +def _format_url_section(template, **kwargs): + components = template.split("/") + while components: + try: + return template.format(**kwargs) + except KeyError as key: + # Need the cast, as for some reasons "split" is typed as list[str | Any] + formatted_components = cast(List[str], template.split("/")) + components = [c for c in formatted_components if "{}".format(key.args[0]) not in c] + template = "/".join(components) diff --git a/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_05_01/_version.py b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_05_01/_version.py index 142a0420b39b..e5754a47ce68 100644 --- a/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_05_01/_version.py +++ b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_05_01/_version.py @@ -6,4 +6,4 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -VERSION = "8.0.0" +VERSION = "1.0.0b1" diff --git a/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_05_01/aio/__init__.py b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_05_01/aio/__init__.py index 1a93fabcef86..e94042023e78 100644 --- a/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_05_01/aio/__init__.py +++ b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_05_01/aio/__init__.py @@ -7,4 +7,17 @@ # -------------------------------------------------------------------------- from ._dns_management_client import DnsManagementClient -__all__ = ['DnsManagementClient'] + +try: + from ._patch import __all__ as _patch_all + from ._patch import * # pylint: disable=unused-wildcard-import +except ImportError: + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "DnsManagementClient", +] +__all__.extend([p for p in _patch_all if p not in __all__]) + +_patch_sdk() diff --git a/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_05_01/aio/_configuration.py b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_05_01/aio/_configuration.py index c2fdc75518e1..8a664a66ae68 100644 --- a/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_05_01/aio/_configuration.py +++ b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_05_01/aio/_configuration.py @@ -6,62 +6,68 @@ # 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 from azure.core.pipeline import policies -from azure.mgmt.core.policies import ARMHttpLoggingPolicy +from azure.mgmt.core.policies import ARMHttpLoggingPolicy, AsyncARMChallengeAuthenticationPolicy 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 -class DnsManagementClientConfiguration(Configuration): +class DnsManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes """Configuration for DnsManagementClient. 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: Specifies the Azure subscription ID, which uniquely identifies the Microsoft Azure subscription. + :param subscription_id: Specifies the Azure subscription ID, which uniquely identifies the + Microsoft Azure subscription. Required. :type subscription_id: str + :keyword api_version: Api Version. Default value is "2018-05-01". Note that overriding this + default value may result in unsupported behavior. + :paramtype api_version: str """ - def __init__( - self, - credential: "AsyncTokenCredential", - subscription_id: str, - **kwargs: Any - ) -> None: + def __init__(self, credential: "AsyncTokenCredential", subscription_id: str, **kwargs: Any) -> None: + super(DnsManagementClientConfiguration, self).__init__(**kwargs) + api_version: Literal["2018-05-01"] = kwargs.pop("api_version", "2018-05-01") + if credential is None: raise ValueError("Parameter 'credential' must not be None.") if subscription_id is None: raise ValueError("Parameter 'subscription_id' must not be None.") - super(DnsManagementClientConfiguration, self).__init__(**kwargs) self.credential = credential self.subscription_id = subscription_id - self.api_version = "2018-05-01" - self.credential_scopes = kwargs.pop('credential_scopes', ['https://management.azure.com/.default']) - kwargs.setdefault('sdk_moniker', 'mgmt-dns/{}'.format(VERSION)) + self.api_version = api_version + self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "mgmt-dns/{}".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 = policies.AsyncBearerTokenCredentialPolicy(self.credential, *self.credential_scopes, **kwargs) + self.authentication_policy = AsyncARMChallengeAuthenticationPolicy( + self.credential, *self.credential_scopes, **kwargs + ) diff --git a/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_05_01/aio/_dns_management_client.py b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_05_01/aio/_dns_management_client.py index 37e833ed55bb..ce8a3c8a4f87 100644 --- a/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_05_01/aio/_dns_management_client.py +++ b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_05_01/aio/_dns_management_client.py @@ -6,24 +6,23 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, Optional, TYPE_CHECKING +from copy import deepcopy +from typing import Any, Awaitable, TYPE_CHECKING -from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.rest import AsyncHttpResponse, HttpRequest from azure.mgmt.core import AsyncARMPipelineClient -from msrest import Deserializer, Serializer + +from .. import models as _models +from ..._serialization import Deserializer, Serializer +from ._configuration import DnsManagementClientConfiguration +from .operations import DnsResourceReferenceOperations, RecordSetsOperations, ZonesOperations if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential -from ._configuration import DnsManagementClientConfiguration -from .operations import RecordSetsOperations -from .operations import ZonesOperations -from .operations import DnsResourceReferenceOperations -from .. import models - -class DnsManagementClient(object): +class DnsManagementClient: # pylint: disable=client-accepts-api-version-keyword """The DNS Management Client. :ivar record_sets: RecordSetsOperations operations @@ -31,55 +30,65 @@ class DnsManagementClient(object): :ivar zones: ZonesOperations operations :vartype zones: azure.mgmt.dns.v2018_05_01.aio.operations.ZonesOperations :ivar dns_resource_reference: DnsResourceReferenceOperations operations - :vartype dns_resource_reference: azure.mgmt.dns.v2018_05_01.aio.operations.DnsResourceReferenceOperations - :param credential: Credential needed for the client to connect to Azure. + :vartype dns_resource_reference: + azure.mgmt.dns.v2018_05_01.aio.operations.DnsResourceReferenceOperations + :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials_async.AsyncTokenCredential - :param subscription_id: Specifies the Azure subscription ID, which uniquely identifies the Microsoft Azure subscription. + :param subscription_id: Specifies the Azure subscription ID, which uniquely identifies the + Microsoft Azure subscription. Required. :type subscription_id: str - :param str base_url: Service URL - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :param base_url: Service URL. Default value is "https://management.azure.com". + :type base_url: str + :keyword api_version: Api Version. Default value is "2018-05-01". Note that overriding this + default value may result in unsupported behavior. + :paramtype api_version: str + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. """ def __init__( self, credential: "AsyncTokenCredential", subscription_id: str, - base_url: Optional[str] = None, + base_url: str = "https://management.azure.com", **kwargs: Any ) -> None: - if not base_url: - base_url = 'https://management.azure.com' - self._config = DnsManagementClientConfiguration(credential, subscription_id, **kwargs) + self._config = DnsManagementClientConfiguration( + 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)} + client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)} self._serialize = Serializer(client_models) - self._serialize.client_side_validation = False self._deserialize = Deserializer(client_models) - - self.record_sets = RecordSetsOperations( - self._client, self._config, self._serialize, self._deserialize) - self.zones = ZonesOperations( - self._client, self._config, self._serialize, self._deserialize) + self._serialize.client_side_validation = False + self.record_sets = RecordSetsOperations(self._client, self._config, self._serialize, self._deserialize) + self.zones = ZonesOperations(self._client, self._config, self._serialize, self._deserialize) self.dns_resource_reference = DnsResourceReferenceOperations( - self._client, self._config, self._serialize, self._deserialize) + self._client, self._config, self._serialize, self._deserialize + ) - async def _send_request(self, http_request: HttpRequest, **kwargs: Any) -> AsyncHttpResponse: + def _send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]: """Runs the network request through the client's chained policies. - :param http_request: The network request you want to make. Required. - :type http_request: ~azure.core.pipeline.transport.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to True. + >>> from azure.core.rest import HttpRequest + >>> request = HttpRequest("GET", "https://www.example.org/") + + >>> response = await client._send_request(request) + + + For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request + + :param request: The network request you want to make. Required. + :type request: ~azure.core.rest.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to False. :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.pipeline.transport.AsyncHttpResponse + :rtype: ~azure.core.rest.AsyncHttpResponse """ - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), - } - http_request.url = self._client.format_url(http_request.url, **path_format_arguments) - stream = kwargs.pop("stream", True) - pipeline_response = await self._client._pipeline.run(http_request, stream=stream, **kwargs) - return pipeline_response.http_response + + request_copy = deepcopy(request) + request_copy.url = self._client.format_url(request_copy.url) + return self._client.send_request(request_copy, **kwargs) async def close(self) -> None: await self._client.close() @@ -88,5 +97,5 @@ async def __aenter__(self) -> "DnsManagementClient": await self._client.__aenter__() return self - async def __aexit__(self, *exc_details) -> None: + async def __aexit__(self, *exc_details: Any) -> None: await self._client.__aexit__(*exc_details) diff --git a/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_05_01/aio/_patch.py b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_05_01/aio/_patch.py new file mode 100644 index 000000000000..f7dd32510333 --- /dev/null +++ b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_05_01/aio/_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/network/azure-mgmt-dns/azure/mgmt/dns/v2018_05_01/aio/operations/__init__.py b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_05_01/aio/operations/__init__.py index 1b7483b4a71f..bb9e9fe8e4bb 100644 --- a/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_05_01/aio/operations/__init__.py +++ b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_05_01/aio/operations/__init__.py @@ -10,8 +10,14 @@ from ._zones_operations import ZonesOperations from ._dns_resource_reference_operations import DnsResourceReferenceOperations +from ._patch import __all__ as _patch_all +from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import patch_sdk as _patch_sdk + __all__ = [ - 'RecordSetsOperations', - 'ZonesOperations', - 'DnsResourceReferenceOperations', + "RecordSetsOperations", + "ZonesOperations", + "DnsResourceReferenceOperations", ] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_05_01/aio/operations/_dns_resource_reference_operations.py b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_05_01/aio/operations/_dns_resource_reference_operations.py index a254031feeff..049142466fd0 100644 --- a/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_05_01/aio/operations/_dns_resource_reference_operations.py +++ b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_05_01/aio/operations/_dns_resource_reference_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,95 +6,159 @@ # 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, Generic, Optional, TypeVar -import warnings - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +import sys +from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, overload + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models - -T = TypeVar('T') +from ..._vendor import _convert_request +from ...operations._dns_resource_reference_operations import build_get_by_target_resources_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 DnsResourceReferenceOperations: - """DnsResourceReferenceOperations 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 DnsResourceReferenceOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.dns.v2018_05_01.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.dns.v2018_05_01.aio.DnsManagementClient`'s + :attr:`dns_resource_reference` 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") + @overload async def get_by_target_resources( - self, - parameters: "_models.DnsResourceReferenceRequest", - **kwargs - ) -> "_models.DnsResourceReferenceResult": + self, parameters: _models.DnsResourceReferenceRequest, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.DnsResourceReferenceResult: """Returns the DNS records specified by the referencing targetResourceIds. - :param parameters: Properties for dns resource reference request. + :param parameters: Properties for dns resource reference request. Required. :type parameters: ~azure.mgmt.dns.v2018_05_01.models.DnsResourceReferenceRequest + :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: DnsResourceReferenceResult or the result of cls(response) + :rtype: ~azure.mgmt.dns.v2018_05_01.models.DnsResourceReferenceResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def get_by_target_resources( + self, parameters: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.DnsResourceReferenceResult: + """Returns the DNS records specified by the referencing targetResourceIds. + + :param parameters: Properties for dns resource reference 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: DnsResourceReferenceResult, or the result of cls(response) + :return: DnsResourceReferenceResult or the result of cls(response) :rtype: ~azure.mgmt.dns.v2018_05_01.models.DnsResourceReferenceResult - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def get_by_target_resources( + self, parameters: Union[_models.DnsResourceReferenceRequest, IO], **kwargs: Any + ) -> _models.DnsResourceReferenceResult: + """Returns the DNS records specified by the referencing targetResourceIds. + + :param parameters: Properties for dns resource reference request. Is either a + DnsResourceReferenceRequest type or a IO type. Required. + :type parameters: ~azure.mgmt.dns.v2018_05_01.models.DnsResourceReferenceRequest 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: DnsResourceReferenceResult or the result of cls(response) + :rtype: ~azure.mgmt.dns.v2018_05_01.models.DnsResourceReferenceResult + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.DnsResourceReferenceResult"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-05-01" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.get_by_target_resources.metadata['url'] # type: ignore - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(parameters, 'DnsResourceReferenceRequest') - body_content_kwargs['content'] = body_content - request = self._client.post(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + 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: Literal["2018-05-01"] = kwargs.pop("api_version", _params.pop("api-version", "2018-05-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.DnsResourceReferenceResult] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "DnsResourceReferenceRequest") + + request = build_get_by_target_resources_request( + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.get_by_target_resources.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = 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('DnsResourceReferenceResult', pipeline_response) + deserialized = self._deserialize("DnsResourceReferenceResult", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get_by_target_resources.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Network/getDnsResourceReference'} # type: ignore + + get_by_target_resources.metadata = { + "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Network/getDnsResourceReference" + } diff --git a/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_05_01/aio/operations/_patch.py b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_05_01/aio/operations/_patch.py new file mode 100644 index 000000000000..f7dd32510333 --- /dev/null +++ b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_05_01/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/network/azure-mgmt-dns/azure/mgmt/dns/v2018_05_01/aio/operations/_record_sets_operations.py b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_05_01/aio/operations/_record_sets_operations.py index 1f22824ea0b6..1ee6ed50a5d4 100644 --- a/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_05_01/aio/operations/_record_sets_operations.py +++ b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_05_01/aio/operations/_record_sets_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,197 +6,425 @@ # 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, Generic, Optional, TypeVar, Union -import warnings +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, HttpRequest +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 - -T = TypeVar('T') +from ..._vendor import _convert_request +from ...operations._record_sets_operations import ( + build_create_or_update_request, + build_delete_request, + build_get_request, + build_list_all_by_dns_zone_request, + build_list_by_dns_zone_request, + build_list_by_type_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 RecordSetsOperations: - """RecordSetsOperations 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 RecordSetsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.dns.v2018_05_01.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.dns.v2018_05_01.aio.DnsManagementClient`'s + :attr:`record_sets` 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") + @overload async def update( self, resource_group_name: str, zone_name: str, relative_record_set_name: str, - record_type: Union[str, "_models.RecordType"], - parameters: "_models.RecordSet", + record_type: Union[str, _models.RecordType], + parameters: _models.RecordSet, if_match: Optional[str] = None, - **kwargs - ) -> "_models.RecordSet": + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RecordSet: """Updates a record set within a DNS zone. - :param resource_group_name: The name of the resource group. + :param resource_group_name: The name of the resource group. Required. :type resource_group_name: str - :param zone_name: The name of the DNS zone (without a terminating dot). + :param zone_name: The name of the DNS zone (without a terminating dot). Required. :type zone_name: str :param relative_record_set_name: The name of the record set, relative to the name of the zone. + Required. :type relative_record_set_name: str - :param record_type: The type of DNS record in this record set. + :param record_type: The type of DNS record in this record set. Known values are: "A", "AAAA", + "CAA", "CNAME", "MX", "NS", "PTR", "SOA", "SRV", and "TXT". Required. :type record_type: str or ~azure.mgmt.dns.v2018_05_01.models.RecordType - :param parameters: Parameters supplied to the Update operation. + :param parameters: Parameters supplied to the Update operation. Required. :type parameters: ~azure.mgmt.dns.v2018_05_01.models.RecordSet :param if_match: The etag of the record set. Omit this value to always overwrite the current record set. Specify the last-seen etag value to prevent accidentally overwriting concurrent - changes. + changes. 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: RecordSet or the result of cls(response) + :rtype: ~azure.mgmt.dns.v2018_05_01.models.RecordSet + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def update( + self, + resource_group_name: str, + zone_name: str, + relative_record_set_name: str, + record_type: Union[str, _models.RecordType], + parameters: IO, + if_match: Optional[str] = None, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RecordSet: + """Updates a record set within a DNS zone. + + :param resource_group_name: The name of the resource group. Required. + :type resource_group_name: str + :param zone_name: The name of the DNS zone (without a terminating dot). Required. + :type zone_name: str + :param relative_record_set_name: The name of the record set, relative to the name of the zone. + Required. + :type relative_record_set_name: str + :param record_type: The type of DNS record in this record set. Known values are: "A", "AAAA", + "CAA", "CNAME", "MX", "NS", "PTR", "SOA", "SRV", and "TXT". Required. + :type record_type: str or ~azure.mgmt.dns.v2018_05_01.models.RecordType + :param parameters: Parameters supplied to the Update operation. Required. + :type parameters: IO + :param if_match: The etag of the record set. Omit this value to always overwrite the current + record set. Specify the last-seen etag value to prevent accidentally overwriting concurrent + changes. 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: RecordSet or the result of cls(response) + :rtype: ~azure.mgmt.dns.v2018_05_01.models.RecordSet + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def update( + self, + resource_group_name: str, + zone_name: str, + relative_record_set_name: str, + record_type: Union[str, _models.RecordType], + parameters: Union[_models.RecordSet, IO], + if_match: Optional[str] = None, + **kwargs: Any + ) -> _models.RecordSet: + """Updates a record set within a DNS zone. + + :param resource_group_name: The name of the resource group. Required. + :type resource_group_name: str + :param zone_name: The name of the DNS zone (without a terminating dot). Required. + :type zone_name: str + :param relative_record_set_name: The name of the record set, relative to the name of the zone. + Required. + :type relative_record_set_name: str + :param record_type: The type of DNS record in this record set. Known values are: "A", "AAAA", + "CAA", "CNAME", "MX", "NS", "PTR", "SOA", "SRV", and "TXT". Required. + :type record_type: str or ~azure.mgmt.dns.v2018_05_01.models.RecordType + :param parameters: Parameters supplied to the Update operation. Is either a RecordSet type or a + IO type. Required. + :type parameters: ~azure.mgmt.dns.v2018_05_01.models.RecordSet or IO + :param if_match: The etag of the record set. Omit this value to always overwrite the current + record set. Specify the last-seen etag value to prevent accidentally overwriting concurrent + changes. 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: RecordSet, or the result of cls(response) + :return: RecordSet or the result of cls(response) :rtype: ~azure.mgmt.dns.v2018_05_01.models.RecordSet - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RecordSet"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-05-01" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.update.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), - 'zoneName': self._serialize.url("zone_name", zone_name, 'str'), - 'relativeRecordSetName': self._serialize.url("relative_record_set_name", relative_record_set_name, 'str', skip_quote=True), - 'recordType': self._serialize.url("record_type", record_type, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - if if_match is not None: - header_parameters['If-Match'] = self._serialize.header("if_match", if_match, 'str') - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(parameters, 'RecordSet') - body_content_kwargs['content'] = body_content - request = self._client.patch(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + 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: Literal["2018-05-01"] = kwargs.pop("api_version", _params.pop("api-version", "2018-05-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.RecordSet] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "RecordSet") + + request = build_update_request( + resource_group_name=resource_group_name, + zone_name=zone_name, + relative_record_set_name=relative_record_set_name, + record_type=record_type, + subscription_id=self._config.subscription_id, + if_match=if_match, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.update.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = 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('RecordSet', pipeline_response) + deserialized = self._deserialize("RecordSet", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}/{recordType}/{relativeRecordSetName}'} # type: ignore + update.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}/{recordType}/{relativeRecordSetName}" + } + + @overload async def create_or_update( self, resource_group_name: str, zone_name: str, relative_record_set_name: str, - record_type: Union[str, "_models.RecordType"], - parameters: "_models.RecordSet", + record_type: Union[str, _models.RecordType], + parameters: _models.RecordSet, if_match: Optional[str] = None, if_none_match: Optional[str] = None, - **kwargs - ) -> "_models.RecordSet": + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RecordSet: """Creates or updates a record set within a DNS zone. - :param resource_group_name: The name of the resource group. + :param resource_group_name: The name of the resource group. Required. :type resource_group_name: str - :param zone_name: The name of the DNS zone (without a terminating dot). + :param zone_name: The name of the DNS zone (without a terminating dot). Required. :type zone_name: str :param relative_record_set_name: The name of the record set, relative to the name of the zone. + Required. :type relative_record_set_name: str :param record_type: The type of DNS record in this record set. Record sets of type SOA can be - updated but not created (they are created when the DNS zone is created). + updated but not created (they are created when the DNS zone is created). Known values are: "A", + "AAAA", "CAA", "CNAME", "MX", "NS", "PTR", "SOA", "SRV", and "TXT". Required. :type record_type: str or ~azure.mgmt.dns.v2018_05_01.models.RecordType - :param parameters: Parameters supplied to the CreateOrUpdate operation. + :param parameters: Parameters supplied to the CreateOrUpdate operation. Required. :type parameters: ~azure.mgmt.dns.v2018_05_01.models.RecordSet :param if_match: The etag of the record set. Omit this value to always overwrite the current record set. Specify the last-seen etag value to prevent accidentally overwriting any concurrent - changes. + changes. Default value is None. + :type if_match: str + :param if_none_match: Set to '*' to allow a new record set to be created, but to prevent + updating an existing record set. 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: RecordSet or the result of cls(response) + :rtype: ~azure.mgmt.dns.v2018_05_01.models.RecordSet + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_or_update( + self, + resource_group_name: str, + zone_name: str, + relative_record_set_name: str, + record_type: Union[str, _models.RecordType], + parameters: IO, + if_match: Optional[str] = None, + if_none_match: Optional[str] = None, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RecordSet: + """Creates or updates a record set within a DNS zone. + + :param resource_group_name: The name of the resource group. Required. + :type resource_group_name: str + :param zone_name: The name of the DNS zone (without a terminating dot). Required. + :type zone_name: str + :param relative_record_set_name: The name of the record set, relative to the name of the zone. + Required. + :type relative_record_set_name: str + :param record_type: The type of DNS record in this record set. Record sets of type SOA can be + updated but not created (they are created when the DNS zone is created). Known values are: "A", + "AAAA", "CAA", "CNAME", "MX", "NS", "PTR", "SOA", "SRV", and "TXT". Required. + :type record_type: str or ~azure.mgmt.dns.v2018_05_01.models.RecordType + :param parameters: Parameters supplied to the CreateOrUpdate operation. Required. + :type parameters: IO + :param if_match: The etag of the record set. Omit this value to always overwrite the current + record set. Specify the last-seen etag value to prevent accidentally overwriting any concurrent + changes. Default value is None. + :type if_match: str + :param if_none_match: Set to '*' to allow a new record set to be created, but to prevent + updating an existing record set. 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: RecordSet or the result of cls(response) + :rtype: ~azure.mgmt.dns.v2018_05_01.models.RecordSet + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create_or_update( + self, + resource_group_name: str, + zone_name: str, + relative_record_set_name: str, + record_type: Union[str, _models.RecordType], + parameters: Union[_models.RecordSet, IO], + if_match: Optional[str] = None, + if_none_match: Optional[str] = None, + **kwargs: Any + ) -> _models.RecordSet: + """Creates or updates a record set within a DNS zone. + + :param resource_group_name: The name of the resource group. Required. + :type resource_group_name: str + :param zone_name: The name of the DNS zone (without a terminating dot). Required. + :type zone_name: str + :param relative_record_set_name: The name of the record set, relative to the name of the zone. + Required. + :type relative_record_set_name: str + :param record_type: The type of DNS record in this record set. Record sets of type SOA can be + updated but not created (they are created when the DNS zone is created). Known values are: "A", + "AAAA", "CAA", "CNAME", "MX", "NS", "PTR", "SOA", "SRV", and "TXT". Required. + :type record_type: str or ~azure.mgmt.dns.v2018_05_01.models.RecordType + :param parameters: Parameters supplied to the CreateOrUpdate operation. Is either a RecordSet + type or a IO type. Required. + :type parameters: ~azure.mgmt.dns.v2018_05_01.models.RecordSet or IO + :param if_match: The etag of the record set. Omit this value to always overwrite the current + record set. Specify the last-seen etag value to prevent accidentally overwriting any concurrent + changes. Default value is None. :type if_match: str :param if_none_match: Set to '*' to allow a new record set to be created, but to prevent - updating an existing record set. Other values will be ignored. + updating an existing record set. 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: RecordSet, or the result of cls(response) + :return: RecordSet or the result of cls(response) :rtype: ~azure.mgmt.dns.v2018_05_01.models.RecordSet - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RecordSet"] 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 = "2018-05-01" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.create_or_update.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), - 'zoneName': self._serialize.url("zone_name", zone_name, 'str'), - 'relativeRecordSetName': self._serialize.url("relative_record_set_name", relative_record_set_name, 'str', skip_quote=True), - 'recordType': self._serialize.url("record_type", record_type, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - if if_match is not None: - header_parameters['If-Match'] = self._serialize.header("if_match", if_match, 'str') - if if_none_match is not None: - header_parameters['If-None-Match'] = self._serialize.header("if_none_match", if_none_match, 'str') - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(parameters, 'RecordSet') - body_content_kwargs['content'] = body_content - request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + 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: Literal["2018-05-01"] = kwargs.pop("api_version", _params.pop("api-version", "2018-05-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.RecordSet] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "RecordSet") + + request = build_create_or_update_request( + resource_group_name=resource_group_name, + zone_name=zone_name, + relative_record_set_name=relative_record_set_name, + record_type=record_type, + subscription_id=self._config.subscription_id, + if_match=if_match, + if_none_match=if_none_match, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create_or_update.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response if response.status_code not in [200, 201]: @@ -203,77 +432,85 @@ async def create_or_update( raise HttpResponseError(response=response, error_format=ARMErrorFormat) if response.status_code == 200: - deserialized = self._deserialize('RecordSet', pipeline_response) + deserialized = self._deserialize("RecordSet", pipeline_response) if response.status_code == 201: - deserialized = self._deserialize('RecordSet', pipeline_response) + deserialized = self._deserialize("RecordSet", pipeline_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}/{recordType}/{relativeRecordSetName}'} # type: ignore + return deserialized # type: ignore - async def delete( + create_or_update.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}/{recordType}/{relativeRecordSetName}" + } + + @distributed_trace_async + async def delete( # pylint: disable=inconsistent-return-statements self, resource_group_name: str, zone_name: str, relative_record_set_name: str, - record_type: Union[str, "_models.RecordType"], + record_type: Union[str, _models.RecordType], if_match: Optional[str] = None, - **kwargs + **kwargs: Any ) -> None: """Deletes a record set from a DNS zone. This operation cannot be undone. - :param resource_group_name: The name of the resource group. + :param resource_group_name: The name of the resource group. Required. :type resource_group_name: str - :param zone_name: The name of the DNS zone (without a terminating dot). + :param zone_name: The name of the DNS zone (without a terminating dot). Required. :type zone_name: str :param relative_record_set_name: The name of the record set, relative to the name of the zone. + Required. :type relative_record_set_name: str :param record_type: The type of DNS record in this record set. Record sets of type SOA cannot - be deleted (they are deleted when the DNS zone is deleted). + be deleted (they are deleted when the DNS zone is deleted). Known values are: "A", "AAAA", + "CAA", "CNAME", "MX", "NS", "PTR", "SOA", "SRV", and "TXT". Required. :type record_type: str or ~azure.mgmt.dns.v2018_05_01.models.RecordType :param if_match: The etag of the record set. Omit this value to always delete the current record set. Specify the last-seen etag value to prevent accidentally deleting any concurrent - changes. + changes. Default value is None. :type if_match: 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 - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-05-01" - accept = "application/json" - - # Construct URL - url = self.delete.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), - 'zoneName': self._serialize.url("zone_name", zone_name, 'str'), - 'relativeRecordSetName': self._serialize.url("relative_record_set_name", relative_record_set_name, 'str', skip_quote=True), - 'recordType': self._serialize.url("record_type", record_type, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2018-05-01"] = kwargs.pop("api_version", _params.pop("api-version", "2018-05-01")) + cls: ClsType[None] = kwargs.pop("cls", None) + + request = build_delete_request( + resource_group_name=resource_group_name, + zone_name=zone_name, + relative_record_set_name=relative_record_set_name, + record_type=record_type, + subscription_id=self._config.subscription_id, + if_match=if_match, + api_version=api_version, + template_url=self.delete.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) - # Construct headers - header_parameters = {} # type: Dict[str, Any] - if if_match is not None: - header_parameters['If-Match'] = self._serialize.header("if_match", if_match, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.delete(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 204]: @@ -283,152 +520,179 @@ async def delete( if cls: return cls(pipeline_response, None, {}) - delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}/{recordType}/{relativeRecordSetName}'} # type: ignore + delete.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}/{recordType}/{relativeRecordSetName}" + } + @distributed_trace_async async def get( self, resource_group_name: str, zone_name: str, relative_record_set_name: str, - record_type: Union[str, "_models.RecordType"], - **kwargs - ) -> "_models.RecordSet": + record_type: Union[str, _models.RecordType], + **kwargs: Any + ) -> _models.RecordSet: """Gets a record set. - :param resource_group_name: The name of the resource group. + :param resource_group_name: The name of the resource group. Required. :type resource_group_name: str - :param zone_name: The name of the DNS zone (without a terminating dot). + :param zone_name: The name of the DNS zone (without a terminating dot). Required. :type zone_name: str :param relative_record_set_name: The name of the record set, relative to the name of the zone. + Required. :type relative_record_set_name: str - :param record_type: The type of DNS record in this record set. + :param record_type: The type of DNS record in this record set. Known values are: "A", "AAAA", + "CAA", "CNAME", "MX", "NS", "PTR", "SOA", "SRV", and "TXT". Required. :type record_type: str or ~azure.mgmt.dns.v2018_05_01.models.RecordType :keyword callable cls: A custom type or function that will be passed the direct response - :return: RecordSet, or the result of cls(response) + :return: RecordSet or the result of cls(response) :rtype: ~azure.mgmt.dns.v2018_05_01.models.RecordSet - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RecordSet"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-05-01" - accept = "application/json" - - # Construct URL - url = self.get.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), - 'zoneName': self._serialize.url("zone_name", zone_name, 'str'), - 'relativeRecordSetName': self._serialize.url("relative_record_set_name", relative_record_set_name, 'str', skip_quote=True), - 'recordType': self._serialize.url("record_type", record_type, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2018-05-01"] = kwargs.pop("api_version", _params.pop("api-version", "2018-05-01")) + cls: ClsType[_models.RecordSet] = kwargs.pop("cls", None) + + request = build_get_request( + resource_group_name=resource_group_name, + zone_name=zone_name, + relative_record_set_name=relative_record_set_name, + record_type=record_type, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('RecordSet', pipeline_response) + deserialized = self._deserialize("RecordSet", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}/{recordType}/{relativeRecordSetName}'} # type: ignore + get.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}/{recordType}/{relativeRecordSetName}" + } + + @distributed_trace def list_by_type( self, resource_group_name: str, zone_name: str, - record_type: Union[str, "_models.RecordType"], + record_type: Union[str, _models.RecordType], top: Optional[int] = None, recordsetnamesuffix: Optional[str] = None, - **kwargs - ) -> AsyncIterable["_models.RecordSetListResult"]: + **kwargs: Any + ) -> AsyncIterable["_models.RecordSet"]: """Lists the record sets of a specified type in a DNS zone. - :param resource_group_name: The name of the resource group. + :param resource_group_name: The name of the resource group. Required. :type resource_group_name: str - :param zone_name: The name of the DNS zone (without a terminating dot). + :param zone_name: The name of the DNS zone (without a terminating dot). Required. :type zone_name: str - :param record_type: The type of record sets to enumerate. + :param record_type: The type of record sets to enumerate. Known values are: "A", "AAAA", "CAA", + "CNAME", "MX", "NS", "PTR", "SOA", "SRV", and "TXT". Required. :type record_type: str or ~azure.mgmt.dns.v2018_05_01.models.RecordType :param top: The maximum number of record sets to return. If not specified, returns up to 100 - record sets. + record sets. Default value is None. :type top: int :param recordsetnamesuffix: The suffix label of the record set name that has to be used to filter the record set enumerations. If this parameter is specified, Enumeration will return - only records that end with .:code:``. + only records that end with .:code:``. Default value is None. :type recordsetnamesuffix: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either RecordSetListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.dns.v2018_05_01.models.RecordSetListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either RecordSet or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.dns.v2018_05_01.models.RecordSet] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RecordSetListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2018-05-01"] = kwargs.pop("api_version", _params.pop("api-version", "2018-05-01")) + cls: ClsType[_models.RecordSetListResult] = kwargs.pop("cls", None) + 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 = "2018-05-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_by_type.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), - 'zoneName': self._serialize.url("zone_name", zone_name, 'str'), - 'recordType': self._serialize.url("record_type", record_type, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - if top is not None: - query_parameters['$top'] = self._serialize.query("top", top, 'int') - if recordsetnamesuffix is not None: - query_parameters['$recordsetnamesuffix'] = self._serialize.query("recordsetnamesuffix", recordsetnamesuffix, 'str') - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_by_type_request( + resource_group_name=resource_group_name, + zone_name=zone_name, + record_type=record_type, + subscription_id=self._config.subscription_id, + top=top, + recordsetnamesuffix=recordsetnamesuffix, + api_version=api_version, + template_url=self.list_by_type.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('RecordSetListResult', pipeline_response) + deserialized = self._deserialize("RecordSetListResult", pipeline_response) list_of_elem = deserialized.value if cls: - list_of_elem = cls(list_of_elem) + list_of_elem = cls(list_of_elem) # type: ignore return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: @@ -437,85 +701,101 @@ async def get_next(next_link=None): return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list_by_type.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}/{recordType}'} # type: ignore + return AsyncItemPaged(get_next, extract_data) + + list_by_type.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}/{recordType}" + } + @distributed_trace def list_by_dns_zone( self, resource_group_name: str, zone_name: str, top: Optional[int] = None, recordsetnamesuffix: Optional[str] = None, - **kwargs - ) -> AsyncIterable["_models.RecordSetListResult"]: + **kwargs: Any + ) -> AsyncIterable["_models.RecordSet"]: """Lists all record sets in a DNS zone. - :param resource_group_name: The name of the resource group. + :param resource_group_name: The name of the resource group. Required. :type resource_group_name: str - :param zone_name: The name of the DNS zone (without a terminating dot). + :param zone_name: The name of the DNS zone (without a terminating dot). Required. :type zone_name: str :param top: The maximum number of record sets to return. If not specified, returns up to 100 - record sets. + record sets. Default value is None. :type top: int :param recordsetnamesuffix: The suffix label of the record set name that has to be used to filter the record set enumerations. If this parameter is specified, Enumeration will return - only records that end with .:code:``. + only records that end with .:code:``. Default value is None. :type recordsetnamesuffix: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either RecordSetListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.dns.v2018_05_01.models.RecordSetListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either RecordSet or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.dns.v2018_05_01.models.RecordSet] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RecordSetListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2018-05-01"] = kwargs.pop("api_version", _params.pop("api-version", "2018-05-01")) + cls: ClsType[_models.RecordSetListResult] = kwargs.pop("cls", None) + 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 = "2018-05-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_by_dns_zone.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), - 'zoneName': self._serialize.url("zone_name", zone_name, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - if top is not None: - query_parameters['$top'] = self._serialize.query("top", top, 'int') - if recordsetnamesuffix is not None: - query_parameters['$recordsetnamesuffix'] = self._serialize.query("recordsetnamesuffix", recordsetnamesuffix, 'str') - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_by_dns_zone_request( + resource_group_name=resource_group_name, + zone_name=zone_name, + subscription_id=self._config.subscription_id, + top=top, + recordsetnamesuffix=recordsetnamesuffix, + api_version=api_version, + template_url=self.list_by_dns_zone.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('RecordSetListResult', pipeline_response) + deserialized = self._deserialize("RecordSetListResult", pipeline_response) list_of_elem = deserialized.value if cls: - list_of_elem = cls(list_of_elem) + list_of_elem = cls(list_of_elem) # type: ignore return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: @@ -524,85 +804,101 @@ async def get_next(next_link=None): return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list_by_dns_zone.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}/recordsets'} # type: ignore + return AsyncItemPaged(get_next, extract_data) + list_by_dns_zone.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}/recordsets" + } + + @distributed_trace def list_all_by_dns_zone( self, resource_group_name: str, zone_name: str, top: Optional[int] = None, record_set_name_suffix: Optional[str] = None, - **kwargs - ) -> AsyncIterable["_models.RecordSetListResult"]: + **kwargs: Any + ) -> AsyncIterable["_models.RecordSet"]: """Lists all record sets in a DNS zone. - :param resource_group_name: The name of the resource group. + :param resource_group_name: The name of the resource group. Required. :type resource_group_name: str - :param zone_name: The name of the DNS zone (without a terminating dot). + :param zone_name: The name of the DNS zone (without a terminating dot). Required. :type zone_name: str :param top: The maximum number of record sets to return. If not specified, returns up to 100 - record sets. + record sets. Default value is None. :type top: int :param record_set_name_suffix: The suffix label of the record set name that has to be used to filter the record set enumerations. If this parameter is specified, Enumeration will return - only records that end with .:code:``. + only records that end with .:code:``. Default value is None. :type record_set_name_suffix: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either RecordSetListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.dns.v2018_05_01.models.RecordSetListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either RecordSet or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.dns.v2018_05_01.models.RecordSet] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RecordSetListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2018-05-01"] = kwargs.pop("api_version", _params.pop("api-version", "2018-05-01")) + cls: ClsType[_models.RecordSetListResult] = kwargs.pop("cls", None) + 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 = "2018-05-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_all_by_dns_zone.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), - 'zoneName': self._serialize.url("zone_name", zone_name, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - if top is not None: - query_parameters['$top'] = self._serialize.query("top", top, 'int') - if record_set_name_suffix is not None: - query_parameters['$recordsetnamesuffix'] = self._serialize.query("record_set_name_suffix", record_set_name_suffix, 'str') - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_all_by_dns_zone_request( + resource_group_name=resource_group_name, + zone_name=zone_name, + subscription_id=self._config.subscription_id, + top=top, + record_set_name_suffix=record_set_name_suffix, + api_version=api_version, + template_url=self.list_all_by_dns_zone.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('RecordSetListResult', pipeline_response) + deserialized = self._deserialize("RecordSetListResult", pipeline_response) list_of_elem = deserialized.value if cls: - list_of_elem = cls(list_of_elem) + list_of_elem = cls(list_of_elem) # type: ignore return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: @@ -611,7 +907,8 @@ async def get_next(next_link=None): return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list_all_by_dns_zone.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}/all'} # type: ignore + return AsyncItemPaged(get_next, extract_data) + + list_all_by_dns_zone.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}/all" + } diff --git a/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_05_01/aio/operations/_zones_operations.py b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_05_01/aio/operations/_zones_operations.py index 0a7d6022a51c..3f96b9d1390d 100644 --- a/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_05_01/aio/operations/_zones_operations.py +++ b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_05_01/aio/operations/_zones_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,109 +6,217 @@ # 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, Generic, Optional, TypeVar, Union -import warnings +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, HttpRequest +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 - -T = TypeVar('T') +from ..._vendor import _convert_request +from ...operations._zones_operations import ( + build_create_or_update_request, + build_delete_request, + build_get_request, + build_list_by_resource_group_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 ZonesOperations: - """ZonesOperations 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 ZonesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.dns.v2018_05_01.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.dns.v2018_05_01.aio.DnsManagementClient`'s + :attr:`zones` 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") + @overload async def create_or_update( self, resource_group_name: str, zone_name: str, - parameters: "_models.Zone", + parameters: _models.Zone, if_match: Optional[str] = None, if_none_match: Optional[str] = None, - **kwargs - ) -> "_models.Zone": + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Zone: """Creates or updates a DNS zone. Does not modify DNS records within the zone. - :param resource_group_name: The name of the resource group. + :param resource_group_name: The name of the resource group. Required. :type resource_group_name: str - :param zone_name: The name of the DNS zone (without a terminating dot). + :param zone_name: The name of the DNS zone (without a terminating dot). Required. :type zone_name: str - :param parameters: Parameters supplied to the CreateOrUpdate operation. + :param parameters: Parameters supplied to the CreateOrUpdate operation. Required. :type parameters: ~azure.mgmt.dns.v2018_05_01.models.Zone :param if_match: The etag of the DNS zone. Omit this value to always overwrite the current zone. Specify the last-seen etag value to prevent accidentally overwriting any concurrent - changes. + changes. Default value is None. + :type if_match: str + :param if_none_match: Set to '*' to allow a new DNS zone to be created, but to prevent updating + an existing zone. 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: Zone or the result of cls(response) + :rtype: ~azure.mgmt.dns.v2018_05_01.models.Zone + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_or_update( + self, + resource_group_name: str, + zone_name: str, + parameters: IO, + if_match: Optional[str] = None, + if_none_match: Optional[str] = None, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Zone: + """Creates or updates a DNS zone. Does not modify DNS records within the zone. + + :param resource_group_name: The name of the resource group. Required. + :type resource_group_name: str + :param zone_name: The name of the DNS zone (without a terminating dot). Required. + :type zone_name: str + :param parameters: Parameters supplied to the CreateOrUpdate operation. Required. + :type parameters: IO + :param if_match: The etag of the DNS zone. Omit this value to always overwrite the current + zone. Specify the last-seen etag value to prevent accidentally overwriting any concurrent + changes. Default value is None. + :type if_match: str + :param if_none_match: Set to '*' to allow a new DNS zone to be created, but to prevent updating + an existing zone. 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: Zone or the result of cls(response) + :rtype: ~azure.mgmt.dns.v2018_05_01.models.Zone + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create_or_update( + self, + resource_group_name: str, + zone_name: str, + parameters: Union[_models.Zone, IO], + if_match: Optional[str] = None, + if_none_match: Optional[str] = None, + **kwargs: Any + ) -> _models.Zone: + """Creates or updates a DNS zone. Does not modify DNS records within the zone. + + :param resource_group_name: The name of the resource group. Required. + :type resource_group_name: str + :param zone_name: The name of the DNS zone (without a terminating dot). Required. + :type zone_name: str + :param parameters: Parameters supplied to the CreateOrUpdate operation. Is either a Zone type + or a IO type. Required. + :type parameters: ~azure.mgmt.dns.v2018_05_01.models.Zone or IO + :param if_match: The etag of the DNS zone. Omit this value to always overwrite the current + zone. Specify the last-seen etag value to prevent accidentally overwriting any concurrent + changes. Default value is None. :type if_match: str :param if_none_match: Set to '*' to allow a new DNS zone to be created, but to prevent updating - an existing zone. Other values will be ignored. + an existing zone. 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: Zone, or the result of cls(response) + :return: Zone or the result of cls(response) :rtype: ~azure.mgmt.dns.v2018_05_01.models.Zone - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Zone"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-05-01" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.create_or_update.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), - 'zoneName': self._serialize.url("zone_name", zone_name, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - if if_match is not None: - header_parameters['If-Match'] = self._serialize.header("if_match", if_match, 'str') - if if_none_match is not None: - header_parameters['If-None-Match'] = self._serialize.header("if_none_match", if_none_match, 'str') - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(parameters, 'Zone') - body_content_kwargs['content'] = body_content - request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + 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: Literal["2018-05-01"] = kwargs.pop("api_version", _params.pop("api-version", "2018-05-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.Zone] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "Zone") + + request = build_create_or_update_request( + resource_group_name=resource_group_name, + zone_name=zone_name, + subscription_id=self._config.subscription_id, + if_match=if_match, + if_none_match=if_none_match, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create_or_update.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response if response.status_code not in [200, 201]: @@ -115,53 +224,54 @@ async def create_or_update( raise HttpResponseError(response=response, error_format=ARMErrorFormat) if response.status_code == 200: - deserialized = self._deserialize('Zone', pipeline_response) + deserialized = self._deserialize("Zone", pipeline_response) if response.status_code == 201: - deserialized = self._deserialize('Zone', pipeline_response) + deserialized = self._deserialize("Zone", pipeline_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}'} # type: ignore + return deserialized # type: ignore - async def _delete_initial( - self, - resource_group_name: str, - zone_name: str, - if_match: Optional[str] = None, - **kwargs + create_or_update.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}" + } + + async def _delete_initial( # pylint: disable=inconsistent-return-statements + self, resource_group_name: str, zone_name: str, if_match: Optional[str] = None, **kwargs: Any ) -> None: - cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-05-01" - accept = "application/json" - - # Construct URL - url = self._delete_initial.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), - 'zoneName': self._serialize.url("zone_name", zone_name, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2018-05-01"] = kwargs.pop("api_version", _params.pop("api-version", "2018-05-01")) + cls: ClsType[None] = kwargs.pop("cls", None) + + request = build_delete_request( + resource_group_name=resource_group_name, + zone_name=zone_name, + subscription_id=self._config.subscription_id, + if_match=if_match, + api_version=api_version, + template_url=self._delete_initial.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) - # Construct headers - header_parameters = {} # type: Dict[str, Any] - if if_match is not None: - header_parameters['If-Match'] = self._serialize.header("if_match", if_match, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.delete(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: @@ -171,272 +281,371 @@ async def _delete_initial( if cls: return cls(pipeline_response, None, {}) - _delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}'} # type: ignore + _delete_initial.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}" + } + @distributed_trace_async async def begin_delete( - self, - resource_group_name: str, - zone_name: str, - if_match: Optional[str] = None, - **kwargs + self, resource_group_name: str, zone_name: str, if_match: Optional[str] = None, **kwargs: Any ) -> AsyncLROPoller[None]: """Deletes a DNS zone. WARNING: All DNS records in the zone will also be deleted. This operation cannot be undone. - :param resource_group_name: The name of the resource group. + :param resource_group_name: The name of the resource group. Required. :type resource_group_name: str - :param zone_name: The name of the DNS zone (without a terminating dot). + :param zone_name: The name of the DNS zone (without a terminating dot). Required. :type zone_name: str :param if_match: The etag of the DNS zone. Omit this value to always delete the current zone. Specify the last-seen etag value to prevent accidentally deleting any concurrent changes. + Default value is None. :type if_match: 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: Pass in True if you'd like the AsyncARMPolling polling method, - False for no polling, or your own initialized polling object for a personal polling strategy. + :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. + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[None] :raises ~azure.core.exceptions.HttpResponseError: """ - polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType[None] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2018-05-01"] = kwargs.pop("api_version", _params.pop("api-version", "2018-05-01")) + cls: ClsType[None] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) if cont_token is None: - raw_result = await self._delete_initial( + raw_result = await self._delete_initial( # type: ignore resource_group_name=resource_group_name, zone_name=zone_name, if_match=if_match, - cls=lambda x,y,z: x, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) + kwargs.pop("error_map", None) - kwargs.pop('error_map', None) - kwargs.pop('content_type', 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, {}) - path_format_arguments = { - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), - 'zoneName': self._serialize.url("zone_name", zone_name, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), - } - - if polling is True: polling_method = AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) - elif polling is False: polling_method = AsyncNoPolling() - else: polling_method = polling + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - else: - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}'} # type: ignore + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - async def get( - self, - resource_group_name: str, - zone_name: str, - **kwargs - ) -> "_models.Zone": + begin_delete.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}" + } + + @distributed_trace_async + async def get(self, resource_group_name: str, zone_name: str, **kwargs: Any) -> _models.Zone: """Gets a DNS zone. Retrieves the zone properties, but not the record sets within the zone. - :param resource_group_name: The name of the resource group. + :param resource_group_name: The name of the resource group. Required. :type resource_group_name: str - :param zone_name: The name of the DNS zone (without a terminating dot). + :param zone_name: The name of the DNS zone (without a terminating dot). Required. :type zone_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: Zone, or the result of cls(response) + :return: Zone or the result of cls(response) :rtype: ~azure.mgmt.dns.v2018_05_01.models.Zone - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Zone"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-05-01" - accept = "application/json" - - # Construct URL - url = self.get.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), - 'zoneName': self._serialize.url("zone_name", zone_name, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2018-05-01"] = kwargs.pop("api_version", _params.pop("api-version", "2018-05-01")) + cls: ClsType[_models.Zone] = kwargs.pop("cls", None) + + request = build_get_request( + resource_group_name=resource_group_name, + zone_name=zone_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('Zone', pipeline_response) + deserialized = self._deserialize("Zone", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}'} # type: ignore + get.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}" + } + + @overload async def update( self, resource_group_name: str, zone_name: str, - parameters: "_models.ZoneUpdate", + parameters: _models.ZoneUpdate, if_match: Optional[str] = None, - **kwargs - ) -> "_models.Zone": + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Zone: """Updates a DNS zone. Does not modify DNS records within the zone. - :param resource_group_name: The name of the resource group. + :param resource_group_name: The name of the resource group. Required. :type resource_group_name: str - :param zone_name: The name of the DNS zone (without a terminating dot). + :param zone_name: The name of the DNS zone (without a terminating dot). Required. :type zone_name: str - :param parameters: Parameters supplied to the Update operation. + :param parameters: Parameters supplied to the Update operation. Required. :type parameters: ~azure.mgmt.dns.v2018_05_01.models.ZoneUpdate :param if_match: The etag of the DNS zone. Omit this value to always overwrite the current zone. Specify the last-seen etag value to prevent accidentally overwriting any concurrent - changes. + changes. 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: Zone or the result of cls(response) + :rtype: ~azure.mgmt.dns.v2018_05_01.models.Zone + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def update( + self, + resource_group_name: str, + zone_name: str, + parameters: IO, + if_match: Optional[str] = None, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Zone: + """Updates a DNS zone. Does not modify DNS records within the zone. + + :param resource_group_name: The name of the resource group. Required. + :type resource_group_name: str + :param zone_name: The name of the DNS zone (without a terminating dot). Required. + :type zone_name: str + :param parameters: Parameters supplied to the Update operation. Required. + :type parameters: IO + :param if_match: The etag of the DNS zone. Omit this value to always overwrite the current + zone. Specify the last-seen etag value to prevent accidentally overwriting any concurrent + changes. 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: Zone, or the result of cls(response) + :return: Zone or the result of cls(response) :rtype: ~azure.mgmt.dns.v2018_05_01.models.Zone - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def update( + self, + resource_group_name: str, + zone_name: str, + parameters: Union[_models.ZoneUpdate, IO], + if_match: Optional[str] = None, + **kwargs: Any + ) -> _models.Zone: + """Updates a DNS zone. Does not modify DNS records within the zone. + + :param resource_group_name: The name of the resource group. Required. + :type resource_group_name: str + :param zone_name: The name of the DNS zone (without a terminating dot). Required. + :type zone_name: str + :param parameters: Parameters supplied to the Update operation. Is either a ZoneUpdate type or + a IO type. Required. + :type parameters: ~azure.mgmt.dns.v2018_05_01.models.ZoneUpdate or IO + :param if_match: The etag of the DNS zone. Omit this value to always overwrite the current + zone. Specify the last-seen etag value to prevent accidentally overwriting any concurrent + changes. 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: Zone or the result of cls(response) + :rtype: ~azure.mgmt.dns.v2018_05_01.models.Zone + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Zone"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-05-01" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.update.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), - 'zoneName': self._serialize.url("zone_name", zone_name, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - if if_match is not None: - header_parameters['If-Match'] = self._serialize.header("if_match", if_match, 'str') - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(parameters, 'ZoneUpdate') - body_content_kwargs['content'] = body_content - request = self._client.patch(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + 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: Literal["2018-05-01"] = kwargs.pop("api_version", _params.pop("api-version", "2018-05-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.Zone] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "ZoneUpdate") + + request = build_update_request( + resource_group_name=resource_group_name, + zone_name=zone_name, + subscription_id=self._config.subscription_id, + if_match=if_match, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.update.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = 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('Zone', pipeline_response) + deserialized = self._deserialize("Zone", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}'} # type: ignore + update.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}" + } + + @distributed_trace def list_by_resource_group( - self, - resource_group_name: str, - top: Optional[int] = None, - **kwargs - ) -> AsyncIterable["_models.ZoneListResult"]: + self, resource_group_name: str, top: Optional[int] = None, **kwargs: Any + ) -> AsyncIterable["_models.Zone"]: """Lists the DNS zones within a resource group. - :param resource_group_name: The name of the resource group. + :param resource_group_name: The name of the resource group. Required. :type resource_group_name: str :param top: The maximum number of record sets to return. If not specified, returns up to 100 - record sets. + record sets. Default value is None. :type top: int :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either ZoneListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.dns.v2018_05_01.models.ZoneListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either Zone or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.dns.v2018_05_01.models.Zone] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.ZoneListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2018-05-01"] = kwargs.pop("api_version", _params.pop("api-version", "2018-05-01")) + cls: ClsType[_models.ZoneListResult] = kwargs.pop("cls", None) + 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 = "2018-05-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_by_resource_group.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - if top is not None: - query_parameters['$top'] = self._serialize.query("top", top, 'int') - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_by_resource_group_request( + resource_group_name=resource_group_name, + subscription_id=self._config.subscription_id, + top=top, + api_version=api_version, + template_url=self.list_by_resource_group.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('ZoneListResult', pipeline_response) + deserialized = self._deserialize("ZoneListResult", pipeline_response) list_of_elem = deserialized.value if cls: - list_of_elem = cls(list_of_elem) + list_of_elem = cls(list_of_elem) # type: ignore return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: @@ -445,70 +654,83 @@ async def get_next(next_link=None): return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list_by_resource_group.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones'} # type: ignore + return AsyncItemPaged(get_next, extract_data) - def list( - self, - top: Optional[int] = None, - **kwargs - ) -> AsyncIterable["_models.ZoneListResult"]: + list_by_resource_group.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones" + } + + @distributed_trace + def list(self, top: Optional[int] = None, **kwargs: Any) -> AsyncIterable["_models.Zone"]: """Lists the DNS zones in all resource groups in a subscription. :param top: The maximum number of DNS zones to return. If not specified, returns up to 100 - zones. + zones. Default value is None. :type top: int :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either ZoneListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.dns.v2018_05_01.models.ZoneListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either Zone or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.dns.v2018_05_01.models.Zone] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.ZoneListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2018-05-01"] = kwargs.pop("api_version", _params.pop("api-version", "2018-05-01")) + cls: ClsType[_models.ZoneListResult] = kwargs.pop("cls", None) + 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 = "2018-05-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list.metadata['url'] # type: ignore - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - if top is not None: - query_parameters['$top'] = self._serialize.query("top", top, 'int') - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_request( + subscription_id=self._config.subscription_id, + top=top, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('ZoneListResult', pipeline_response) + deserialized = self._deserialize("ZoneListResult", pipeline_response) list_of_elem = deserialized.value if cls: - list_of_elem = cls(list_of_elem) + list_of_elem = cls(list_of_elem) # type: ignore return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: @@ -517,7 +739,6 @@ async def get_next(next_link=None): return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Network/dnszones'} # type: ignore + return AsyncItemPaged(get_next, extract_data) + + list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Network/dnszones"} diff --git a/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_05_01/models/__init__.py b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_05_01/models/__init__.py index ecceb3cb0c3b..1182e1bcbf84 100644 --- a/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_05_01/models/__init__.py +++ b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_05_01/models/__init__.py @@ -6,81 +6,60 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -try: - from ._models_py3 import ARecord - from ._models_py3 import AaaaRecord - from ._models_py3 import CaaRecord - from ._models_py3 import CloudErrorBody - from ._models_py3 import CnameRecord - from ._models_py3 import DnsResourceReference - from ._models_py3 import DnsResourceReferenceRequest - from ._models_py3 import DnsResourceReferenceResult - from ._models_py3 import MxRecord - from ._models_py3 import NsRecord - from ._models_py3 import PtrRecord - from ._models_py3 import RecordSet - from ._models_py3 import RecordSetListResult - from ._models_py3 import RecordSetUpdateParameters - from ._models_py3 import Resource - from ._models_py3 import SoaRecord - from ._models_py3 import SrvRecord - from ._models_py3 import SubResource - from ._models_py3 import TxtRecord - from ._models_py3 import Zone - from ._models_py3 import ZoneListResult - from ._models_py3 import ZoneUpdate -except (SyntaxError, ImportError): - from ._models import ARecord # type: ignore - from ._models import AaaaRecord # type: ignore - from ._models import CaaRecord # type: ignore - from ._models import CloudErrorBody # type: ignore - from ._models import CnameRecord # type: ignore - from ._models import DnsResourceReference # type: ignore - from ._models import DnsResourceReferenceRequest # type: ignore - from ._models import DnsResourceReferenceResult # type: ignore - from ._models import MxRecord # type: ignore - from ._models import NsRecord # type: ignore - from ._models import PtrRecord # type: ignore - from ._models import RecordSet # type: ignore - from ._models import RecordSetListResult # type: ignore - from ._models import RecordSetUpdateParameters # type: ignore - from ._models import Resource # type: ignore - from ._models import SoaRecord # type: ignore - from ._models import SrvRecord # type: ignore - from ._models import SubResource # type: ignore - from ._models import TxtRecord # type: ignore - from ._models import Zone # type: ignore - from ._models import ZoneListResult # type: ignore - from ._models import ZoneUpdate # type: ignore +from ._models_py3 import ARecord +from ._models_py3 import AaaaRecord +from ._models_py3 import CaaRecord +from ._models_py3 import CloudErrorBody +from ._models_py3 import CnameRecord +from ._models_py3 import DnsResourceReference +from ._models_py3 import DnsResourceReferenceRequest +from ._models_py3 import DnsResourceReferenceResult +from ._models_py3 import MxRecord +from ._models_py3 import NsRecord +from ._models_py3 import PtrRecord +from ._models_py3 import RecordSet +from ._models_py3 import RecordSetListResult +from ._models_py3 import RecordSetUpdateParameters +from ._models_py3 import Resource +from ._models_py3 import SoaRecord +from ._models_py3 import SrvRecord +from ._models_py3 import SubResource +from ._models_py3 import TxtRecord +from ._models_py3 import Zone +from ._models_py3 import ZoneListResult +from ._models_py3 import ZoneUpdate -from ._dns_management_client_enums import ( - RecordType, - ZoneType, -) +from ._dns_management_client_enums import RecordType +from ._dns_management_client_enums import ZoneType +from ._patch import __all__ as _patch_all +from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import patch_sdk as _patch_sdk __all__ = [ - 'ARecord', - 'AaaaRecord', - 'CaaRecord', - 'CloudErrorBody', - 'CnameRecord', - 'DnsResourceReference', - 'DnsResourceReferenceRequest', - 'DnsResourceReferenceResult', - 'MxRecord', - 'NsRecord', - 'PtrRecord', - 'RecordSet', - 'RecordSetListResult', - 'RecordSetUpdateParameters', - 'Resource', - 'SoaRecord', - 'SrvRecord', - 'SubResource', - 'TxtRecord', - 'Zone', - 'ZoneListResult', - 'ZoneUpdate', - 'RecordType', - 'ZoneType', + "ARecord", + "AaaaRecord", + "CaaRecord", + "CloudErrorBody", + "CnameRecord", + "DnsResourceReference", + "DnsResourceReferenceRequest", + "DnsResourceReferenceResult", + "MxRecord", + "NsRecord", + "PtrRecord", + "RecordSet", + "RecordSetListResult", + "RecordSetUpdateParameters", + "Resource", + "SoaRecord", + "SrvRecord", + "SubResource", + "TxtRecord", + "Zone", + "ZoneListResult", + "ZoneUpdate", + "RecordType", + "ZoneType", ] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_05_01/models/_dns_management_client_enums.py b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_05_01/models/_dns_management_client_enums.py index f2abeece2155..ca561301a0f6 100644 --- a/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_05_01/models/_dns_management_client_enums.py +++ b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_05_01/models/_dns_management_client_enums.py @@ -6,27 +6,12 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from enum import Enum, EnumMeta -from six import with_metaclass +from enum import Enum +from azure.core import CaseInsensitiveEnumMeta -class _CaseInsensitiveEnumMeta(EnumMeta): - def __getitem__(self, name): - return super().__getitem__(name.upper()) - def __getattr__(cls, name): - """Return the enum member matching `name` - We use __getattr__ instead of descriptors or inserting into the enum - class' __dict__ in order to support `name` and `value` being both - properties for enum members (which live in the class' __dict__) and - enum members themselves. - """ - try: - return cls._member_map_[name.upper()] - except KeyError: - raise AttributeError(name) - - -class RecordType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): +class RecordType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """RecordType.""" A = "A" AAAA = "AAAA" @@ -39,9 +24,9 @@ class RecordType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): SRV = "SRV" TXT = "TXT" -class ZoneType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """The type of this DNS zone (Public or Private). - """ + +class ZoneType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The type of this DNS zone (Public or Private).""" PUBLIC = "Public" PRIVATE = "Private" diff --git a/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_05_01/models/_models.py b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_05_01/models/_models.py deleted file mode 100644 index eec9fa62b048..000000000000 --- a/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_05_01/models/_models.py +++ /dev/null @@ -1,694 +0,0 @@ -# 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. -# -------------------------------------------------------------------------- - -import msrest.serialization - - -class AaaaRecord(msrest.serialization.Model): - """An AAAA record. - - :param ipv6_address: The IPv6 address of this AAAA record. - :type ipv6_address: str - """ - - _attribute_map = { - 'ipv6_address': {'key': 'ipv6Address', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(AaaaRecord, self).__init__(**kwargs) - self.ipv6_address = kwargs.get('ipv6_address', None) - - -class ARecord(msrest.serialization.Model): - """An A record. - - :param ipv4_address: The IPv4 address of this A record. - :type ipv4_address: str - """ - - _attribute_map = { - 'ipv4_address': {'key': 'ipv4Address', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(ARecord, self).__init__(**kwargs) - self.ipv4_address = kwargs.get('ipv4_address', None) - - -class CaaRecord(msrest.serialization.Model): - """A CAA record. - - :param flags: The flags for this CAA record as an integer between 0 and 255. - :type flags: int - :param tag: The tag for this CAA record. - :type tag: str - :param value: The value for this CAA record. - :type value: str - """ - - _attribute_map = { - 'flags': {'key': 'flags', 'type': 'int'}, - 'tag': {'key': 'tag', 'type': 'str'}, - 'value': {'key': 'value', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(CaaRecord, self).__init__(**kwargs) - self.flags = kwargs.get('flags', None) - self.tag = kwargs.get('tag', None) - self.value = kwargs.get('value', None) - - -class CloudErrorBody(msrest.serialization.Model): - """An error response from the service. - - :param code: An identifier for the error. Codes are invariant and are intended to be consumed - programmatically. - :type code: str - :param message: A message describing the error, intended to be suitable for display in a user - interface. - :type message: str - :param target: The target of the particular error. For example, the name of the property in - error. - :type target: str - :param details: A list of additional details about the error. - :type details: list[~azure.mgmt.dns.v2018_05_01.models.CloudErrorBody] - """ - - _attribute_map = { - 'code': {'key': 'code', 'type': 'str'}, - 'message': {'key': 'message', 'type': 'str'}, - 'target': {'key': 'target', 'type': 'str'}, - 'details': {'key': 'details', 'type': '[CloudErrorBody]'}, - } - - def __init__( - self, - **kwargs - ): - super(CloudErrorBody, self).__init__(**kwargs) - self.code = kwargs.get('code', None) - self.message = kwargs.get('message', None) - self.target = kwargs.get('target', None) - self.details = kwargs.get('details', None) - - -class CnameRecord(msrest.serialization.Model): - """A CNAME record. - - :param cname: The canonical name for this CNAME record. - :type cname: str - """ - - _attribute_map = { - 'cname': {'key': 'cname', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(CnameRecord, self).__init__(**kwargs) - self.cname = kwargs.get('cname', None) - - -class DnsResourceReference(msrest.serialization.Model): - """Represents a single Azure resource and its referencing DNS records. - - :param dns_resources: A list of dns Records. - :type dns_resources: list[~azure.mgmt.dns.v2018_05_01.models.SubResource] - :param target_resource: A reference to an azure resource from where the dns resource value is - taken. - :type target_resource: ~azure.mgmt.dns.v2018_05_01.models.SubResource - """ - - _attribute_map = { - 'dns_resources': {'key': 'dnsResources', 'type': '[SubResource]'}, - 'target_resource': {'key': 'targetResource', 'type': 'SubResource'}, - } - - def __init__( - self, - **kwargs - ): - super(DnsResourceReference, self).__init__(**kwargs) - self.dns_resources = kwargs.get('dns_resources', None) - self.target_resource = kwargs.get('target_resource', None) - - -class DnsResourceReferenceRequest(msrest.serialization.Model): - """Represents the properties of the Dns Resource Reference Request. - - :param target_resources: A list of references to azure resources for which referencing dns - records need to be queried. - :type target_resources: list[~azure.mgmt.dns.v2018_05_01.models.SubResource] - """ - - _attribute_map = { - 'target_resources': {'key': 'properties.targetResources', 'type': '[SubResource]'}, - } - - def __init__( - self, - **kwargs - ): - super(DnsResourceReferenceRequest, self).__init__(**kwargs) - self.target_resources = kwargs.get('target_resources', None) - - -class DnsResourceReferenceResult(msrest.serialization.Model): - """Represents the properties of the Dns Resource Reference Result. - - :param dns_resource_references: The result of dns resource reference request. A list of dns - resource references for each of the azure resource in the request. - :type dns_resource_references: list[~azure.mgmt.dns.v2018_05_01.models.DnsResourceReference] - """ - - _attribute_map = { - 'dns_resource_references': {'key': 'properties.dnsResourceReferences', 'type': '[DnsResourceReference]'}, - } - - def __init__( - self, - **kwargs - ): - super(DnsResourceReferenceResult, self).__init__(**kwargs) - self.dns_resource_references = kwargs.get('dns_resource_references', None) - - -class MxRecord(msrest.serialization.Model): - """An MX record. - - :param preference: The preference value for this MX record. - :type preference: int - :param exchange: The domain name of the mail host for this MX record. - :type exchange: str - """ - - _attribute_map = { - 'preference': {'key': 'preference', 'type': 'int'}, - 'exchange': {'key': 'exchange', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(MxRecord, self).__init__(**kwargs) - self.preference = kwargs.get('preference', None) - self.exchange = kwargs.get('exchange', None) - - -class NsRecord(msrest.serialization.Model): - """An NS record. - - :param nsdname: The name server name for this NS record. - :type nsdname: str - """ - - _attribute_map = { - 'nsdname': {'key': 'nsdname', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(NsRecord, self).__init__(**kwargs) - self.nsdname = kwargs.get('nsdname', None) - - -class PtrRecord(msrest.serialization.Model): - """A PTR record. - - :param ptrdname: The PTR target domain name for this PTR record. - :type ptrdname: str - """ - - _attribute_map = { - 'ptrdname': {'key': 'ptrdname', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(PtrRecord, self).__init__(**kwargs) - self.ptrdname = kwargs.get('ptrdname', None) - - -class RecordSet(msrest.serialization.Model): - """Describes a DNS record set (a collection of DNS records with the same name and type). - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: The ID of the record set. - :vartype id: str - :ivar name: The name of the record set. - :vartype name: str - :ivar type: The type of the record set. - :vartype type: str - :param etag: The etag of the record set. - :type etag: str - :param metadata: The metadata attached to the record set. - :type metadata: dict[str, str] - :param ttl: The TTL (time-to-live) of the records in the record set. - :type ttl: long - :ivar fqdn: Fully qualified domain name of the record set. - :vartype fqdn: str - :ivar provisioning_state: provisioning State of the record set. - :vartype provisioning_state: str - :param target_resource: A reference to an azure resource from where the dns resource value is - taken. - :type target_resource: ~azure.mgmt.dns.v2018_05_01.models.SubResource - :param a_records: The list of A records in the record set. - :type a_records: list[~azure.mgmt.dns.v2018_05_01.models.ARecord] - :param aaaa_records: The list of AAAA records in the record set. - :type aaaa_records: list[~azure.mgmt.dns.v2018_05_01.models.AaaaRecord] - :param mx_records: The list of MX records in the record set. - :type mx_records: list[~azure.mgmt.dns.v2018_05_01.models.MxRecord] - :param ns_records: The list of NS records in the record set. - :type ns_records: list[~azure.mgmt.dns.v2018_05_01.models.NsRecord] - :param ptr_records: The list of PTR records in the record set. - :type ptr_records: list[~azure.mgmt.dns.v2018_05_01.models.PtrRecord] - :param srv_records: The list of SRV records in the record set. - :type srv_records: list[~azure.mgmt.dns.v2018_05_01.models.SrvRecord] - :param txt_records: The list of TXT records in the record set. - :type txt_records: list[~azure.mgmt.dns.v2018_05_01.models.TxtRecord] - :param cname_record: The CNAME record in the record set. - :type cname_record: ~azure.mgmt.dns.v2018_05_01.models.CnameRecord - :param soa_record: The SOA record in the record set. - :type soa_record: ~azure.mgmt.dns.v2018_05_01.models.SoaRecord - :param caa_records: The list of CAA records in the record set. - :type caa_records: list[~azure.mgmt.dns.v2018_05_01.models.CaaRecord] - """ - - _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'fqdn': {'readonly': True}, - 'provisioning_state': {'readonly': True}, - } - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'etag': {'key': 'etag', 'type': 'str'}, - 'metadata': {'key': 'properties.metadata', 'type': '{str}'}, - 'ttl': {'key': 'properties.TTL', 'type': 'long'}, - 'fqdn': {'key': 'properties.fqdn', 'type': 'str'}, - 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, - 'target_resource': {'key': 'properties.targetResource', 'type': 'SubResource'}, - 'a_records': {'key': 'properties.ARecords', 'type': '[ARecord]'}, - 'aaaa_records': {'key': 'properties.AAAARecords', 'type': '[AaaaRecord]'}, - 'mx_records': {'key': 'properties.MXRecords', 'type': '[MxRecord]'}, - 'ns_records': {'key': 'properties.NSRecords', 'type': '[NsRecord]'}, - 'ptr_records': {'key': 'properties.PTRRecords', 'type': '[PtrRecord]'}, - 'srv_records': {'key': 'properties.SRVRecords', 'type': '[SrvRecord]'}, - 'txt_records': {'key': 'properties.TXTRecords', 'type': '[TxtRecord]'}, - 'cname_record': {'key': 'properties.CNAMERecord', 'type': 'CnameRecord'}, - 'soa_record': {'key': 'properties.SOARecord', 'type': 'SoaRecord'}, - 'caa_records': {'key': 'properties.caaRecords', 'type': '[CaaRecord]'}, - } - - def __init__( - self, - **kwargs - ): - super(RecordSet, self).__init__(**kwargs) - self.id = None - self.name = None - self.type = None - self.etag = kwargs.get('etag', None) - self.metadata = kwargs.get('metadata', None) - self.ttl = kwargs.get('ttl', None) - self.fqdn = None - self.provisioning_state = None - self.target_resource = kwargs.get('target_resource', None) - self.a_records = kwargs.get('a_records', None) - self.aaaa_records = kwargs.get('aaaa_records', None) - self.mx_records = kwargs.get('mx_records', None) - self.ns_records = kwargs.get('ns_records', None) - self.ptr_records = kwargs.get('ptr_records', None) - self.srv_records = kwargs.get('srv_records', None) - self.txt_records = kwargs.get('txt_records', None) - self.cname_record = kwargs.get('cname_record', None) - self.soa_record = kwargs.get('soa_record', None) - self.caa_records = kwargs.get('caa_records', None) - - -class RecordSetListResult(msrest.serialization.Model): - """The response to a record set List operation. - - Variables are only populated by the server, and will be ignored when sending a request. - - :param value: Information about the record sets in the response. - :type value: list[~azure.mgmt.dns.v2018_05_01.models.RecordSet] - :ivar next_link: The continuation token for the next page of results. - :vartype next_link: str - """ - - _validation = { - 'next_link': {'readonly': True}, - } - - _attribute_map = { - 'value': {'key': 'value', 'type': '[RecordSet]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(RecordSetListResult, self).__init__(**kwargs) - self.value = kwargs.get('value', None) - self.next_link = None - - -class RecordSetUpdateParameters(msrest.serialization.Model): - """Parameters supplied to update a record set. - - :param record_set: Specifies information about the record set being updated. - :type record_set: ~azure.mgmt.dns.v2018_05_01.models.RecordSet - """ - - _attribute_map = { - 'record_set': {'key': 'RecordSet', 'type': 'RecordSet'}, - } - - def __init__( - self, - **kwargs - ): - super(RecordSetUpdateParameters, self).__init__(**kwargs) - self.record_set = kwargs.get('record_set', None) - - -class Resource(msrest.serialization.Model): - """Common properties of an Azure Resource Manager resource. - - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to Azure. - - :ivar id: Resource ID. - :vartype id: str - :ivar name: Resource name. - :vartype name: str - :ivar type: Resource type. - :vartype type: str - :param location: Required. Resource location. - :type location: str - :param tags: A set of tags. Resource tags. - :type tags: dict[str, str] - """ - - _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'location': {'required': True}, - } - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'location': {'key': 'location', 'type': 'str'}, - 'tags': {'key': 'tags', 'type': '{str}'}, - } - - def __init__( - self, - **kwargs - ): - super(Resource, self).__init__(**kwargs) - self.id = None - self.name = None - self.type = None - self.location = kwargs['location'] - self.tags = kwargs.get('tags', None) - - -class SoaRecord(msrest.serialization.Model): - """An SOA record. - - :param host: The domain name of the authoritative name server for this SOA record. - :type host: str - :param email: The email contact for this SOA record. - :type email: str - :param serial_number: The serial number for this SOA record. - :type serial_number: long - :param refresh_time: The refresh value for this SOA record. - :type refresh_time: long - :param retry_time: The retry time for this SOA record. - :type retry_time: long - :param expire_time: The expire time for this SOA record. - :type expire_time: long - :param minimum_ttl: The minimum value for this SOA record. By convention this is used to - determine the negative caching duration. - :type minimum_ttl: long - """ - - _attribute_map = { - 'host': {'key': 'host', 'type': 'str'}, - 'email': {'key': 'email', 'type': 'str'}, - 'serial_number': {'key': 'serialNumber', 'type': 'long'}, - 'refresh_time': {'key': 'refreshTime', 'type': 'long'}, - 'retry_time': {'key': 'retryTime', 'type': 'long'}, - 'expire_time': {'key': 'expireTime', 'type': 'long'}, - 'minimum_ttl': {'key': 'minimumTTL', 'type': 'long'}, - } - - def __init__( - self, - **kwargs - ): - super(SoaRecord, self).__init__(**kwargs) - self.host = kwargs.get('host', None) - self.email = kwargs.get('email', None) - self.serial_number = kwargs.get('serial_number', None) - self.refresh_time = kwargs.get('refresh_time', None) - self.retry_time = kwargs.get('retry_time', None) - self.expire_time = kwargs.get('expire_time', None) - self.minimum_ttl = kwargs.get('minimum_ttl', None) - - -class SrvRecord(msrest.serialization.Model): - """An SRV record. - - :param priority: The priority value for this SRV record. - :type priority: int - :param weight: The weight value for this SRV record. - :type weight: int - :param port: The port value for this SRV record. - :type port: int - :param target: The target domain name for this SRV record. - :type target: str - """ - - _attribute_map = { - 'priority': {'key': 'priority', 'type': 'int'}, - 'weight': {'key': 'weight', 'type': 'int'}, - 'port': {'key': 'port', 'type': 'int'}, - 'target': {'key': 'target', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(SrvRecord, self).__init__(**kwargs) - self.priority = kwargs.get('priority', None) - self.weight = kwargs.get('weight', None) - self.port = kwargs.get('port', None) - self.target = kwargs.get('target', None) - - -class SubResource(msrest.serialization.Model): - """A reference to a another resource. - - :param id: Resource Id. - :type id: str - """ - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(SubResource, self).__init__(**kwargs) - self.id = kwargs.get('id', None) - - -class TxtRecord(msrest.serialization.Model): - """A TXT record. - - :param value: The text value of this TXT record. - :type value: list[str] - """ - - _attribute_map = { - 'value': {'key': 'value', 'type': '[str]'}, - } - - def __init__( - self, - **kwargs - ): - super(TxtRecord, self).__init__(**kwargs) - self.value = kwargs.get('value', None) - - -class Zone(Resource): - """Describes a DNS zone. - - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to Azure. - - :ivar id: Resource ID. - :vartype id: str - :ivar name: Resource name. - :vartype name: str - :ivar type: Resource type. - :vartype type: str - :param location: Required. Resource location. - :type location: str - :param tags: A set of tags. Resource tags. - :type tags: dict[str, str] - :param etag: The etag of the zone. - :type etag: str - :ivar max_number_of_record_sets: The maximum number of record sets that can be created in this - DNS zone. This is a read-only property and any attempt to set this value will be ignored. - :vartype max_number_of_record_sets: long - :ivar max_number_of_records_per_record_set: The maximum number of records per record set that - can be created in this DNS zone. This is a read-only property and any attempt to set this - value will be ignored. - :vartype max_number_of_records_per_record_set: long - :ivar number_of_record_sets: The current number of record sets in this DNS zone. This is a - read-only property and any attempt to set this value will be ignored. - :vartype number_of_record_sets: long - :ivar name_servers: The name servers for this DNS zone. This is a read-only property and any - attempt to set this value will be ignored. - :vartype name_servers: list[str] - :param zone_type: The type of this DNS zone (Public or Private). Possible values include: - "Public", "Private". Default value: "Public". - :type zone_type: str or ~azure.mgmt.dns.v2018_05_01.models.ZoneType - :param registration_virtual_networks: A list of references to virtual networks that register - hostnames in this DNS zone. This is a only when ZoneType is Private. - :type registration_virtual_networks: list[~azure.mgmt.dns.v2018_05_01.models.SubResource] - :param resolution_virtual_networks: A list of references to virtual networks that resolve - records in this DNS zone. This is a only when ZoneType is Private. - :type resolution_virtual_networks: list[~azure.mgmt.dns.v2018_05_01.models.SubResource] - """ - - _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'location': {'required': True}, - 'max_number_of_record_sets': {'readonly': True}, - 'max_number_of_records_per_record_set': {'readonly': True}, - 'number_of_record_sets': {'readonly': True}, - 'name_servers': {'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}'}, - 'etag': {'key': 'etag', 'type': 'str'}, - 'max_number_of_record_sets': {'key': 'properties.maxNumberOfRecordSets', 'type': 'long'}, - 'max_number_of_records_per_record_set': {'key': 'properties.maxNumberOfRecordsPerRecordSet', 'type': 'long'}, - 'number_of_record_sets': {'key': 'properties.numberOfRecordSets', 'type': 'long'}, - 'name_servers': {'key': 'properties.nameServers', 'type': '[str]'}, - 'zone_type': {'key': 'properties.zoneType', 'type': 'str'}, - 'registration_virtual_networks': {'key': 'properties.registrationVirtualNetworks', 'type': '[SubResource]'}, - 'resolution_virtual_networks': {'key': 'properties.resolutionVirtualNetworks', 'type': '[SubResource]'}, - } - - def __init__( - self, - **kwargs - ): - super(Zone, self).__init__(**kwargs) - self.etag = kwargs.get('etag', None) - self.max_number_of_record_sets = None - self.max_number_of_records_per_record_set = None - self.number_of_record_sets = None - self.name_servers = None - self.zone_type = kwargs.get('zone_type', "Public") - self.registration_virtual_networks = kwargs.get('registration_virtual_networks', None) - self.resolution_virtual_networks = kwargs.get('resolution_virtual_networks', None) - - -class ZoneListResult(msrest.serialization.Model): - """The response to a Zone List or ListAll operation. - - Variables are only populated by the server, and will be ignored when sending a request. - - :param value: Information about the DNS zones. - :type value: list[~azure.mgmt.dns.v2018_05_01.models.Zone] - :ivar next_link: The continuation token for the next page of results. - :vartype next_link: str - """ - - _validation = { - 'next_link': {'readonly': True}, - } - - _attribute_map = { - 'value': {'key': 'value', 'type': '[Zone]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(ZoneListResult, self).__init__(**kwargs) - self.value = kwargs.get('value', None) - self.next_link = None - - -class ZoneUpdate(msrest.serialization.Model): - """Describes a request to update a DNS zone. - - :param tags: A set of tags. Resource tags. - :type tags: dict[str, str] - """ - - _attribute_map = { - 'tags': {'key': 'tags', 'type': '{str}'}, - } - - def __init__( - self, - **kwargs - ): - super(ZoneUpdate, self).__init__(**kwargs) - self.tags = kwargs.get('tags', None) diff --git a/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_05_01/models/_models_py3.py b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_05_01/models/_models_py3.py index c6c2406e6a63..9946acc70051 100644 --- a/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_05_01/models/_models_py3.py +++ b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_05_01/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. @@ -6,107 +7,110 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Dict, List, Optional, Union +from typing import Any, Dict, List, Optional, TYPE_CHECKING, Union -import msrest.serialization +from ... import _serialization -from ._dns_management_client_enums import * +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from .. import models as _models -class AaaaRecord(msrest.serialization.Model): +class AaaaRecord(_serialization.Model): """An AAAA record. - :param ipv6_address: The IPv6 address of this AAAA record. - :type ipv6_address: str + :ivar ipv6_address: The IPv6 address of this AAAA record. + :vartype ipv6_address: str """ _attribute_map = { - 'ipv6_address': {'key': 'ipv6Address', 'type': 'str'}, + "ipv6_address": {"key": "ipv6Address", "type": "str"}, } - def __init__( - self, - *, - ipv6_address: Optional[str] = None, - **kwargs - ): - super(AaaaRecord, self).__init__(**kwargs) + def __init__(self, *, ipv6_address: Optional[str] = None, **kwargs: Any) -> None: + """ + :keyword ipv6_address: The IPv6 address of this AAAA record. + :paramtype ipv6_address: str + """ + super().__init__(**kwargs) self.ipv6_address = ipv6_address -class ARecord(msrest.serialization.Model): +class ARecord(_serialization.Model): """An A record. - :param ipv4_address: The IPv4 address of this A record. - :type ipv4_address: str + :ivar ipv4_address: The IPv4 address of this A record. + :vartype ipv4_address: str """ _attribute_map = { - 'ipv4_address': {'key': 'ipv4Address', 'type': 'str'}, + "ipv4_address": {"key": "ipv4Address", "type": "str"}, } - def __init__( - self, - *, - ipv4_address: Optional[str] = None, - **kwargs - ): - super(ARecord, self).__init__(**kwargs) + def __init__(self, *, ipv4_address: Optional[str] = None, **kwargs: Any) -> None: + """ + :keyword ipv4_address: The IPv4 address of this A record. + :paramtype ipv4_address: str + """ + super().__init__(**kwargs) self.ipv4_address = ipv4_address -class CaaRecord(msrest.serialization.Model): +class CaaRecord(_serialization.Model): """A CAA record. - :param flags: The flags for this CAA record as an integer between 0 and 255. - :type flags: int - :param tag: The tag for this CAA record. - :type tag: str - :param value: The value for this CAA record. - :type value: str + :ivar flags: The flags for this CAA record as an integer between 0 and 255. + :vartype flags: int + :ivar tag: The tag for this CAA record. + :vartype tag: str + :ivar value: The value for this CAA record. + :vartype value: str """ _attribute_map = { - 'flags': {'key': 'flags', 'type': 'int'}, - 'tag': {'key': 'tag', 'type': 'str'}, - 'value': {'key': 'value', 'type': 'str'}, + "flags": {"key": "flags", "type": "int"}, + "tag": {"key": "tag", "type": "str"}, + "value": {"key": "value", "type": "str"}, } def __init__( - self, - *, - flags: Optional[int] = None, - tag: Optional[str] = None, - value: Optional[str] = None, - **kwargs - ): - super(CaaRecord, self).__init__(**kwargs) + self, *, flags: Optional[int] = None, tag: Optional[str] = None, value: Optional[str] = None, **kwargs: Any + ) -> None: + """ + :keyword flags: The flags for this CAA record as an integer between 0 and 255. + :paramtype flags: int + :keyword tag: The tag for this CAA record. + :paramtype tag: str + :keyword value: The value for this CAA record. + :paramtype value: str + """ + super().__init__(**kwargs) self.flags = flags self.tag = tag self.value = value -class CloudErrorBody(msrest.serialization.Model): +class CloudErrorBody(_serialization.Model): """An error response from the service. - :param code: An identifier for the error. Codes are invariant and are intended to be consumed + :ivar code: An identifier for the error. Codes are invariant and are intended to be consumed programmatically. - :type code: str - :param message: A message describing the error, intended to be suitable for display in a user + :vartype code: str + :ivar message: A message describing the error, intended to be suitable for display in a user interface. - :type message: str - :param target: The target of the particular error. For example, the name of the property in + :vartype message: str + :ivar target: The target of the particular error. For example, the name of the property in error. - :type target: str - :param details: A list of additional details about the error. - :type details: list[~azure.mgmt.dns.v2018_05_01.models.CloudErrorBody] + :vartype target: str + :ivar details: A list of additional details about the error. + :vartype details: list[~azure.mgmt.dns.v2018_05_01.models.CloudErrorBody] """ _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__( @@ -115,177 +119,197 @@ def __init__( code: Optional[str] = None, message: Optional[str] = None, target: Optional[str] = None, - details: Optional[List["CloudErrorBody"]] = None, - **kwargs - ): - super(CloudErrorBody, self).__init__(**kwargs) + details: Optional[List["_models.CloudErrorBody"]] = None, + **kwargs: Any + ) -> None: + """ + :keyword code: An identifier for the error. Codes are invariant and are intended to be consumed + programmatically. + :paramtype code: str + :keyword message: A message describing the error, intended to be suitable for display in a user + interface. + :paramtype message: str + :keyword target: The target of the particular error. For example, the name of the property in + error. + :paramtype target: str + :keyword details: A list of additional details about the error. + :paramtype details: list[~azure.mgmt.dns.v2018_05_01.models.CloudErrorBody] + """ + super().__init__(**kwargs) self.code = code self.message = message self.target = target self.details = details -class CnameRecord(msrest.serialization.Model): +class CnameRecord(_serialization.Model): """A CNAME record. - :param cname: The canonical name for this CNAME record. - :type cname: str + :ivar cname: The canonical name for this CNAME record. + :vartype cname: str """ _attribute_map = { - 'cname': {'key': 'cname', 'type': 'str'}, + "cname": {"key": "cname", "type": "str"}, } - def __init__( - self, - *, - cname: Optional[str] = None, - **kwargs - ): - super(CnameRecord, self).__init__(**kwargs) + def __init__(self, *, cname: Optional[str] = None, **kwargs: Any) -> None: + """ + :keyword cname: The canonical name for this CNAME record. + :paramtype cname: str + """ + super().__init__(**kwargs) self.cname = cname -class DnsResourceReference(msrest.serialization.Model): +class DnsResourceReference(_serialization.Model): """Represents a single Azure resource and its referencing DNS records. - :param dns_resources: A list of dns Records. - :type dns_resources: list[~azure.mgmt.dns.v2018_05_01.models.SubResource] - :param target_resource: A reference to an azure resource from where the dns resource value is + :ivar dns_resources: A list of dns Records. + :vartype dns_resources: list[~azure.mgmt.dns.v2018_05_01.models.SubResource] + :ivar target_resource: A reference to an azure resource from where the dns resource value is taken. - :type target_resource: ~azure.mgmt.dns.v2018_05_01.models.SubResource + :vartype target_resource: ~azure.mgmt.dns.v2018_05_01.models.SubResource """ _attribute_map = { - 'dns_resources': {'key': 'dnsResources', 'type': '[SubResource]'}, - 'target_resource': {'key': 'targetResource', 'type': 'SubResource'}, + "dns_resources": {"key": "dnsResources", "type": "[SubResource]"}, + "target_resource": {"key": "targetResource", "type": "SubResource"}, } def __init__( self, *, - dns_resources: Optional[List["SubResource"]] = None, - target_resource: Optional["SubResource"] = None, - **kwargs - ): - super(DnsResourceReference, self).__init__(**kwargs) + dns_resources: Optional[List["_models.SubResource"]] = None, + target_resource: Optional["_models.SubResource"] = None, + **kwargs: Any + ) -> None: + """ + :keyword dns_resources: A list of dns Records. + :paramtype dns_resources: list[~azure.mgmt.dns.v2018_05_01.models.SubResource] + :keyword target_resource: A reference to an azure resource from where the dns resource value is + taken. + :paramtype target_resource: ~azure.mgmt.dns.v2018_05_01.models.SubResource + """ + super().__init__(**kwargs) self.dns_resources = dns_resources self.target_resource = target_resource -class DnsResourceReferenceRequest(msrest.serialization.Model): +class DnsResourceReferenceRequest(_serialization.Model): """Represents the properties of the Dns Resource Reference Request. - :param target_resources: A list of references to azure resources for which referencing dns + :ivar target_resources: A list of references to azure resources for which referencing dns records need to be queried. - :type target_resources: list[~azure.mgmt.dns.v2018_05_01.models.SubResource] + :vartype target_resources: list[~azure.mgmt.dns.v2018_05_01.models.SubResource] """ _attribute_map = { - 'target_resources': {'key': 'properties.targetResources', 'type': '[SubResource]'}, + "target_resources": {"key": "properties.targetResources", "type": "[SubResource]"}, } - def __init__( - self, - *, - target_resources: Optional[List["SubResource"]] = None, - **kwargs - ): - super(DnsResourceReferenceRequest, self).__init__(**kwargs) + def __init__(self, *, target_resources: Optional[List["_models.SubResource"]] = None, **kwargs: Any) -> None: + """ + :keyword target_resources: A list of references to azure resources for which referencing dns + records need to be queried. + :paramtype target_resources: list[~azure.mgmt.dns.v2018_05_01.models.SubResource] + """ + super().__init__(**kwargs) self.target_resources = target_resources -class DnsResourceReferenceResult(msrest.serialization.Model): +class DnsResourceReferenceResult(_serialization.Model): """Represents the properties of the Dns Resource Reference Result. - :param dns_resource_references: The result of dns resource reference request. A list of dns + :ivar dns_resource_references: The result of dns resource reference request. A list of dns resource references for each of the azure resource in the request. - :type dns_resource_references: list[~azure.mgmt.dns.v2018_05_01.models.DnsResourceReference] + :vartype dns_resource_references: list[~azure.mgmt.dns.v2018_05_01.models.DnsResourceReference] """ _attribute_map = { - 'dns_resource_references': {'key': 'properties.dnsResourceReferences', 'type': '[DnsResourceReference]'}, + "dns_resource_references": {"key": "properties.dnsResourceReferences", "type": "[DnsResourceReference]"}, } def __init__( - self, - *, - dns_resource_references: Optional[List["DnsResourceReference"]] = None, - **kwargs - ): - super(DnsResourceReferenceResult, self).__init__(**kwargs) + self, *, dns_resource_references: Optional[List["_models.DnsResourceReference"]] = None, **kwargs: Any + ) -> None: + """ + :keyword dns_resource_references: The result of dns resource reference request. A list of dns + resource references for each of the azure resource in the request. + :paramtype dns_resource_references: + list[~azure.mgmt.dns.v2018_05_01.models.DnsResourceReference] + """ + super().__init__(**kwargs) self.dns_resource_references = dns_resource_references -class MxRecord(msrest.serialization.Model): +class MxRecord(_serialization.Model): """An MX record. - :param preference: The preference value for this MX record. - :type preference: int - :param exchange: The domain name of the mail host for this MX record. - :type exchange: str + :ivar preference: The preference value for this MX record. + :vartype preference: int + :ivar exchange: The domain name of the mail host for this MX record. + :vartype exchange: str """ _attribute_map = { - 'preference': {'key': 'preference', 'type': 'int'}, - 'exchange': {'key': 'exchange', 'type': 'str'}, + "preference": {"key": "preference", "type": "int"}, + "exchange": {"key": "exchange", "type": "str"}, } - def __init__( - self, - *, - preference: Optional[int] = None, - exchange: Optional[str] = None, - **kwargs - ): - super(MxRecord, self).__init__(**kwargs) + def __init__(self, *, preference: Optional[int] = None, exchange: Optional[str] = None, **kwargs: Any) -> None: + """ + :keyword preference: The preference value for this MX record. + :paramtype preference: int + :keyword exchange: The domain name of the mail host for this MX record. + :paramtype exchange: str + """ + super().__init__(**kwargs) self.preference = preference self.exchange = exchange -class NsRecord(msrest.serialization.Model): +class NsRecord(_serialization.Model): """An NS record. - :param nsdname: The name server name for this NS record. - :type nsdname: str + :ivar nsdname: The name server name for this NS record. + :vartype nsdname: str """ _attribute_map = { - 'nsdname': {'key': 'nsdname', 'type': 'str'}, + "nsdname": {"key": "nsdname", "type": "str"}, } - def __init__( - self, - *, - nsdname: Optional[str] = None, - **kwargs - ): - super(NsRecord, self).__init__(**kwargs) + def __init__(self, *, nsdname: Optional[str] = None, **kwargs: Any) -> None: + """ + :keyword nsdname: The name server name for this NS record. + :paramtype nsdname: str + """ + super().__init__(**kwargs) self.nsdname = nsdname -class PtrRecord(msrest.serialization.Model): +class PtrRecord(_serialization.Model): """A PTR record. - :param ptrdname: The PTR target domain name for this PTR record. - :type ptrdname: str + :ivar ptrdname: The PTR target domain name for this PTR record. + :vartype ptrdname: str """ _attribute_map = { - 'ptrdname': {'key': 'ptrdname', 'type': 'str'}, + "ptrdname": {"key": "ptrdname", "type": "str"}, } - def __init__( - self, - *, - ptrdname: Optional[str] = None, - **kwargs - ): - super(PtrRecord, self).__init__(**kwargs) + def __init__(self, *, ptrdname: Optional[str] = None, **kwargs: Any) -> None: + """ + :keyword ptrdname: The PTR target domain name for this PTR record. + :paramtype ptrdname: str + """ + super().__init__(**kwargs) self.ptrdname = ptrdname -class RecordSet(msrest.serialization.Model): +class RecordSet(_serialization.Model): # pylint: disable=too-many-instance-attributes """Describes a DNS record set (a collection of DNS records with the same name and type). Variables are only populated by the server, and will be ignored when sending a request. @@ -296,69 +320,69 @@ class RecordSet(msrest.serialization.Model): :vartype name: str :ivar type: The type of the record set. :vartype type: str - :param etag: The etag of the record set. - :type etag: str - :param metadata: The metadata attached to the record set. - :type metadata: dict[str, str] - :param ttl: The TTL (time-to-live) of the records in the record set. - :type ttl: long + :ivar etag: The etag of the record set. + :vartype etag: str + :ivar metadata: The metadata attached to the record set. + :vartype metadata: dict[str, str] + :ivar ttl: The TTL (time-to-live) of the records in the record set. + :vartype ttl: int :ivar fqdn: Fully qualified domain name of the record set. :vartype fqdn: str :ivar provisioning_state: provisioning State of the record set. :vartype provisioning_state: str - :param target_resource: A reference to an azure resource from where the dns resource value is + :ivar target_resource: A reference to an azure resource from where the dns resource value is taken. - :type target_resource: ~azure.mgmt.dns.v2018_05_01.models.SubResource - :param a_records: The list of A records in the record set. - :type a_records: list[~azure.mgmt.dns.v2018_05_01.models.ARecord] - :param aaaa_records: The list of AAAA records in the record set. - :type aaaa_records: list[~azure.mgmt.dns.v2018_05_01.models.AaaaRecord] - :param mx_records: The list of MX records in the record set. - :type mx_records: list[~azure.mgmt.dns.v2018_05_01.models.MxRecord] - :param ns_records: The list of NS records in the record set. - :type ns_records: list[~azure.mgmt.dns.v2018_05_01.models.NsRecord] - :param ptr_records: The list of PTR records in the record set. - :type ptr_records: list[~azure.mgmt.dns.v2018_05_01.models.PtrRecord] - :param srv_records: The list of SRV records in the record set. - :type srv_records: list[~azure.mgmt.dns.v2018_05_01.models.SrvRecord] - :param txt_records: The list of TXT records in the record set. - :type txt_records: list[~azure.mgmt.dns.v2018_05_01.models.TxtRecord] - :param cname_record: The CNAME record in the record set. - :type cname_record: ~azure.mgmt.dns.v2018_05_01.models.CnameRecord - :param soa_record: The SOA record in the record set. - :type soa_record: ~azure.mgmt.dns.v2018_05_01.models.SoaRecord - :param caa_records: The list of CAA records in the record set. - :type caa_records: list[~azure.mgmt.dns.v2018_05_01.models.CaaRecord] + :vartype target_resource: ~azure.mgmt.dns.v2018_05_01.models.SubResource + :ivar a_records: The list of A records in the record set. + :vartype a_records: list[~azure.mgmt.dns.v2018_05_01.models.ARecord] + :ivar aaaa_records: The list of AAAA records in the record set. + :vartype aaaa_records: list[~azure.mgmt.dns.v2018_05_01.models.AaaaRecord] + :ivar mx_records: The list of MX records in the record set. + :vartype mx_records: list[~azure.mgmt.dns.v2018_05_01.models.MxRecord] + :ivar ns_records: The list of NS records in the record set. + :vartype ns_records: list[~azure.mgmt.dns.v2018_05_01.models.NsRecord] + :ivar ptr_records: The list of PTR records in the record set. + :vartype ptr_records: list[~azure.mgmt.dns.v2018_05_01.models.PtrRecord] + :ivar srv_records: The list of SRV records in the record set. + :vartype srv_records: list[~azure.mgmt.dns.v2018_05_01.models.SrvRecord] + :ivar txt_records: The list of TXT records in the record set. + :vartype txt_records: list[~azure.mgmt.dns.v2018_05_01.models.TxtRecord] + :ivar cname_record: The CNAME record in the record set. + :vartype cname_record: ~azure.mgmt.dns.v2018_05_01.models.CnameRecord + :ivar soa_record: The SOA record in the record set. + :vartype soa_record: ~azure.mgmt.dns.v2018_05_01.models.SoaRecord + :ivar caa_records: The list of CAA records in the record set. + :vartype caa_records: list[~azure.mgmt.dns.v2018_05_01.models.CaaRecord] """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'fqdn': {'readonly': True}, - 'provisioning_state': {'readonly': True}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "fqdn": {"readonly": True}, + "provisioning_state": {"readonly": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'etag': {'key': 'etag', 'type': 'str'}, - 'metadata': {'key': 'properties.metadata', 'type': '{str}'}, - 'ttl': {'key': 'properties.TTL', 'type': 'long'}, - 'fqdn': {'key': 'properties.fqdn', 'type': 'str'}, - 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, - 'target_resource': {'key': 'properties.targetResource', 'type': 'SubResource'}, - 'a_records': {'key': 'properties.ARecords', 'type': '[ARecord]'}, - 'aaaa_records': {'key': 'properties.AAAARecords', 'type': '[AaaaRecord]'}, - 'mx_records': {'key': 'properties.MXRecords', 'type': '[MxRecord]'}, - 'ns_records': {'key': 'properties.NSRecords', 'type': '[NsRecord]'}, - 'ptr_records': {'key': 'properties.PTRRecords', 'type': '[PtrRecord]'}, - 'srv_records': {'key': 'properties.SRVRecords', 'type': '[SrvRecord]'}, - 'txt_records': {'key': 'properties.TXTRecords', 'type': '[TxtRecord]'}, - 'cname_record': {'key': 'properties.CNAMERecord', 'type': 'CnameRecord'}, - 'soa_record': {'key': 'properties.SOARecord', 'type': 'SoaRecord'}, - 'caa_records': {'key': 'properties.caaRecords', 'type': '[CaaRecord]'}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "etag": {"key": "etag", "type": "str"}, + "metadata": {"key": "properties.metadata", "type": "{str}"}, + "ttl": {"key": "properties.TTL", "type": "int"}, + "fqdn": {"key": "properties.fqdn", "type": "str"}, + "provisioning_state": {"key": "properties.provisioningState", "type": "str"}, + "target_resource": {"key": "properties.targetResource", "type": "SubResource"}, + "a_records": {"key": "properties.ARecords", "type": "[ARecord]"}, + "aaaa_records": {"key": "properties.AAAARecords", "type": "[AaaaRecord]"}, + "mx_records": {"key": "properties.MXRecords", "type": "[MxRecord]"}, + "ns_records": {"key": "properties.NSRecords", "type": "[NsRecord]"}, + "ptr_records": {"key": "properties.PTRRecords", "type": "[PtrRecord]"}, + "srv_records": {"key": "properties.SRVRecords", "type": "[SrvRecord]"}, + "txt_records": {"key": "properties.TXTRecords", "type": "[TxtRecord]"}, + "cname_record": {"key": "properties.CNAMERecord", "type": "CnameRecord"}, + "soa_record": {"key": "properties.SOARecord", "type": "SoaRecord"}, + "caa_records": {"key": "properties.caaRecords", "type": "[CaaRecord]"}, } def __init__( @@ -367,20 +391,51 @@ def __init__( etag: Optional[str] = None, metadata: Optional[Dict[str, str]] = None, ttl: Optional[int] = None, - target_resource: Optional["SubResource"] = None, - a_records: Optional[List["ARecord"]] = None, - aaaa_records: Optional[List["AaaaRecord"]] = None, - mx_records: Optional[List["MxRecord"]] = None, - ns_records: Optional[List["NsRecord"]] = None, - ptr_records: Optional[List["PtrRecord"]] = None, - srv_records: Optional[List["SrvRecord"]] = None, - txt_records: Optional[List["TxtRecord"]] = None, - cname_record: Optional["CnameRecord"] = None, - soa_record: Optional["SoaRecord"] = None, - caa_records: Optional[List["CaaRecord"]] = None, - **kwargs - ): - super(RecordSet, self).__init__(**kwargs) + target_resource: Optional["_models.SubResource"] = None, + a_records: Optional[List["_models.ARecord"]] = None, + aaaa_records: Optional[List["_models.AaaaRecord"]] = None, + mx_records: Optional[List["_models.MxRecord"]] = None, + ns_records: Optional[List["_models.NsRecord"]] = None, + ptr_records: Optional[List["_models.PtrRecord"]] = None, + srv_records: Optional[List["_models.SrvRecord"]] = None, + txt_records: Optional[List["_models.TxtRecord"]] = None, + cname_record: Optional["_models.CnameRecord"] = None, + soa_record: Optional["_models.SoaRecord"] = None, + caa_records: Optional[List["_models.CaaRecord"]] = None, + **kwargs: Any + ) -> None: + """ + :keyword etag: The etag of the record set. + :paramtype etag: str + :keyword metadata: The metadata attached to the record set. + :paramtype metadata: dict[str, str] + :keyword ttl: The TTL (time-to-live) of the records in the record set. + :paramtype ttl: int + :keyword target_resource: A reference to an azure resource from where the dns resource value is + taken. + :paramtype target_resource: ~azure.mgmt.dns.v2018_05_01.models.SubResource + :keyword a_records: The list of A records in the record set. + :paramtype a_records: list[~azure.mgmt.dns.v2018_05_01.models.ARecord] + :keyword aaaa_records: The list of AAAA records in the record set. + :paramtype aaaa_records: list[~azure.mgmt.dns.v2018_05_01.models.AaaaRecord] + :keyword mx_records: The list of MX records in the record set. + :paramtype mx_records: list[~azure.mgmt.dns.v2018_05_01.models.MxRecord] + :keyword ns_records: The list of NS records in the record set. + :paramtype ns_records: list[~azure.mgmt.dns.v2018_05_01.models.NsRecord] + :keyword ptr_records: The list of PTR records in the record set. + :paramtype ptr_records: list[~azure.mgmt.dns.v2018_05_01.models.PtrRecord] + :keyword srv_records: The list of SRV records in the record set. + :paramtype srv_records: list[~azure.mgmt.dns.v2018_05_01.models.SrvRecord] + :keyword txt_records: The list of TXT records in the record set. + :paramtype txt_records: list[~azure.mgmt.dns.v2018_05_01.models.TxtRecord] + :keyword cname_record: The CNAME record in the record set. + :paramtype cname_record: ~azure.mgmt.dns.v2018_05_01.models.CnameRecord + :keyword soa_record: The SOA record in the record set. + :paramtype soa_record: ~azure.mgmt.dns.v2018_05_01.models.SoaRecord + :keyword caa_records: The list of CAA records in the record set. + :paramtype caa_records: list[~azure.mgmt.dns.v2018_05_01.models.CaaRecord] + """ + super().__init__(**kwargs) self.id = None self.name = None self.type = None @@ -402,59 +457,57 @@ def __init__( self.caa_records = caa_records -class RecordSetListResult(msrest.serialization.Model): +class RecordSetListResult(_serialization.Model): """The response to a record set List operation. Variables are only populated by the server, and will be ignored when sending a request. - :param value: Information about the record sets in the response. - :type value: list[~azure.mgmt.dns.v2018_05_01.models.RecordSet] + :ivar value: Information about the record sets in the response. + :vartype value: list[~azure.mgmt.dns.v2018_05_01.models.RecordSet] :ivar next_link: The continuation token for the next page of results. :vartype next_link: str """ _validation = { - 'next_link': {'readonly': True}, + "next_link": {"readonly": True}, } _attribute_map = { - 'value': {'key': 'value', 'type': '[RecordSet]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "value": {"key": "value", "type": "[RecordSet]"}, + "next_link": {"key": "nextLink", "type": "str"}, } - def __init__( - self, - *, - value: Optional[List["RecordSet"]] = None, - **kwargs - ): - super(RecordSetListResult, self).__init__(**kwargs) + def __init__(self, *, value: Optional[List["_models.RecordSet"]] = None, **kwargs: Any) -> None: + """ + :keyword value: Information about the record sets in the response. + :paramtype value: list[~azure.mgmt.dns.v2018_05_01.models.RecordSet] + """ + super().__init__(**kwargs) self.value = value self.next_link = None -class RecordSetUpdateParameters(msrest.serialization.Model): +class RecordSetUpdateParameters(_serialization.Model): """Parameters supplied to update a record set. - :param record_set: Specifies information about the record set being updated. - :type record_set: ~azure.mgmt.dns.v2018_05_01.models.RecordSet + :ivar record_set: Specifies information about the record set being updated. + :vartype record_set: ~azure.mgmt.dns.v2018_05_01.models.RecordSet """ _attribute_map = { - 'record_set': {'key': 'RecordSet', 'type': 'RecordSet'}, + "record_set": {"key": "RecordSet", "type": "RecordSet"}, } - def __init__( - self, - *, - record_set: Optional["RecordSet"] = None, - **kwargs - ): - super(RecordSetUpdateParameters, self).__init__(**kwargs) + def __init__(self, *, record_set: Optional["_models.RecordSet"] = None, **kwargs: Any) -> None: + """ + :keyword record_set: Specifies information about the record set being updated. + :paramtype record_set: ~azure.mgmt.dns.v2018_05_01.models.RecordSet + """ + super().__init__(**kwargs) self.record_set = record_set -class Resource(msrest.serialization.Model): +class Resource(_serialization.Model): """Common properties of an Azure Resource Manager resource. Variables are only populated by the server, and will be ignored when sending a request. @@ -467,35 +520,35 @@ class Resource(msrest.serialization.Model): :vartype name: str :ivar type: Resource type. :vartype type: str - :param location: Required. Resource location. - :type location: str - :param tags: A set of tags. Resource tags. - :type tags: dict[str, str] + :ivar location: Resource location. Required. + :vartype location: str + :ivar tags: Resource tags. + :vartype tags: dict[str, str] """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'location': {'required': True}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "location": {"required": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - '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, - *, - location: str, - tags: Optional[Dict[str, str]] = None, - **kwargs - ): - super(Resource, self).__init__(**kwargs) + def __init__(self, *, location: str, tags: Optional[Dict[str, str]] = None, **kwargs: Any) -> None: + """ + :keyword location: Resource location. Required. + :paramtype location: str + :keyword tags: Resource tags. + :paramtype tags: dict[str, str] + """ + super().__init__(**kwargs) self.id = None self.name = None self.type = None @@ -503,34 +556,34 @@ def __init__( self.tags = tags -class SoaRecord(msrest.serialization.Model): +class SoaRecord(_serialization.Model): """An SOA record. - :param host: The domain name of the authoritative name server for this SOA record. - :type host: str - :param email: The email contact for this SOA record. - :type email: str - :param serial_number: The serial number for this SOA record. - :type serial_number: long - :param refresh_time: The refresh value for this SOA record. - :type refresh_time: long - :param retry_time: The retry time for this SOA record. - :type retry_time: long - :param expire_time: The expire time for this SOA record. - :type expire_time: long - :param minimum_ttl: The minimum value for this SOA record. By convention this is used to + :ivar host: The domain name of the authoritative name server for this SOA record. + :vartype host: str + :ivar email: The email contact for this SOA record. + :vartype email: str + :ivar serial_number: The serial number for this SOA record. + :vartype serial_number: int + :ivar refresh_time: The refresh value for this SOA record. + :vartype refresh_time: int + :ivar retry_time: The retry time for this SOA record. + :vartype retry_time: int + :ivar expire_time: The expire time for this SOA record. + :vartype expire_time: int + :ivar minimum_ttl: The minimum value for this SOA record. By convention this is used to determine the negative caching duration. - :type minimum_ttl: long + :vartype minimum_ttl: int """ _attribute_map = { - 'host': {'key': 'host', 'type': 'str'}, - 'email': {'key': 'email', 'type': 'str'}, - 'serial_number': {'key': 'serialNumber', 'type': 'long'}, - 'refresh_time': {'key': 'refreshTime', 'type': 'long'}, - 'retry_time': {'key': 'retryTime', 'type': 'long'}, - 'expire_time': {'key': 'expireTime', 'type': 'long'}, - 'minimum_ttl': {'key': 'minimumTTL', 'type': 'long'}, + "host": {"key": "host", "type": "str"}, + "email": {"key": "email", "type": "str"}, + "serial_number": {"key": "serialNumber", "type": "int"}, + "refresh_time": {"key": "refreshTime", "type": "int"}, + "retry_time": {"key": "retryTime", "type": "int"}, + "expire_time": {"key": "expireTime", "type": "int"}, + "minimum_ttl": {"key": "minimumTTL", "type": "int"}, } def __init__( @@ -543,9 +596,26 @@ def __init__( retry_time: Optional[int] = None, expire_time: Optional[int] = None, minimum_ttl: Optional[int] = None, - **kwargs - ): - super(SoaRecord, self).__init__(**kwargs) + **kwargs: Any + ) -> None: + """ + :keyword host: The domain name of the authoritative name server for this SOA record. + :paramtype host: str + :keyword email: The email contact for this SOA record. + :paramtype email: str + :keyword serial_number: The serial number for this SOA record. + :paramtype serial_number: int + :keyword refresh_time: The refresh value for this SOA record. + :paramtype refresh_time: int + :keyword retry_time: The retry time for this SOA record. + :paramtype retry_time: int + :keyword expire_time: The expire time for this SOA record. + :paramtype expire_time: int + :keyword minimum_ttl: The minimum value for this SOA record. By convention this is used to + determine the negative caching duration. + :paramtype minimum_ttl: int + """ + super().__init__(**kwargs) self.host = host self.email = email self.serial_number = serial_number @@ -555,24 +625,24 @@ def __init__( self.minimum_ttl = minimum_ttl -class SrvRecord(msrest.serialization.Model): +class SrvRecord(_serialization.Model): """An SRV record. - :param priority: The priority value for this SRV record. - :type priority: int - :param weight: The weight value for this SRV record. - :type weight: int - :param port: The port value for this SRV record. - :type port: int - :param target: The target domain name for this SRV record. - :type target: str + :ivar priority: The priority value for this SRV record. + :vartype priority: int + :ivar weight: The weight value for this SRV record. + :vartype weight: int + :ivar port: The port value for this SRV record. + :vartype port: int + :ivar target: The target domain name for this SRV record. + :vartype target: str """ _attribute_map = { - 'priority': {'key': 'priority', 'type': 'int'}, - 'weight': {'key': 'weight', 'type': 'int'}, - 'port': {'key': 'port', 'type': 'int'}, - 'target': {'key': 'target', 'type': 'str'}, + "priority": {"key": "priority", "type": "int"}, + "weight": {"key": "weight", "type": "int"}, + "port": {"key": "port", "type": "int"}, + "target": {"key": "target", "type": "str"}, } def __init__( @@ -582,58 +652,66 @@ def __init__( weight: Optional[int] = None, port: Optional[int] = None, target: Optional[str] = None, - **kwargs - ): - super(SrvRecord, self).__init__(**kwargs) + **kwargs: Any + ) -> None: + """ + :keyword priority: The priority value for this SRV record. + :paramtype priority: int + :keyword weight: The weight value for this SRV record. + :paramtype weight: int + :keyword port: The port value for this SRV record. + :paramtype port: int + :keyword target: The target domain name for this SRV record. + :paramtype target: str + """ + super().__init__(**kwargs) self.priority = priority self.weight = weight self.port = port self.target = target -class SubResource(msrest.serialization.Model): +class SubResource(_serialization.Model): """A reference to a another resource. - :param id: Resource Id. - :type id: str + :ivar id: Resource Id. + :vartype id: str """ _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, + "id": {"key": "id", "type": "str"}, } - def __init__( - self, - *, - id: Optional[str] = None, - **kwargs - ): - super(SubResource, self).__init__(**kwargs) + def __init__(self, *, id: Optional[str] = None, **kwargs: Any) -> None: # pylint: disable=redefined-builtin + """ + :keyword id: Resource Id. + :paramtype id: str + """ + super().__init__(**kwargs) self.id = id -class TxtRecord(msrest.serialization.Model): +class TxtRecord(_serialization.Model): """A TXT record. - :param value: The text value of this TXT record. - :type value: list[str] + :ivar value: The text value of this TXT record. + :vartype value: list[str] """ _attribute_map = { - 'value': {'key': 'value', 'type': '[str]'}, + "value": {"key": "value", "type": "[str]"}, } - def __init__( - self, - *, - value: Optional[List[str]] = None, - **kwargs - ): - super(TxtRecord, self).__init__(**kwargs) + def __init__(self, *, value: Optional[List[str]] = None, **kwargs: Any) -> None: + """ + :keyword value: The text value of this TXT record. + :paramtype value: list[str] + """ + super().__init__(**kwargs) self.value = value -class Zone(Resource): +class Zone(Resource): # pylint: disable=too-many-instance-attributes """Describes a DNS zone. Variables are only populated by the server, and will be ignored when sending a request. @@ -646,61 +724,61 @@ class Zone(Resource): :vartype name: str :ivar type: Resource type. :vartype type: str - :param location: Required. Resource location. - :type location: str - :param tags: A set of tags. Resource tags. - :type tags: dict[str, str] - :param etag: The etag of the zone. - :type etag: str + :ivar location: Resource location. Required. + :vartype location: str + :ivar tags: Resource tags. + :vartype tags: dict[str, str] + :ivar etag: The etag of the zone. + :vartype etag: str :ivar max_number_of_record_sets: The maximum number of record sets that can be created in this DNS zone. This is a read-only property and any attempt to set this value will be ignored. - :vartype max_number_of_record_sets: long + :vartype max_number_of_record_sets: int :ivar max_number_of_records_per_record_set: The maximum number of records per record set that can be created in this DNS zone. This is a read-only property and any attempt to set this value will be ignored. - :vartype max_number_of_records_per_record_set: long + :vartype max_number_of_records_per_record_set: int :ivar number_of_record_sets: The current number of record sets in this DNS zone. This is a read-only property and any attempt to set this value will be ignored. - :vartype number_of_record_sets: long + :vartype number_of_record_sets: int :ivar name_servers: The name servers for this DNS zone. This is a read-only property and any attempt to set this value will be ignored. :vartype name_servers: list[str] - :param zone_type: The type of this DNS zone (Public or Private). Possible values include: - "Public", "Private". Default value: "Public". - :type zone_type: str or ~azure.mgmt.dns.v2018_05_01.models.ZoneType - :param registration_virtual_networks: A list of references to virtual networks that register + :ivar zone_type: The type of this DNS zone (Public or Private). Known values are: "Public" and + "Private". + :vartype zone_type: str or ~azure.mgmt.dns.v2018_05_01.models.ZoneType + :ivar registration_virtual_networks: A list of references to virtual networks that register hostnames in this DNS zone. This is a only when ZoneType is Private. - :type registration_virtual_networks: list[~azure.mgmt.dns.v2018_05_01.models.SubResource] - :param resolution_virtual_networks: A list of references to virtual networks that resolve + :vartype registration_virtual_networks: list[~azure.mgmt.dns.v2018_05_01.models.SubResource] + :ivar resolution_virtual_networks: A list of references to virtual networks that resolve records in this DNS zone. This is a only when ZoneType is Private. - :type resolution_virtual_networks: list[~azure.mgmt.dns.v2018_05_01.models.SubResource] + :vartype resolution_virtual_networks: list[~azure.mgmt.dns.v2018_05_01.models.SubResource] """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'location': {'required': True}, - 'max_number_of_record_sets': {'readonly': True}, - 'max_number_of_records_per_record_set': {'readonly': True}, - 'number_of_record_sets': {'readonly': True}, - 'name_servers': {'readonly': True}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "location": {"required": True}, + "max_number_of_record_sets": {"readonly": True}, + "max_number_of_records_per_record_set": {"readonly": True}, + "number_of_record_sets": {"readonly": True}, + "name_servers": {"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}'}, - 'etag': {'key': 'etag', 'type': 'str'}, - 'max_number_of_record_sets': {'key': 'properties.maxNumberOfRecordSets', 'type': 'long'}, - 'max_number_of_records_per_record_set': {'key': 'properties.maxNumberOfRecordsPerRecordSet', 'type': 'long'}, - 'number_of_record_sets': {'key': 'properties.numberOfRecordSets', 'type': 'long'}, - 'name_servers': {'key': 'properties.nameServers', 'type': '[str]'}, - 'zone_type': {'key': 'properties.zoneType', 'type': 'str'}, - 'registration_virtual_networks': {'key': 'properties.registrationVirtualNetworks', 'type': '[SubResource]'}, - 'resolution_virtual_networks': {'key': 'properties.resolutionVirtualNetworks', 'type': '[SubResource]'}, + "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}"}, + "etag": {"key": "etag", "type": "str"}, + "max_number_of_record_sets": {"key": "properties.maxNumberOfRecordSets", "type": "int"}, + "max_number_of_records_per_record_set": {"key": "properties.maxNumberOfRecordsPerRecordSet", "type": "int"}, + "number_of_record_sets": {"key": "properties.numberOfRecordSets", "type": "int"}, + "name_servers": {"key": "properties.nameServers", "type": "[str]"}, + "zone_type": {"key": "properties.zoneType", "type": "str"}, + "registration_virtual_networks": {"key": "properties.registrationVirtualNetworks", "type": "[SubResource]"}, + "resolution_virtual_networks": {"key": "properties.resolutionVirtualNetworks", "type": "[SubResource]"}, } def __init__( @@ -709,12 +787,29 @@ def __init__( location: str, tags: Optional[Dict[str, str]] = None, etag: Optional[str] = None, - zone_type: Optional[Union[str, "ZoneType"]] = "Public", - registration_virtual_networks: Optional[List["SubResource"]] = None, - resolution_virtual_networks: Optional[List["SubResource"]] = None, - **kwargs - ): - super(Zone, self).__init__(location=location, tags=tags, **kwargs) + zone_type: Union[str, "_models.ZoneType"] = "Public", + registration_virtual_networks: Optional[List["_models.SubResource"]] = None, + resolution_virtual_networks: Optional[List["_models.SubResource"]] = None, + **kwargs: Any + ) -> None: + """ + :keyword location: Resource location. Required. + :paramtype location: str + :keyword tags: Resource tags. + :paramtype tags: dict[str, str] + :keyword etag: The etag of the zone. + :paramtype etag: str + :keyword zone_type: The type of this DNS zone (Public or Private). Known values are: "Public" + and "Private". + :paramtype zone_type: str or ~azure.mgmt.dns.v2018_05_01.models.ZoneType + :keyword registration_virtual_networks: A list of references to virtual networks that register + hostnames in this DNS zone. This is a only when ZoneType is Private. + :paramtype registration_virtual_networks: list[~azure.mgmt.dns.v2018_05_01.models.SubResource] + :keyword resolution_virtual_networks: A list of references to virtual networks that resolve + records in this DNS zone. This is a only when ZoneType is Private. + :paramtype resolution_virtual_networks: list[~azure.mgmt.dns.v2018_05_01.models.SubResource] + """ + super().__init__(location=location, tags=tags, **kwargs) self.etag = etag self.max_number_of_record_sets = None self.max_number_of_records_per_record_set = None @@ -725,53 +820,51 @@ def __init__( self.resolution_virtual_networks = resolution_virtual_networks -class ZoneListResult(msrest.serialization.Model): +class ZoneListResult(_serialization.Model): """The response to a Zone List or ListAll operation. Variables are only populated by the server, and will be ignored when sending a request. - :param value: Information about the DNS zones. - :type value: list[~azure.mgmt.dns.v2018_05_01.models.Zone] + :ivar value: Information about the DNS zones. + :vartype value: list[~azure.mgmt.dns.v2018_05_01.models.Zone] :ivar next_link: The continuation token for the next page of results. :vartype next_link: str """ _validation = { - 'next_link': {'readonly': True}, + "next_link": {"readonly": True}, } _attribute_map = { - 'value': {'key': 'value', 'type': '[Zone]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "value": {"key": "value", "type": "[Zone]"}, + "next_link": {"key": "nextLink", "type": "str"}, } - def __init__( - self, - *, - value: Optional[List["Zone"]] = None, - **kwargs - ): - super(ZoneListResult, self).__init__(**kwargs) + def __init__(self, *, value: Optional[List["_models.Zone"]] = None, **kwargs: Any) -> None: + """ + :keyword value: Information about the DNS zones. + :paramtype value: list[~azure.mgmt.dns.v2018_05_01.models.Zone] + """ + super().__init__(**kwargs) self.value = value self.next_link = None -class ZoneUpdate(msrest.serialization.Model): +class ZoneUpdate(_serialization.Model): """Describes a request to update a DNS zone. - :param tags: A set of tags. Resource tags. - :type tags: dict[str, str] + :ivar tags: Resource tags. + :vartype tags: dict[str, str] """ _attribute_map = { - 'tags': {'key': 'tags', 'type': '{str}'}, + "tags": {"key": "tags", "type": "{str}"}, } - def __init__( - self, - *, - tags: Optional[Dict[str, str]] = None, - **kwargs - ): - super(ZoneUpdate, self).__init__(**kwargs) + def __init__(self, *, tags: Optional[Dict[str, str]] = None, **kwargs: Any) -> None: + """ + :keyword tags: Resource tags. + :paramtype tags: dict[str, str] + """ + super().__init__(**kwargs) self.tags = tags diff --git a/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_05_01/models/_patch.py b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_05_01/models/_patch.py new file mode 100644 index 000000000000..f7dd32510333 --- /dev/null +++ b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_05_01/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/network/azure-mgmt-dns/azure/mgmt/dns/v2018_05_01/operations/__init__.py b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_05_01/operations/__init__.py index 1b7483b4a71f..bb9e9fe8e4bb 100644 --- a/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_05_01/operations/__init__.py +++ b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_05_01/operations/__init__.py @@ -10,8 +10,14 @@ from ._zones_operations import ZonesOperations from ._dns_resource_reference_operations import DnsResourceReferenceOperations +from ._patch import __all__ as _patch_all +from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import patch_sdk as _patch_sdk + __all__ = [ - 'RecordSetsOperations', - 'ZonesOperations', - 'DnsResourceReferenceOperations', + "RecordSetsOperations", + "ZonesOperations", + "DnsResourceReferenceOperations", ] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_05_01/operations/_dns_resource_reference_operations.py b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_05_01/operations/_dns_resource_reference_operations.py index a69e3bd8f53d..8655d20299b6 100644 --- a/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_05_01/operations/_dns_resource_reference_operations.py +++ b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_05_01/operations/_dns_resource_reference_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,100 +6,191 @@ # 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 TYPE_CHECKING -import warnings - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +import sys +from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, overload + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from ..._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_get_by_target_resources_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: Literal["2018-05-01"] = kwargs.pop("api_version", _params.pop("api-version", "2018-05-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Network/getDnsResourceReference" + ) + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Callable, Dict, Generic, Optional, TypeVar + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore - T = TypeVar('T') - ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") -class DnsResourceReferenceOperations(object): - """DnsResourceReferenceOperations operations. + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - 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. + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.dns.v2018_05_01.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. + +class DnsResourceReferenceOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.dns.v2018_05_01.DnsManagementClient`'s + :attr:`dns_resource_reference` 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") + @overload def get_by_target_resources( - self, - parameters, # type: "_models.DnsResourceReferenceRequest" - **kwargs # type: Any - ): - # type: (...) -> "_models.DnsResourceReferenceResult" + self, parameters: _models.DnsResourceReferenceRequest, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.DnsResourceReferenceResult: """Returns the DNS records specified by the referencing targetResourceIds. - :param parameters: Properties for dns resource reference request. + :param parameters: Properties for dns resource reference request. Required. :type parameters: ~azure.mgmt.dns.v2018_05_01.models.DnsResourceReferenceRequest + :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: DnsResourceReferenceResult, or the result of cls(response) + :return: DnsResourceReferenceResult or the result of cls(response) :rtype: ~azure.mgmt.dns.v2018_05_01.models.DnsResourceReferenceResult - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def get_by_target_resources( + self, parameters: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.DnsResourceReferenceResult: + """Returns the DNS records specified by the referencing targetResourceIds. + + :param parameters: Properties for dns resource reference 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: DnsResourceReferenceResult or the result of cls(response) + :rtype: ~azure.mgmt.dns.v2018_05_01.models.DnsResourceReferenceResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def get_by_target_resources( + self, parameters: Union[_models.DnsResourceReferenceRequest, IO], **kwargs: Any + ) -> _models.DnsResourceReferenceResult: + """Returns the DNS records specified by the referencing targetResourceIds. + + :param parameters: Properties for dns resource reference request. Is either a + DnsResourceReferenceRequest type or a IO type. Required. + :type parameters: ~azure.mgmt.dns.v2018_05_01.models.DnsResourceReferenceRequest 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: DnsResourceReferenceResult or the result of cls(response) + :rtype: ~azure.mgmt.dns.v2018_05_01.models.DnsResourceReferenceResult + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.DnsResourceReferenceResult"] 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 = "2018-05-01" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.get_by_target_resources.metadata['url'] # type: ignore - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(parameters, 'DnsResourceReferenceRequest') - body_content_kwargs['content'] = body_content - request = self._client.post(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + 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: Literal["2018-05-01"] = kwargs.pop("api_version", _params.pop("api-version", "2018-05-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.DnsResourceReferenceResult] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "DnsResourceReferenceRequest") + + request = build_get_by_target_resources_request( + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.get_by_target_resources.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = 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('DnsResourceReferenceResult', pipeline_response) + deserialized = self._deserialize("DnsResourceReferenceResult", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get_by_target_resources.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Network/getDnsResourceReference'} # type: ignore + + get_by_target_resources.metadata = { + "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Network/getDnsResourceReference" + } diff --git a/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_05_01/operations/_patch.py b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_05_01/operations/_patch.py new file mode 100644 index 000000000000..f7dd32510333 --- /dev/null +++ b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_05_01/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/network/azure-mgmt-dns/azure/mgmt/dns/v2018_05_01/operations/_record_sets_operations.py b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_05_01/operations/_record_sets_operations.py index 7c9b6ec708a0..b0bab7d25e27 100644 --- a/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_05_01/operations/_record_sets_operations.py +++ b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_05_01/operations/_record_sets_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,203 +6,725 @@ # 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 TYPE_CHECKING -import warnings - -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 HttpRequest, HttpResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from ..._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_update_request( + resource_group_name: str, + zone_name: str, + relative_record_set_name: str, + record_type: Union[str, _models.RecordType], + subscription_id: str, + *, + if_match: Optional[str] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2018-05-01"] = kwargs.pop("api_version", _params.pop("api-version", "2018-05-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}/{recordType}/{relativeRecordSetName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "zoneName": _SERIALIZER.url("zone_name", zone_name, "str"), + "relativeRecordSetName": _SERIALIZER.url( + "relative_record_set_name", relative_record_set_name, "str", skip_quote=True + ), + "recordType": _SERIALIZER.url("record_type", record_type, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if if_match is not None: + _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_create_or_update_request( + resource_group_name: str, + zone_name: str, + relative_record_set_name: str, + record_type: Union[str, _models.RecordType], + subscription_id: str, + *, + if_match: Optional[str] = None, + if_none_match: Optional[str] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2018-05-01"] = kwargs.pop("api_version", _params.pop("api-version", "2018-05-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}/{recordType}/{relativeRecordSetName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "zoneName": _SERIALIZER.url("zone_name", zone_name, "str"), + "relativeRecordSetName": _SERIALIZER.url( + "relative_record_set_name", relative_record_set_name, "str", skip_quote=True + ), + "recordType": _SERIALIZER.url("record_type", record_type, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if if_match is not None: + _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") + if if_none_match is not None: + _headers["If-None-Match"] = _SERIALIZER.header("if_none_match", if_none_match, "str") + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_delete_request( + resource_group_name: str, + zone_name: str, + relative_record_set_name: str, + record_type: Union[str, _models.RecordType], + subscription_id: str, + *, + if_match: Optional[str] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2018-05-01"] = kwargs.pop("api_version", _params.pop("api-version", "2018-05-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}/{recordType}/{relativeRecordSetName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "zoneName": _SERIALIZER.url("zone_name", zone_name, "str"), + "relativeRecordSetName": _SERIALIZER.url( + "relative_record_set_name", relative_record_set_name, "str", skip_quote=True + ), + "recordType": _SERIALIZER.url("record_type", record_type, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if if_match is not None: + _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "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, + zone_name: str, + relative_record_set_name: str, + record_type: Union[str, _models.RecordType], + subscription_id: str, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2018-05-01"] = kwargs.pop("api_version", _params.pop("api-version", "2018-05-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}/{recordType}/{relativeRecordSetName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "zoneName": _SERIALIZER.url("zone_name", zone_name, "str"), + "relativeRecordSetName": _SERIALIZER.url( + "relative_record_set_name", relative_record_set_name, "str", skip_quote=True + ), + "recordType": _SERIALIZER.url("record_type", record_type, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_by_type_request( + resource_group_name: str, + zone_name: str, + record_type: Union[str, _models.RecordType], + subscription_id: str, + *, + top: Optional[int] = None, + recordsetnamesuffix: Optional[str] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2018-05-01"] = kwargs.pop("api_version", _params.pop("api-version", "2018-05-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}/{recordType}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "zoneName": _SERIALIZER.url("zone_name", zone_name, "str"), + "recordType": _SERIALIZER.url("record_type", record_type, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + if top is not None: + _params["$top"] = _SERIALIZER.query("top", top, "int") + if recordsetnamesuffix is not None: + _params["$recordsetnamesuffix"] = _SERIALIZER.query("recordsetnamesuffix", recordsetnamesuffix, "str") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_by_dns_zone_request( + resource_group_name: str, + zone_name: str, + subscription_id: str, + *, + top: Optional[int] = None, + recordsetnamesuffix: Optional[str] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2018-05-01"] = kwargs.pop("api_version", _params.pop("api-version", "2018-05-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}/recordsets", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "zoneName": _SERIALIZER.url("zone_name", zone_name, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + if top is not None: + _params["$top"] = _SERIALIZER.query("top", top, "int") + if recordsetnamesuffix is not None: + _params["$recordsetnamesuffix"] = _SERIALIZER.query("recordsetnamesuffix", recordsetnamesuffix, "str") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_all_by_dns_zone_request( + resource_group_name: str, + zone_name: str, + subscription_id: str, + *, + top: Optional[int] = None, + record_set_name_suffix: Optional[str] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2018-05-01"] = kwargs.pop("api_version", _params.pop("api-version", "2018-05-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}/all", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "zoneName": _SERIALIZER.url("zone_name", zone_name, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + if top is not None: + _params["$top"] = _SERIALIZER.query("top", top, "int") + if record_set_name_suffix is not None: + _params["$recordsetnamesuffix"] = _SERIALIZER.query("record_set_name_suffix", record_set_name_suffix, "str") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class RecordSetsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar, Union + Instead, you should access the following operations through + :class:`~azure.mgmt.dns.v2018_05_01.DnsManagementClient`'s + :attr:`record_sets` attribute. + """ - T = TypeVar('T') - ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + models = _models -class RecordSetsOperations(object): - """RecordSetsOperations operations. + 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") - 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. + @overload + def update( + self, + resource_group_name: str, + zone_name: str, + relative_record_set_name: str, + record_type: Union[str, _models.RecordType], + parameters: _models.RecordSet, + if_match: Optional[str] = None, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RecordSet: + """Updates a record set within a DNS zone. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.dns.v2018_05_01.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. - """ + :param resource_group_name: The name of the resource group. Required. + :type resource_group_name: str + :param zone_name: The name of the DNS zone (without a terminating dot). Required. + :type zone_name: str + :param relative_record_set_name: The name of the record set, relative to the name of the zone. + Required. + :type relative_record_set_name: str + :param record_type: The type of DNS record in this record set. Known values are: "A", "AAAA", + "CAA", "CNAME", "MX", "NS", "PTR", "SOA", "SRV", and "TXT". Required. + :type record_type: str or ~azure.mgmt.dns.v2018_05_01.models.RecordType + :param parameters: Parameters supplied to the Update operation. Required. + :type parameters: ~azure.mgmt.dns.v2018_05_01.models.RecordSet + :param if_match: The etag of the record set. Omit this value to always overwrite the current + record set. Specify the last-seen etag value to prevent accidentally overwriting concurrent + changes. 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: RecordSet or the result of cls(response) + :rtype: ~azure.mgmt.dns.v2018_05_01.models.RecordSet + :raises ~azure.core.exceptions.HttpResponseError: + """ - models = _models + @overload + def update( + self, + resource_group_name: str, + zone_name: str, + relative_record_set_name: str, + record_type: Union[str, _models.RecordType], + parameters: IO, + if_match: Optional[str] = None, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RecordSet: + """Updates a record set within a DNS zone. - def __init__(self, client, config, serializer, deserializer): - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + :param resource_group_name: The name of the resource group. Required. + :type resource_group_name: str + :param zone_name: The name of the DNS zone (without a terminating dot). Required. + :type zone_name: str + :param relative_record_set_name: The name of the record set, relative to the name of the zone. + Required. + :type relative_record_set_name: str + :param record_type: The type of DNS record in this record set. Known values are: "A", "AAAA", + "CAA", "CNAME", "MX", "NS", "PTR", "SOA", "SRV", and "TXT". Required. + :type record_type: str or ~azure.mgmt.dns.v2018_05_01.models.RecordType + :param parameters: Parameters supplied to the Update operation. Required. + :type parameters: IO + :param if_match: The etag of the record set. Omit this value to always overwrite the current + record set. Specify the last-seen etag value to prevent accidentally overwriting concurrent + changes. 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: RecordSet or the result of cls(response) + :rtype: ~azure.mgmt.dns.v2018_05_01.models.RecordSet + :raises ~azure.core.exceptions.HttpResponseError: + """ + @distributed_trace def update( self, - resource_group_name, # type: str - zone_name, # type: str - relative_record_set_name, # type: str - record_type, # type: Union[str, "_models.RecordType"] - parameters, # type: "_models.RecordSet" - if_match=None, # type: Optional[str] - **kwargs # type: Any - ): - # type: (...) -> "_models.RecordSet" + resource_group_name: str, + zone_name: str, + relative_record_set_name: str, + record_type: Union[str, _models.RecordType], + parameters: Union[_models.RecordSet, IO], + if_match: Optional[str] = None, + **kwargs: Any + ) -> _models.RecordSet: """Updates a record set within a DNS zone. - :param resource_group_name: The name of the resource group. + :param resource_group_name: The name of the resource group. Required. :type resource_group_name: str - :param zone_name: The name of the DNS zone (without a terminating dot). + :param zone_name: The name of the DNS zone (without a terminating dot). Required. :type zone_name: str :param relative_record_set_name: The name of the record set, relative to the name of the zone. + Required. :type relative_record_set_name: str - :param record_type: The type of DNS record in this record set. + :param record_type: The type of DNS record in this record set. Known values are: "A", "AAAA", + "CAA", "CNAME", "MX", "NS", "PTR", "SOA", "SRV", and "TXT". Required. :type record_type: str or ~azure.mgmt.dns.v2018_05_01.models.RecordType - :param parameters: Parameters supplied to the Update operation. - :type parameters: ~azure.mgmt.dns.v2018_05_01.models.RecordSet + :param parameters: Parameters supplied to the Update operation. Is either a RecordSet type or a + IO type. Required. + :type parameters: ~azure.mgmt.dns.v2018_05_01.models.RecordSet or IO :param if_match: The etag of the record set. Omit this value to always overwrite the current record set. Specify the last-seen etag value to prevent accidentally overwriting concurrent - changes. + changes. 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: RecordSet, or the result of cls(response) + :return: RecordSet or the result of cls(response) :rtype: ~azure.mgmt.dns.v2018_05_01.models.RecordSet - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RecordSet"] 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 = "2018-05-01" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.update.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), - 'zoneName': self._serialize.url("zone_name", zone_name, 'str'), - 'relativeRecordSetName': self._serialize.url("relative_record_set_name", relative_record_set_name, 'str', skip_quote=True), - 'recordType': self._serialize.url("record_type", record_type, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - if if_match is not None: - header_parameters['If-Match'] = self._serialize.header("if_match", if_match, 'str') - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(parameters, 'RecordSet') - body_content_kwargs['content'] = body_content - request = self._client.patch(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + 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: Literal["2018-05-01"] = kwargs.pop("api_version", _params.pop("api-version", "2018-05-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.RecordSet] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "RecordSet") + + request = build_update_request( + resource_group_name=resource_group_name, + zone_name=zone_name, + relative_record_set_name=relative_record_set_name, + record_type=record_type, + subscription_id=self._config.subscription_id, + if_match=if_match, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.update.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = 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('RecordSet', pipeline_response) + deserialized = self._deserialize("RecordSet", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}/{recordType}/{relativeRecordSetName}'} # type: ignore + update.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}/{recordType}/{relativeRecordSetName}" + } + + @overload def create_or_update( self, - resource_group_name, # type: str - zone_name, # type: str - relative_record_set_name, # type: str - record_type, # type: Union[str, "_models.RecordType"] - parameters, # type: "_models.RecordSet" - if_match=None, # type: Optional[str] - if_none_match=None, # type: Optional[str] - **kwargs # type: Any - ): - # type: (...) -> "_models.RecordSet" + resource_group_name: str, + zone_name: str, + relative_record_set_name: str, + record_type: Union[str, _models.RecordType], + parameters: _models.RecordSet, + if_match: Optional[str] = None, + if_none_match: Optional[str] = None, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RecordSet: """Creates or updates a record set within a DNS zone. - :param resource_group_name: The name of the resource group. + :param resource_group_name: The name of the resource group. Required. :type resource_group_name: str - :param zone_name: The name of the DNS zone (without a terminating dot). + :param zone_name: The name of the DNS zone (without a terminating dot). Required. :type zone_name: str :param relative_record_set_name: The name of the record set, relative to the name of the zone. + Required. :type relative_record_set_name: str :param record_type: The type of DNS record in this record set. Record sets of type SOA can be - updated but not created (they are created when the DNS zone is created). + updated but not created (they are created when the DNS zone is created). Known values are: "A", + "AAAA", "CAA", "CNAME", "MX", "NS", "PTR", "SOA", "SRV", and "TXT". Required. :type record_type: str or ~azure.mgmt.dns.v2018_05_01.models.RecordType - :param parameters: Parameters supplied to the CreateOrUpdate operation. + :param parameters: Parameters supplied to the CreateOrUpdate operation. Required. :type parameters: ~azure.mgmt.dns.v2018_05_01.models.RecordSet :param if_match: The etag of the record set. Omit this value to always overwrite the current record set. Specify the last-seen etag value to prevent accidentally overwriting any concurrent - changes. + changes. Default value is None. + :type if_match: str + :param if_none_match: Set to '*' to allow a new record set to be created, but to prevent + updating an existing record set. 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: RecordSet or the result of cls(response) + :rtype: ~azure.mgmt.dns.v2018_05_01.models.RecordSet + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_or_update( + self, + resource_group_name: str, + zone_name: str, + relative_record_set_name: str, + record_type: Union[str, _models.RecordType], + parameters: IO, + if_match: Optional[str] = None, + if_none_match: Optional[str] = None, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RecordSet: + """Creates or updates a record set within a DNS zone. + + :param resource_group_name: The name of the resource group. Required. + :type resource_group_name: str + :param zone_name: The name of the DNS zone (without a terminating dot). Required. + :type zone_name: str + :param relative_record_set_name: The name of the record set, relative to the name of the zone. + Required. + :type relative_record_set_name: str + :param record_type: The type of DNS record in this record set. Record sets of type SOA can be + updated but not created (they are created when the DNS zone is created). Known values are: "A", + "AAAA", "CAA", "CNAME", "MX", "NS", "PTR", "SOA", "SRV", and "TXT". Required. + :type record_type: str or ~azure.mgmt.dns.v2018_05_01.models.RecordType + :param parameters: Parameters supplied to the CreateOrUpdate operation. Required. + :type parameters: IO + :param if_match: The etag of the record set. Omit this value to always overwrite the current + record set. Specify the last-seen etag value to prevent accidentally overwriting any concurrent + changes. Default value is None. + :type if_match: str + :param if_none_match: Set to '*' to allow a new record set to be created, but to prevent + updating an existing record set. 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: RecordSet or the result of cls(response) + :rtype: ~azure.mgmt.dns.v2018_05_01.models.RecordSet + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create_or_update( + self, + resource_group_name: str, + zone_name: str, + relative_record_set_name: str, + record_type: Union[str, _models.RecordType], + parameters: Union[_models.RecordSet, IO], + if_match: Optional[str] = None, + if_none_match: Optional[str] = None, + **kwargs: Any + ) -> _models.RecordSet: + """Creates or updates a record set within a DNS zone. + + :param resource_group_name: The name of the resource group. Required. + :type resource_group_name: str + :param zone_name: The name of the DNS zone (without a terminating dot). Required. + :type zone_name: str + :param relative_record_set_name: The name of the record set, relative to the name of the zone. + Required. + :type relative_record_set_name: str + :param record_type: The type of DNS record in this record set. Record sets of type SOA can be + updated but not created (they are created when the DNS zone is created). Known values are: "A", + "AAAA", "CAA", "CNAME", "MX", "NS", "PTR", "SOA", "SRV", and "TXT". Required. + :type record_type: str or ~azure.mgmt.dns.v2018_05_01.models.RecordType + :param parameters: Parameters supplied to the CreateOrUpdate operation. Is either a RecordSet + type or a IO type. Required. + :type parameters: ~azure.mgmt.dns.v2018_05_01.models.RecordSet or IO + :param if_match: The etag of the record set. Omit this value to always overwrite the current + record set. Specify the last-seen etag value to prevent accidentally overwriting any concurrent + changes. Default value is None. :type if_match: str :param if_none_match: Set to '*' to allow a new record set to be created, but to prevent - updating an existing record set. Other values will be ignored. + updating an existing record set. 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: RecordSet, or the result of cls(response) + :return: RecordSet or the result of cls(response) :rtype: ~azure.mgmt.dns.v2018_05_01.models.RecordSet - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RecordSet"] 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 = "2018-05-01" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.create_or_update.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), - 'zoneName': self._serialize.url("zone_name", zone_name, 'str'), - 'relativeRecordSetName': self._serialize.url("relative_record_set_name", relative_record_set_name, 'str', skip_quote=True), - 'recordType': self._serialize.url("record_type", record_type, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - if if_match is not None: - header_parameters['If-Match'] = self._serialize.header("if_match", if_match, 'str') - if if_none_match is not None: - header_parameters['If-None-Match'] = self._serialize.header("if_none_match", if_none_match, 'str') - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(parameters, 'RecordSet') - body_content_kwargs['content'] = body_content - request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + 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: Literal["2018-05-01"] = kwargs.pop("api_version", _params.pop("api-version", "2018-05-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.RecordSet] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "RecordSet") + + request = build_create_or_update_request( + resource_group_name=resource_group_name, + zone_name=zone_name, + relative_record_set_name=relative_record_set_name, + record_type=record_type, + subscription_id=self._config.subscription_id, + if_match=if_match, + if_none_match=if_none_match, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create_or_update.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response if response.status_code not in [200, 201]: @@ -209,78 +732,85 @@ def create_or_update( raise HttpResponseError(response=response, error_format=ARMErrorFormat) if response.status_code == 200: - deserialized = self._deserialize('RecordSet', pipeline_response) + deserialized = self._deserialize("RecordSet", pipeline_response) if response.status_code == 201: - deserialized = self._deserialize('RecordSet', pipeline_response) + deserialized = self._deserialize("RecordSet", pipeline_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}/{recordType}/{relativeRecordSetName}'} # type: ignore + return deserialized # type: ignore + + create_or_update.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}/{recordType}/{relativeRecordSetName}" + } - def delete( + @distributed_trace + def delete( # pylint: disable=inconsistent-return-statements self, - resource_group_name, # type: str - zone_name, # type: str - relative_record_set_name, # type: str - record_type, # type: Union[str, "_models.RecordType"] - if_match=None, # type: Optional[str] - **kwargs # type: Any - ): - # type: (...) -> None + resource_group_name: str, + zone_name: str, + relative_record_set_name: str, + record_type: Union[str, _models.RecordType], + if_match: Optional[str] = None, + **kwargs: Any + ) -> None: """Deletes a record set from a DNS zone. This operation cannot be undone. - :param resource_group_name: The name of the resource group. + :param resource_group_name: The name of the resource group. Required. :type resource_group_name: str - :param zone_name: The name of the DNS zone (without a terminating dot). + :param zone_name: The name of the DNS zone (without a terminating dot). Required. :type zone_name: str :param relative_record_set_name: The name of the record set, relative to the name of the zone. + Required. :type relative_record_set_name: str :param record_type: The type of DNS record in this record set. Record sets of type SOA cannot - be deleted (they are deleted when the DNS zone is deleted). + be deleted (they are deleted when the DNS zone is deleted). Known values are: "A", "AAAA", + "CAA", "CNAME", "MX", "NS", "PTR", "SOA", "SRV", and "TXT". Required. :type record_type: str or ~azure.mgmt.dns.v2018_05_01.models.RecordType :param if_match: The etag of the record set. Omit this value to always delete the current record set. Specify the last-seen etag value to prevent accidentally deleting any concurrent - changes. + changes. Default value is None. :type if_match: 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 - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-05-01" - accept = "application/json" - - # Construct URL - url = self.delete.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), - 'zoneName': self._serialize.url("zone_name", zone_name, 'str'), - 'relativeRecordSetName': self._serialize.url("relative_record_set_name", relative_record_set_name, 'str', skip_quote=True), - 'recordType': self._serialize.url("record_type", record_type, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2018-05-01"] = kwargs.pop("api_version", _params.pop("api-version", "2018-05-01")) + cls: ClsType[None] = kwargs.pop("cls", None) + + request = build_delete_request( + resource_group_name=resource_group_name, + zone_name=zone_name, + relative_record_set_name=relative_record_set_name, + record_type=record_type, + subscription_id=self._config.subscription_id, + if_match=if_match, + api_version=api_version, + template_url=self.delete.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) - # Construct headers - header_parameters = {} # type: Dict[str, Any] - if if_match is not None: - header_parameters['If-Match'] = self._serialize.header("if_match", if_match, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.delete(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 204]: @@ -290,154 +820,179 @@ def delete( if cls: return cls(pipeline_response, None, {}) - delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}/{recordType}/{relativeRecordSetName}'} # type: ignore + delete.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}/{recordType}/{relativeRecordSetName}" + } + @distributed_trace def get( self, - resource_group_name, # type: str - zone_name, # type: str - relative_record_set_name, # type: str - record_type, # type: Union[str, "_models.RecordType"] - **kwargs # type: Any - ): - # type: (...) -> "_models.RecordSet" + resource_group_name: str, + zone_name: str, + relative_record_set_name: str, + record_type: Union[str, _models.RecordType], + **kwargs: Any + ) -> _models.RecordSet: """Gets a record set. - :param resource_group_name: The name of the resource group. + :param resource_group_name: The name of the resource group. Required. :type resource_group_name: str - :param zone_name: The name of the DNS zone (without a terminating dot). + :param zone_name: The name of the DNS zone (without a terminating dot). Required. :type zone_name: str :param relative_record_set_name: The name of the record set, relative to the name of the zone. + Required. :type relative_record_set_name: str - :param record_type: The type of DNS record in this record set. + :param record_type: The type of DNS record in this record set. Known values are: "A", "AAAA", + "CAA", "CNAME", "MX", "NS", "PTR", "SOA", "SRV", and "TXT". Required. :type record_type: str or ~azure.mgmt.dns.v2018_05_01.models.RecordType :keyword callable cls: A custom type or function that will be passed the direct response - :return: RecordSet, or the result of cls(response) + :return: RecordSet or the result of cls(response) :rtype: ~azure.mgmt.dns.v2018_05_01.models.RecordSet - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RecordSet"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-05-01" - accept = "application/json" - - # Construct URL - url = self.get.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), - 'zoneName': self._serialize.url("zone_name", zone_name, 'str'), - 'relativeRecordSetName': self._serialize.url("relative_record_set_name", relative_record_set_name, 'str', skip_quote=True), - 'recordType': self._serialize.url("record_type", record_type, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2018-05-01"] = kwargs.pop("api_version", _params.pop("api-version", "2018-05-01")) + cls: ClsType[_models.RecordSet] = kwargs.pop("cls", None) + + request = build_get_request( + resource_group_name=resource_group_name, + zone_name=zone_name, + relative_record_set_name=relative_record_set_name, + record_type=record_type, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('RecordSet', pipeline_response) + deserialized = self._deserialize("RecordSet", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}/{recordType}/{relativeRecordSetName}'} # type: ignore + get.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}/{recordType}/{relativeRecordSetName}" + } + + @distributed_trace def list_by_type( self, - resource_group_name, # type: str - zone_name, # type: str - record_type, # type: Union[str, "_models.RecordType"] - top=None, # type: Optional[int] - recordsetnamesuffix=None, # type: Optional[str] - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.RecordSetListResult"] + resource_group_name: str, + zone_name: str, + record_type: Union[str, _models.RecordType], + top: Optional[int] = None, + recordsetnamesuffix: Optional[str] = None, + **kwargs: Any + ) -> Iterable["_models.RecordSet"]: """Lists the record sets of a specified type in a DNS zone. - :param resource_group_name: The name of the resource group. + :param resource_group_name: The name of the resource group. Required. :type resource_group_name: str - :param zone_name: The name of the DNS zone (without a terminating dot). + :param zone_name: The name of the DNS zone (without a terminating dot). Required. :type zone_name: str - :param record_type: The type of record sets to enumerate. + :param record_type: The type of record sets to enumerate. Known values are: "A", "AAAA", "CAA", + "CNAME", "MX", "NS", "PTR", "SOA", "SRV", and "TXT". Required. :type record_type: str or ~azure.mgmt.dns.v2018_05_01.models.RecordType :param top: The maximum number of record sets to return. If not specified, returns up to 100 - record sets. + record sets. Default value is None. :type top: int :param recordsetnamesuffix: The suffix label of the record set name that has to be used to filter the record set enumerations. If this parameter is specified, Enumeration will return - only records that end with .:code:``. + only records that end with .:code:``. Default value is None. :type recordsetnamesuffix: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either RecordSetListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.dns.v2018_05_01.models.RecordSetListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either RecordSet or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.dns.v2018_05_01.models.RecordSet] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RecordSetListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2018-05-01"] = kwargs.pop("api_version", _params.pop("api-version", "2018-05-01")) + cls: ClsType[_models.RecordSetListResult] = kwargs.pop("cls", None) + 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 = "2018-05-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_by_type.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), - 'zoneName': self._serialize.url("zone_name", zone_name, 'str'), - 'recordType': self._serialize.url("record_type", record_type, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - if top is not None: - query_parameters['$top'] = self._serialize.query("top", top, 'int') - if recordsetnamesuffix is not None: - query_parameters['$recordsetnamesuffix'] = self._serialize.query("recordsetnamesuffix", recordsetnamesuffix, 'str') - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_by_type_request( + resource_group_name=resource_group_name, + zone_name=zone_name, + record_type=record_type, + subscription_id=self._config.subscription_id, + top=top, + recordsetnamesuffix=recordsetnamesuffix, + api_version=api_version, + template_url=self.list_by_type.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('RecordSetListResult', pipeline_response) + deserialized = self._deserialize("RecordSetListResult", pipeline_response) list_of_elem = deserialized.value if cls: - list_of_elem = cls(list_of_elem) + list_of_elem = cls(list_of_elem) # type: ignore return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: @@ -446,86 +1001,101 @@ def get_next(next_link=None): return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list_by_type.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}/{recordType}'} # type: ignore + return ItemPaged(get_next, extract_data) + + list_by_type.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}/{recordType}" + } + @distributed_trace def list_by_dns_zone( self, - resource_group_name, # type: str - zone_name, # type: str - top=None, # type: Optional[int] - recordsetnamesuffix=None, # type: Optional[str] - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.RecordSetListResult"] + resource_group_name: str, + zone_name: str, + top: Optional[int] = None, + recordsetnamesuffix: Optional[str] = None, + **kwargs: Any + ) -> Iterable["_models.RecordSet"]: """Lists all record sets in a DNS zone. - :param resource_group_name: The name of the resource group. + :param resource_group_name: The name of the resource group. Required. :type resource_group_name: str - :param zone_name: The name of the DNS zone (without a terminating dot). + :param zone_name: The name of the DNS zone (without a terminating dot). Required. :type zone_name: str :param top: The maximum number of record sets to return. If not specified, returns up to 100 - record sets. + record sets. Default value is None. :type top: int :param recordsetnamesuffix: The suffix label of the record set name that has to be used to filter the record set enumerations. If this parameter is specified, Enumeration will return - only records that end with .:code:``. + only records that end with .:code:``. Default value is None. :type recordsetnamesuffix: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either RecordSetListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.dns.v2018_05_01.models.RecordSetListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either RecordSet or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.dns.v2018_05_01.models.RecordSet] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RecordSetListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2018-05-01"] = kwargs.pop("api_version", _params.pop("api-version", "2018-05-01")) + cls: ClsType[_models.RecordSetListResult] = kwargs.pop("cls", None) + 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 = "2018-05-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_by_dns_zone.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), - 'zoneName': self._serialize.url("zone_name", zone_name, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - if top is not None: - query_parameters['$top'] = self._serialize.query("top", top, 'int') - if recordsetnamesuffix is not None: - query_parameters['$recordsetnamesuffix'] = self._serialize.query("recordsetnamesuffix", recordsetnamesuffix, 'str') - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_by_dns_zone_request( + resource_group_name=resource_group_name, + zone_name=zone_name, + subscription_id=self._config.subscription_id, + top=top, + recordsetnamesuffix=recordsetnamesuffix, + api_version=api_version, + template_url=self.list_by_dns_zone.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('RecordSetListResult', pipeline_response) + deserialized = self._deserialize("RecordSetListResult", pipeline_response) list_of_elem = deserialized.value if cls: - list_of_elem = cls(list_of_elem) + list_of_elem = cls(list_of_elem) # type: ignore return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: @@ -534,86 +1104,101 @@ def get_next(next_link=None): return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list_by_dns_zone.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}/recordsets'} # type: ignore + return ItemPaged(get_next, extract_data) + + list_by_dns_zone.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}/recordsets" + } + @distributed_trace def list_all_by_dns_zone( self, - resource_group_name, # type: str - zone_name, # type: str - top=None, # type: Optional[int] - record_set_name_suffix=None, # type: Optional[str] - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.RecordSetListResult"] + resource_group_name: str, + zone_name: str, + top: Optional[int] = None, + record_set_name_suffix: Optional[str] = None, + **kwargs: Any + ) -> Iterable["_models.RecordSet"]: """Lists all record sets in a DNS zone. - :param resource_group_name: The name of the resource group. + :param resource_group_name: The name of the resource group. Required. :type resource_group_name: str - :param zone_name: The name of the DNS zone (without a terminating dot). + :param zone_name: The name of the DNS zone (without a terminating dot). Required. :type zone_name: str :param top: The maximum number of record sets to return. If not specified, returns up to 100 - record sets. + record sets. Default value is None. :type top: int :param record_set_name_suffix: The suffix label of the record set name that has to be used to filter the record set enumerations. If this parameter is specified, Enumeration will return - only records that end with .:code:``. + only records that end with .:code:``. Default value is None. :type record_set_name_suffix: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either RecordSetListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.dns.v2018_05_01.models.RecordSetListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either RecordSet or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.dns.v2018_05_01.models.RecordSet] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RecordSetListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2018-05-01"] = kwargs.pop("api_version", _params.pop("api-version", "2018-05-01")) + cls: ClsType[_models.RecordSetListResult] = kwargs.pop("cls", None) + 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 = "2018-05-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_all_by_dns_zone.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), - 'zoneName': self._serialize.url("zone_name", zone_name, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - if top is not None: - query_parameters['$top'] = self._serialize.query("top", top, 'int') - if record_set_name_suffix is not None: - query_parameters['$recordsetnamesuffix'] = self._serialize.query("record_set_name_suffix", record_set_name_suffix, 'str') - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_all_by_dns_zone_request( + resource_group_name=resource_group_name, + zone_name=zone_name, + subscription_id=self._config.subscription_id, + top=top, + record_set_name_suffix=record_set_name_suffix, + api_version=api_version, + template_url=self.list_all_by_dns_zone.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('RecordSetListResult', pipeline_response) + deserialized = self._deserialize("RecordSetListResult", pipeline_response) list_of_elem = deserialized.value if cls: - list_of_elem = cls(list_of_elem) + list_of_elem = cls(list_of_elem) # type: ignore return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: @@ -622,7 +1207,8 @@ def get_next(next_link=None): return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list_all_by_dns_zone.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}/all'} # type: ignore + return ItemPaged(get_next, extract_data) + + list_all_by_dns_zone.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}/all" + } diff --git a/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_05_01/operations/_zones_operations.py b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_05_01/operations/_zones_operations.py index f3b78d9cff35..b1da4ef54ec0 100644 --- a/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_05_01/operations/_zones_operations.py +++ b/sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2018_05_01/operations/_zones_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,114 +6,412 @@ # 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 TYPE_CHECKING -import warnings - -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 HttpRequest, HttpResponse +from azure.core.pipeline.transport import HttpResponse from azure.core.polling import LROPoller, NoPolling, PollingMethod +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.arm_polling import ARMPolling from .. import models as _models +from ..._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_create_or_update_request( + resource_group_name: str, + zone_name: str, + subscription_id: str, + *, + if_match: Optional[str] = None, + if_none_match: Optional[str] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2018-05-01"] = kwargs.pop("api_version", _params.pop("api-version", "2018-05-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "zoneName": _SERIALIZER.url("zone_name", zone_name, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if if_match is not None: + _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") + if if_none_match is not None: + _headers["If-None-Match"] = _SERIALIZER.header("if_none_match", if_none_match, "str") + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_delete_request( + resource_group_name: str, zone_name: str, subscription_id: str, *, if_match: Optional[str] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2018-05-01"] = kwargs.pop("api_version", _params.pop("api-version", "2018-05-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "zoneName": _SERIALIZER.url("zone_name", zone_name, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if if_match is not None: + _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "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, zone_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: Literal["2018-05-01"] = kwargs.pop("api_version", _params.pop("api-version", "2018-05-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "zoneName": _SERIALIZER.url("zone_name", zone_name, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_update_request( + resource_group_name: str, zone_name: str, subscription_id: str, *, if_match: Optional[str] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2018-05-01"] = kwargs.pop("api_version", _params.pop("api-version", "2018-05-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "zoneName": _SERIALIZER.url("zone_name", zone_name, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if if_match is not None: + _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_by_resource_group_request( + resource_group_name: str, subscription_id: str, *, top: Optional[int] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2018-05-01"] = kwargs.pop("api_version", _params.pop("api-version", "2018-05-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + if top is not None: + _params["$top"] = _SERIALIZER.query("top", top, "int") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_request(subscription_id: str, *, top: Optional[int] = None, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2018-05-01"] = kwargs.pop("api_version", _params.pop("api-version", "2018-05-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Network/dnszones") + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar, Union + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore - T = TypeVar('T') - ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + # Construct parameters + if top is not None: + _params["$top"] = _SERIALIZER.query("top", top, "int") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") -class ZonesOperations(object): - """ZonesOperations operations. + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - 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. + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.dns.v2018_05_01.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. + +class ZonesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.dns.v2018_05_01.DnsManagementClient`'s + :attr:`zones` 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") + @overload def create_or_update( self, - resource_group_name, # type: str - zone_name, # type: str - parameters, # type: "_models.Zone" - if_match=None, # type: Optional[str] - if_none_match=None, # type: Optional[str] - **kwargs # type: Any - ): - # type: (...) -> "_models.Zone" + resource_group_name: str, + zone_name: str, + parameters: _models.Zone, + if_match: Optional[str] = None, + if_none_match: Optional[str] = None, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Zone: """Creates or updates a DNS zone. Does not modify DNS records within the zone. - :param resource_group_name: The name of the resource group. + :param resource_group_name: The name of the resource group. Required. :type resource_group_name: str - :param zone_name: The name of the DNS zone (without a terminating dot). + :param zone_name: The name of the DNS zone (without a terminating dot). Required. :type zone_name: str - :param parameters: Parameters supplied to the CreateOrUpdate operation. + :param parameters: Parameters supplied to the CreateOrUpdate operation. Required. :type parameters: ~azure.mgmt.dns.v2018_05_01.models.Zone :param if_match: The etag of the DNS zone. Omit this value to always overwrite the current zone. Specify the last-seen etag value to prevent accidentally overwriting any concurrent - changes. + changes. Default value is None. :type if_match: str :param if_none_match: Set to '*' to allow a new DNS zone to be created, but to prevent updating - an existing zone. Other values will be ignored. + an existing zone. 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: Zone, or the result of cls(response) + :return: Zone or the result of cls(response) :rtype: ~azure.mgmt.dns.v2018_05_01.models.Zone - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_or_update( + self, + resource_group_name: str, + zone_name: str, + parameters: IO, + if_match: Optional[str] = None, + if_none_match: Optional[str] = None, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Zone: + """Creates or updates a DNS zone. Does not modify DNS records within the zone. + + :param resource_group_name: The name of the resource group. Required. + :type resource_group_name: str + :param zone_name: The name of the DNS zone (without a terminating dot). Required. + :type zone_name: str + :param parameters: Parameters supplied to the CreateOrUpdate operation. Required. + :type parameters: IO + :param if_match: The etag of the DNS zone. Omit this value to always overwrite the current + zone. Specify the last-seen etag value to prevent accidentally overwriting any concurrent + changes. Default value is None. + :type if_match: str + :param if_none_match: Set to '*' to allow a new DNS zone to be created, but to prevent updating + an existing zone. 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: Zone or the result of cls(response) + :rtype: ~azure.mgmt.dns.v2018_05_01.models.Zone + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create_or_update( + self, + resource_group_name: str, + zone_name: str, + parameters: Union[_models.Zone, IO], + if_match: Optional[str] = None, + if_none_match: Optional[str] = None, + **kwargs: Any + ) -> _models.Zone: + """Creates or updates a DNS zone. Does not modify DNS records within the zone. + + :param resource_group_name: The name of the resource group. Required. + :type resource_group_name: str + :param zone_name: The name of the DNS zone (without a terminating dot). Required. + :type zone_name: str + :param parameters: Parameters supplied to the CreateOrUpdate operation. Is either a Zone type + or a IO type. Required. + :type parameters: ~azure.mgmt.dns.v2018_05_01.models.Zone or IO + :param if_match: The etag of the DNS zone. Omit this value to always overwrite the current + zone. Specify the last-seen etag value to prevent accidentally overwriting any concurrent + changes. Default value is None. + :type if_match: str + :param if_none_match: Set to '*' to allow a new DNS zone to be created, but to prevent updating + an existing zone. 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: Zone or the result of cls(response) + :rtype: ~azure.mgmt.dns.v2018_05_01.models.Zone + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Zone"] 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 = "2018-05-01" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.create_or_update.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), - 'zoneName': self._serialize.url("zone_name", zone_name, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - if if_match is not None: - header_parameters['If-Match'] = self._serialize.header("if_match", if_match, 'str') - if if_none_match is not None: - header_parameters['If-None-Match'] = self._serialize.header("if_none_match", if_none_match, 'str') - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(parameters, 'Zone') - body_content_kwargs['content'] = body_content - request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + 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: Literal["2018-05-01"] = kwargs.pop("api_version", _params.pop("api-version", "2018-05-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.Zone] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "Zone") + + request = build_create_or_update_request( + resource_group_name=resource_group_name, + zone_name=zone_name, + subscription_id=self._config.subscription_id, + if_match=if_match, + if_none_match=if_none_match, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create_or_update.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response if response.status_code not in [200, 201]: @@ -120,54 +419,54 @@ def create_or_update( raise HttpResponseError(response=response, error_format=ARMErrorFormat) if response.status_code == 200: - deserialized = self._deserialize('Zone', pipeline_response) + deserialized = self._deserialize("Zone", pipeline_response) if response.status_code == 201: - deserialized = self._deserialize('Zone', pipeline_response) + deserialized = self._deserialize("Zone", pipeline_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}'} # type: ignore + return deserialized # type: ignore - def _delete_initial( - self, - resource_group_name, # type: str - zone_name, # type: str - if_match=None, # type: Optional[str] - **kwargs # type: Any - ): - # type: (...) -> None - cls = kwargs.pop('cls', None) # type: ClsType[None] + create_or_update.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}" + } + + def _delete_initial( # pylint: disable=inconsistent-return-statements + self, resource_group_name: str, zone_name: str, if_match: Optional[str] = None, **kwargs: Any + ) -> None: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-05-01" - accept = "application/json" - - # Construct URL - url = self._delete_initial.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), - 'zoneName': self._serialize.url("zone_name", zone_name, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2018-05-01"] = kwargs.pop("api_version", _params.pop("api-version", "2018-05-01")) + cls: ClsType[None] = kwargs.pop("cls", None) + + request = build_delete_request( + resource_group_name=resource_group_name, + zone_name=zone_name, + subscription_id=self._config.subscription_id, + if_match=if_match, + api_version=api_version, + template_url=self._delete_initial.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) - # Construct headers - header_parameters = {} # type: Dict[str, Any] - if if_match is not None: - header_parameters['If-Match'] = self._serialize.header("if_match", if_match, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.delete(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: @@ -177,276 +476,371 @@ def _delete_initial( if cls: return cls(pipeline_response, None, {}) - _delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}'} # type: ignore + _delete_initial.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}" + } + @distributed_trace def begin_delete( - self, - resource_group_name, # type: str - zone_name, # type: str - if_match=None, # type: Optional[str] - **kwargs # type: Any - ): - # type: (...) -> LROPoller[None] + self, resource_group_name: str, zone_name: str, if_match: Optional[str] = None, **kwargs: Any + ) -> LROPoller[None]: """Deletes a DNS zone. WARNING: All DNS records in the zone will also be deleted. This operation cannot be undone. - :param resource_group_name: The name of the resource group. + :param resource_group_name: The name of the resource group. Required. :type resource_group_name: str - :param zone_name: The name of the DNS zone (without a terminating dot). + :param zone_name: The name of the DNS zone (without a terminating dot). Required. :type zone_name: str :param if_match: The etag of the DNS zone. Omit this value to always delete the current zone. Specify the last-seen etag value to prevent accidentally deleting any concurrent changes. + Default value is None. :type if_match: 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: Pass in True if you'd like the ARMPolling polling method, - False for no polling, or your own initialized polling object for a personal polling strategy. + :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. + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. :return: An instance of LROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[None] :raises ~azure.core.exceptions.HttpResponseError: """ - polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType[None] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2018-05-01"] = kwargs.pop("api_version", _params.pop("api-version", "2018-05-01")) + cls: ClsType[None] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) if cont_token is None: - raw_result = self._delete_initial( + raw_result = self._delete_initial( # type: ignore resource_group_name=resource_group_name, zone_name=zone_name, if_match=if_match, - cls=lambda x,y,z: x, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) + kwargs.pop("error_map", None) - kwargs.pop('error_map', None) - kwargs.pop('content_type', 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, {}) - path_format_arguments = { - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), - 'zoneName': self._serialize.url("zone_name", zone_name, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), - } - - if polling is True: polling_method = ARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) - elif polling is False: polling_method = NoPolling() - else: polling_method = polling + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - else: - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}'} # type: ignore + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - def get( - self, - resource_group_name, # type: str - zone_name, # type: str - **kwargs # type: Any - ): - # type: (...) -> "_models.Zone" + begin_delete.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}" + } + + @distributed_trace + def get(self, resource_group_name: str, zone_name: str, **kwargs: Any) -> _models.Zone: """Gets a DNS zone. Retrieves the zone properties, but not the record sets within the zone. - :param resource_group_name: The name of the resource group. + :param resource_group_name: The name of the resource group. Required. :type resource_group_name: str - :param zone_name: The name of the DNS zone (without a terminating dot). + :param zone_name: The name of the DNS zone (without a terminating dot). Required. :type zone_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: Zone, or the result of cls(response) + :return: Zone or the result of cls(response) :rtype: ~azure.mgmt.dns.v2018_05_01.models.Zone - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Zone"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-05-01" - accept = "application/json" - - # Construct URL - url = self.get.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), - 'zoneName': self._serialize.url("zone_name", zone_name, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2018-05-01"] = kwargs.pop("api_version", _params.pop("api-version", "2018-05-01")) + cls: ClsType[_models.Zone] = kwargs.pop("cls", None) + + request = build_get_request( + resource_group_name=resource_group_name, + zone_name=zone_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('Zone', pipeline_response) + deserialized = self._deserialize("Zone", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}'} # type: ignore + get.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}" + } + + @overload def update( self, - resource_group_name, # type: str - zone_name, # type: str - parameters, # type: "_models.ZoneUpdate" - if_match=None, # type: Optional[str] - **kwargs # type: Any - ): - # type: (...) -> "_models.Zone" + resource_group_name: str, + zone_name: str, + parameters: _models.ZoneUpdate, + if_match: Optional[str] = None, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Zone: """Updates a DNS zone. Does not modify DNS records within the zone. - :param resource_group_name: The name of the resource group. + :param resource_group_name: The name of the resource group. Required. :type resource_group_name: str - :param zone_name: The name of the DNS zone (without a terminating dot). + :param zone_name: The name of the DNS zone (without a terminating dot). Required. :type zone_name: str - :param parameters: Parameters supplied to the Update operation. + :param parameters: Parameters supplied to the Update operation. Required. :type parameters: ~azure.mgmt.dns.v2018_05_01.models.ZoneUpdate :param if_match: The etag of the DNS zone. Omit this value to always overwrite the current zone. Specify the last-seen etag value to prevent accidentally overwriting any concurrent - changes. + changes. 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: Zone, or the result of cls(response) + :return: Zone or the result of cls(response) :rtype: ~azure.mgmt.dns.v2018_05_01.models.Zone - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def update( + self, + resource_group_name: str, + zone_name: str, + parameters: IO, + if_match: Optional[str] = None, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Zone: + """Updates a DNS zone. Does not modify DNS records within the zone. + + :param resource_group_name: The name of the resource group. Required. + :type resource_group_name: str + :param zone_name: The name of the DNS zone (without a terminating dot). Required. + :type zone_name: str + :param parameters: Parameters supplied to the Update operation. Required. + :type parameters: IO + :param if_match: The etag of the DNS zone. Omit this value to always overwrite the current + zone. Specify the last-seen etag value to prevent accidentally overwriting any concurrent + changes. 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: Zone or the result of cls(response) + :rtype: ~azure.mgmt.dns.v2018_05_01.models.Zone + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def update( + self, + resource_group_name: str, + zone_name: str, + parameters: Union[_models.ZoneUpdate, IO], + if_match: Optional[str] = None, + **kwargs: Any + ) -> _models.Zone: + """Updates a DNS zone. Does not modify DNS records within the zone. + + :param resource_group_name: The name of the resource group. Required. + :type resource_group_name: str + :param zone_name: The name of the DNS zone (without a terminating dot). Required. + :type zone_name: str + :param parameters: Parameters supplied to the Update operation. Is either a ZoneUpdate type or + a IO type. Required. + :type parameters: ~azure.mgmt.dns.v2018_05_01.models.ZoneUpdate or IO + :param if_match: The etag of the DNS zone. Omit this value to always overwrite the current + zone. Specify the last-seen etag value to prevent accidentally overwriting any concurrent + changes. 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: Zone or the result of cls(response) + :rtype: ~azure.mgmt.dns.v2018_05_01.models.Zone + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Zone"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-05-01" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.update.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), - 'zoneName': self._serialize.url("zone_name", zone_name, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - if if_match is not None: - header_parameters['If-Match'] = self._serialize.header("if_match", if_match, 'str') - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(parameters, 'ZoneUpdate') - body_content_kwargs['content'] = body_content - request = self._client.patch(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + 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: Literal["2018-05-01"] = kwargs.pop("api_version", _params.pop("api-version", "2018-05-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.Zone] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "ZoneUpdate") + + request = build_update_request( + resource_group_name=resource_group_name, + zone_name=zone_name, + subscription_id=self._config.subscription_id, + if_match=if_match, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.update.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = 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('Zone', pipeline_response) + deserialized = self._deserialize("Zone", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}'} # type: ignore + update.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}" + } + + @distributed_trace def list_by_resource_group( - self, - resource_group_name, # type: str - top=None, # type: Optional[int] - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.ZoneListResult"] + self, resource_group_name: str, top: Optional[int] = None, **kwargs: Any + ) -> Iterable["_models.Zone"]: """Lists the DNS zones within a resource group. - :param resource_group_name: The name of the resource group. + :param resource_group_name: The name of the resource group. Required. :type resource_group_name: str :param top: The maximum number of record sets to return. If not specified, returns up to 100 - record sets. + record sets. Default value is None. :type top: int :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either ZoneListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.dns.v2018_05_01.models.ZoneListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either Zone or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.dns.v2018_05_01.models.Zone] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.ZoneListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2018-05-01"] = kwargs.pop("api_version", _params.pop("api-version", "2018-05-01")) + cls: ClsType[_models.ZoneListResult] = kwargs.pop("cls", None) + 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 = "2018-05-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_by_resource_group.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - if top is not None: - query_parameters['$top'] = self._serialize.query("top", top, 'int') - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_by_resource_group_request( + resource_group_name=resource_group_name, + subscription_id=self._config.subscription_id, + top=top, + api_version=api_version, + template_url=self.list_by_resource_group.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('ZoneListResult', pipeline_response) + deserialized = self._deserialize("ZoneListResult", pipeline_response) list_of_elem = deserialized.value if cls: - list_of_elem = cls(list_of_elem) + list_of_elem = cls(list_of_elem) # type: ignore return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: @@ -455,71 +849,83 @@ def get_next(next_link=None): return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list_by_resource_group.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones'} # type: ignore + return ItemPaged(get_next, extract_data) - def list( - self, - top=None, # type: Optional[int] - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.ZoneListResult"] + list_by_resource_group.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones" + } + + @distributed_trace + def list(self, top: Optional[int] = None, **kwargs: Any) -> Iterable["_models.Zone"]: """Lists the DNS zones in all resource groups in a subscription. :param top: The maximum number of DNS zones to return. If not specified, returns up to 100 - zones. + zones. Default value is None. :type top: int :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either ZoneListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.dns.v2018_05_01.models.ZoneListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either Zone or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.dns.v2018_05_01.models.Zone] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.ZoneListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2018-05-01"] = kwargs.pop("api_version", _params.pop("api-version", "2018-05-01")) + cls: ClsType[_models.ZoneListResult] = kwargs.pop("cls", None) + 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 = "2018-05-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list.metadata['url'] # type: ignore - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - if top is not None: - query_parameters['$top'] = self._serialize.query("top", top, 'int') - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_request( + subscription_id=self._config.subscription_id, + top=top, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('ZoneListResult', pipeline_response) + deserialized = self._deserialize("ZoneListResult", pipeline_response) list_of_elem = deserialized.value if cls: - list_of_elem = cls(list_of_elem) + list_of_elem = cls(list_of_elem) # type: ignore return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: @@ -528,7 +934,6 @@ def get_next(next_link=None): return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Network/dnszones'} # type: ignore + return ItemPaged(get_next, extract_data) + + list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Network/dnszones"} diff --git a/sdk/network/azure-mgmt-dns/generated_samples/create_or_update_aaaa_recordset.py b/sdk/network/azure-mgmt-dns/generated_samples/create_or_update_aaaa_recordset.py new file mode 100644 index 000000000000..00e8ef3648c3 --- /dev/null +++ b/sdk/network/azure-mgmt-dns/generated_samples/create_or_update_aaaa_recordset.py @@ -0,0 +1,46 @@ +# 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.dns import DnsManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-dns +# USAGE + python create_or_update_aaaa_recordset.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 = DnsManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subid", + ) + + response = client.record_sets.create_or_update( + resource_group_name="rg1", + zone_name="zone1", + relative_record_set_name="record1", + record_type="AAAA", + parameters={ + "properties": {"AAAARecords": [{"ipv6Address": "::1"}], "TTL": 3600, "metadata": {"key1": "value1"}} + }, + ) + print(response) + + +# x-ms-original-file: specification/dns/resource-manager/Microsoft.Network/stable/2018-05-01/examples/CreateOrUpdateAAAARecordset.json +if __name__ == "__main__": + main() diff --git a/sdk/network/azure-mgmt-dns/generated_samples/create_or_update_arecordset.py b/sdk/network/azure-mgmt-dns/generated_samples/create_or_update_arecordset.py new file mode 100644 index 000000000000..e7f7a7b974c9 --- /dev/null +++ b/sdk/network/azure-mgmt-dns/generated_samples/create_or_update_arecordset.py @@ -0,0 +1,46 @@ +# 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.dns import DnsManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-dns +# USAGE + python create_or_update_arecordset.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 = DnsManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subid", + ) + + response = client.record_sets.create_or_update( + resource_group_name="rg1", + zone_name="zone1", + relative_record_set_name="record1", + record_type="A", + parameters={ + "properties": {"ARecords": [{"ipv4Address": "127.0.0.1"}], "TTL": 3600, "metadata": {"key1": "value1"}} + }, + ) + print(response) + + +# x-ms-original-file: specification/dns/resource-manager/Microsoft.Network/stable/2018-05-01/examples/CreateOrUpdateARecordset.json +if __name__ == "__main__": + main() diff --git a/sdk/network/azure-mgmt-dns/generated_samples/create_or_update_arecordset_alias.py b/sdk/network/azure-mgmt-dns/generated_samples/create_or_update_arecordset_alias.py new file mode 100644 index 000000000000..9dfed155760e --- /dev/null +++ b/sdk/network/azure-mgmt-dns/generated_samples/create_or_update_arecordset_alias.py @@ -0,0 +1,52 @@ +# 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.dns import DnsManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-dns +# USAGE + python create_or_update_arecordset_alias.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 = DnsManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subid", + ) + + response = client.record_sets.create_or_update( + resource_group_name="rg1", + zone_name="zone1", + relative_record_set_name="record1", + record_type="A", + parameters={ + "properties": { + "TTL": 3600, + "metadata": {"key1": "value1"}, + "targetResource": { + "id": "/subscriptions/726f8cd6-6459-4db4-8e6d-2cd2716904e2/resourceGroups/test/providers/Microsoft.Network/trafficManagerProfiles/testpp2" + }, + } + }, + ) + print(response) + + +# x-ms-original-file: specification/dns/resource-manager/Microsoft.Network/stable/2018-05-01/examples/CreateOrUpdateARecordsetAlias.json +if __name__ == "__main__": + main() diff --git a/sdk/network/azure-mgmt-dns/generated_samples/create_or_update_caa_recordset.py b/sdk/network/azure-mgmt-dns/generated_samples/create_or_update_caa_recordset.py new file mode 100644 index 000000000000..2fca577af508 --- /dev/null +++ b/sdk/network/azure-mgmt-dns/generated_samples/create_or_update_caa_recordset.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.dns import DnsManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-dns +# USAGE + python create_or_update_caa_recordset.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 = DnsManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subid", + ) + + response = client.record_sets.create_or_update( + resource_group_name="rg1", + zone_name="zone1", + relative_record_set_name="record1", + record_type="CAA", + parameters={ + "properties": { + "TTL": 3600, + "caaRecords": [{"flags": 0, "tag": "issue", "value": "ca.contoso.com"}], + "metadata": {"key1": "value1"}, + } + }, + ) + print(response) + + +# x-ms-original-file: specification/dns/resource-manager/Microsoft.Network/stable/2018-05-01/examples/CreateOrUpdateCaaRecordset.json +if __name__ == "__main__": + main() diff --git a/sdk/network/azure-mgmt-dns/generated_samples/create_or_update_cname_recordset.py b/sdk/network/azure-mgmt-dns/generated_samples/create_or_update_cname_recordset.py new file mode 100644 index 000000000000..f4a95dba4d5f --- /dev/null +++ b/sdk/network/azure-mgmt-dns/generated_samples/create_or_update_cname_recordset.py @@ -0,0 +1,46 @@ +# 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.dns import DnsManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-dns +# USAGE + python create_or_update_cname_recordset.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 = DnsManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subid", + ) + + response = client.record_sets.create_or_update( + resource_group_name="rg1", + zone_name="zone1", + relative_record_set_name="record1", + record_type="CNAME", + parameters={ + "properties": {"CNAMERecord": {"cname": "contoso.com"}, "TTL": 3600, "metadata": {"key1": "value1"}} + }, + ) + print(response) + + +# x-ms-original-file: specification/dns/resource-manager/Microsoft.Network/stable/2018-05-01/examples/CreateOrUpdateCNAMERecordset.json +if __name__ == "__main__": + main() diff --git a/sdk/network/azure-mgmt-dns/generated_samples/create_or_update_mx_recordset.py b/sdk/network/azure-mgmt-dns/generated_samples/create_or_update_mx_recordset.py new file mode 100644 index 000000000000..34e619e7351a --- /dev/null +++ b/sdk/network/azure-mgmt-dns/generated_samples/create_or_update_mx_recordset.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.dns import DnsManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-dns +# USAGE + python create_or_update_mx_recordset.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 = DnsManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subid", + ) + + response = client.record_sets.create_or_update( + resource_group_name="rg1", + zone_name="zone1", + relative_record_set_name="record1", + record_type="MX", + parameters={ + "properties": { + "MXRecords": [{"exchange": "mail.contoso.com", "preference": 0}], + "TTL": 3600, + "metadata": {"key1": "value1"}, + } + }, + ) + print(response) + + +# x-ms-original-file: specification/dns/resource-manager/Microsoft.Network/stable/2018-05-01/examples/CreateOrUpdateMXRecordset.json +if __name__ == "__main__": + main() diff --git a/sdk/network/azure-mgmt-dns/generated_samples/create_or_update_ns_recordset.py b/sdk/network/azure-mgmt-dns/generated_samples/create_or_update_ns_recordset.py new file mode 100644 index 000000000000..cc9e69a52e01 --- /dev/null +++ b/sdk/network/azure-mgmt-dns/generated_samples/create_or_update_ns_recordset.py @@ -0,0 +1,46 @@ +# 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.dns import DnsManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-dns +# USAGE + python create_or_update_ns_recordset.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 = DnsManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subid", + ) + + response = client.record_sets.create_or_update( + resource_group_name="rg1", + zone_name="zone1", + relative_record_set_name="record1", + record_type="NS", + parameters={ + "properties": {"NSRecords": [{"nsdname": "ns1.contoso.com"}], "TTL": 3600, "metadata": {"key1": "value1"}} + }, + ) + print(response) + + +# x-ms-original-file: specification/dns/resource-manager/Microsoft.Network/stable/2018-05-01/examples/CreateOrUpdateNSRecordset.json +if __name__ == "__main__": + main() diff --git a/sdk/network/azure-mgmt-dns/generated_samples/create_or_update_ptr_recordset.py b/sdk/network/azure-mgmt-dns/generated_samples/create_or_update_ptr_recordset.py new file mode 100644 index 000000000000..46484ed40ae4 --- /dev/null +++ b/sdk/network/azure-mgmt-dns/generated_samples/create_or_update_ptr_recordset.py @@ -0,0 +1,46 @@ +# 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.dns import DnsManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-dns +# USAGE + python create_or_update_ptr_recordset.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 = DnsManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subid", + ) + + response = client.record_sets.create_or_update( + resource_group_name="rg1", + zone_name="0.0.127.in-addr.arpa", + relative_record_set_name="1", + record_type="PTR", + parameters={ + "properties": {"PTRRecords": [{"ptrdname": "localhost"}], "TTL": 3600, "metadata": {"key1": "value1"}} + }, + ) + print(response) + + +# x-ms-original-file: specification/dns/resource-manager/Microsoft.Network/stable/2018-05-01/examples/CreateOrUpdatePTRRecordset.json +if __name__ == "__main__": + main() diff --git a/sdk/network/azure-mgmt-dns/generated_samples/create_or_update_soa_recordset.py b/sdk/network/azure-mgmt-dns/generated_samples/create_or_update_soa_recordset.py new file mode 100644 index 000000000000..c068aa72e163 --- /dev/null +++ b/sdk/network/azure-mgmt-dns/generated_samples/create_or_update_soa_recordset.py @@ -0,0 +1,58 @@ +# 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.dns import DnsManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-dns +# USAGE + python create_or_update_soa_recordset.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 = DnsManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subid", + ) + + response = client.record_sets.create_or_update( + resource_group_name="rg1", + zone_name="zone1", + relative_record_set_name="@", + record_type="SOA", + parameters={ + "properties": { + "SOARecord": { + "email": "hostmaster.contoso.com", + "expireTime": 2419200, + "host": "ns1.contoso.com", + "minimumTTL": 300, + "refreshTime": 3600, + "retryTime": 300, + "serialNumber": 1, + }, + "TTL": 3600, + "metadata": {"key1": "value1"}, + } + }, + ) + print(response) + + +# x-ms-original-file: specification/dns/resource-manager/Microsoft.Network/stable/2018-05-01/examples/CreateOrUpdateSOARecordset.json +if __name__ == "__main__": + main() diff --git a/sdk/network/azure-mgmt-dns/generated_samples/create_or_update_srv_recordset.py b/sdk/network/azure-mgmt-dns/generated_samples/create_or_update_srv_recordset.py new file mode 100644 index 000000000000..5b6ffbbff38e --- /dev/null +++ b/sdk/network/azure-mgmt-dns/generated_samples/create_or_update_srv_recordset.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.dns import DnsManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-dns +# USAGE + python create_or_update_srv_recordset.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 = DnsManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subid", + ) + + response = client.record_sets.create_or_update( + resource_group_name="rg1", + zone_name="zone1", + relative_record_set_name="record1", + record_type="SRV", + parameters={ + "properties": { + "SRVRecords": [{"port": 80, "priority": 0, "target": "contoso.com", "weight": 10}], + "TTL": 3600, + "metadata": {"key1": "value1"}, + } + }, + ) + print(response) + + +# x-ms-original-file: specification/dns/resource-manager/Microsoft.Network/stable/2018-05-01/examples/CreateOrUpdateSRVRecordset.json +if __name__ == "__main__": + main() diff --git a/sdk/network/azure-mgmt-dns/generated_samples/create_or_update_txt_recordset.py b/sdk/network/azure-mgmt-dns/generated_samples/create_or_update_txt_recordset.py new file mode 100644 index 000000000000..ea5ac613af01 --- /dev/null +++ b/sdk/network/azure-mgmt-dns/generated_samples/create_or_update_txt_recordset.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.dns import DnsManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-dns +# USAGE + python create_or_update_txt_recordset.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 = DnsManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subid", + ) + + response = client.record_sets.create_or_update( + resource_group_name="rg1", + zone_name="zone1", + relative_record_set_name="record1", + record_type="TXT", + parameters={ + "properties": { + "TTL": 3600, + "TXTRecords": [{"value": ["string1", "string2"]}], + "metadata": {"key1": "value1"}, + } + }, + ) + print(response) + + +# x-ms-original-file: specification/dns/resource-manager/Microsoft.Network/stable/2018-05-01/examples/CreateOrUpdateTXTRecordset.json +if __name__ == "__main__": + main() diff --git a/sdk/network/azure-mgmt-dns/generated_samples/create_or_update_zone.py b/sdk/network/azure-mgmt-dns/generated_samples/create_or_update_zone.py new file mode 100644 index 000000000000..88243d13fc40 --- /dev/null +++ b/sdk/network/azure-mgmt-dns/generated_samples/create_or_update_zone.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.dns import DnsManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-dns +# USAGE + python create_or_update_zone.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 = DnsManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subid", + ) + + response = client.zones.create_or_update( + resource_group_name="rg1", + zone_name="zone1", + parameters={"location": "Global", "tags": {"key1": "value1"}}, + ) + print(response) + + +# x-ms-original-file: specification/dns/resource-manager/Microsoft.Network/stable/2018-05-01/examples/CreateOrUpdateZone.json +if __name__ == "__main__": + main() diff --git a/sdk/network/azure-mgmt-dns/generated_samples/delete_aaaa_recordset.py b/sdk/network/azure-mgmt-dns/generated_samples/delete_aaaa_recordset.py new file mode 100644 index 000000000000..c11e21ceaa8b --- /dev/null +++ b/sdk/network/azure-mgmt-dns/generated_samples/delete_aaaa_recordset.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.dns import DnsManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-dns +# USAGE + python delete_aaaa_recordset.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 = DnsManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subid", + ) + + response = client.record_sets.delete( + resource_group_name="rg1", + zone_name="zone1", + relative_record_set_name="record1", + record_type="AAAA", + ) + print(response) + + +# x-ms-original-file: specification/dns/resource-manager/Microsoft.Network/stable/2018-05-01/examples/DeleteAAAARecordset.json +if __name__ == "__main__": + main() diff --git a/sdk/network/azure-mgmt-dns/generated_samples/delete_arecordset.py b/sdk/network/azure-mgmt-dns/generated_samples/delete_arecordset.py new file mode 100644 index 000000000000..34827e1b4904 --- /dev/null +++ b/sdk/network/azure-mgmt-dns/generated_samples/delete_arecordset.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.dns import DnsManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-dns +# USAGE + python delete_arecordset.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 = DnsManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subid", + ) + + response = client.record_sets.delete( + resource_group_name="rg1", + zone_name="zone1", + relative_record_set_name="record1", + record_type="A", + ) + print(response) + + +# x-ms-original-file: specification/dns/resource-manager/Microsoft.Network/stable/2018-05-01/examples/DeleteARecordset.json +if __name__ == "__main__": + main() diff --git a/sdk/network/azure-mgmt-dns/generated_samples/delete_caa_recordset.py b/sdk/network/azure-mgmt-dns/generated_samples/delete_caa_recordset.py new file mode 100644 index 000000000000..55090957aca5 --- /dev/null +++ b/sdk/network/azure-mgmt-dns/generated_samples/delete_caa_recordset.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.dns import DnsManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-dns +# USAGE + python delete_caa_recordset.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 = DnsManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subid", + ) + + response = client.record_sets.delete( + resource_group_name="rg1", + zone_name="zone1", + relative_record_set_name="record1", + record_type="CAA", + ) + print(response) + + +# x-ms-original-file: specification/dns/resource-manager/Microsoft.Network/stable/2018-05-01/examples/DeleteCaaRecordset.json +if __name__ == "__main__": + main() diff --git a/sdk/network/azure-mgmt-dns/generated_samples/delete_ptr_recordset.py b/sdk/network/azure-mgmt-dns/generated_samples/delete_ptr_recordset.py new file mode 100644 index 000000000000..8e4ce27f33be --- /dev/null +++ b/sdk/network/azure-mgmt-dns/generated_samples/delete_ptr_recordset.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.dns import DnsManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-dns +# USAGE + python delete_ptr_recordset.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 = DnsManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subid", + ) + + response = client.record_sets.delete( + resource_group_name="rg1", + zone_name="0.0.127.in-addr.arpa", + relative_record_set_name="1", + record_type="PTR", + ) + print(response) + + +# x-ms-original-file: specification/dns/resource-manager/Microsoft.Network/stable/2018-05-01/examples/DeletePTRRecordset.json +if __name__ == "__main__": + main() diff --git a/sdk/network/azure-mgmt-dns/generated_samples/delete_srv_recordset.py b/sdk/network/azure-mgmt-dns/generated_samples/delete_srv_recordset.py new file mode 100644 index 000000000000..9a339769eaa8 --- /dev/null +++ b/sdk/network/azure-mgmt-dns/generated_samples/delete_srv_recordset.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.dns import DnsManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-dns +# USAGE + python delete_srv_recordset.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 = DnsManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subid", + ) + + response = client.record_sets.delete( + resource_group_name="rg1", + zone_name="zone1", + relative_record_set_name="record1", + record_type="SRV", + ) + print(response) + + +# x-ms-original-file: specification/dns/resource-manager/Microsoft.Network/stable/2018-05-01/examples/DeleteSRVRecordset.json +if __name__ == "__main__": + main() diff --git a/sdk/network/azure-mgmt-dns/generated_samples/delete_txt_recordset.py b/sdk/network/azure-mgmt-dns/generated_samples/delete_txt_recordset.py new file mode 100644 index 000000000000..cc43cc8859c9 --- /dev/null +++ b/sdk/network/azure-mgmt-dns/generated_samples/delete_txt_recordset.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.dns import DnsManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-dns +# USAGE + python delete_txt_recordset.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 = DnsManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subid", + ) + + response = client.record_sets.delete( + resource_group_name="rg1", + zone_name="zone1", + relative_record_set_name="record1", + record_type="TXT", + ) + print(response) + + +# x-ms-original-file: specification/dns/resource-manager/Microsoft.Network/stable/2018-05-01/examples/DeleteTXTRecordset.json +if __name__ == "__main__": + main() diff --git a/sdk/network/azure-mgmt-dns/generated_samples/delete_zone.py b/sdk/network/azure-mgmt-dns/generated_samples/delete_zone.py new file mode 100644 index 000000000000..6f272eb59fe1 --- /dev/null +++ b/sdk/network/azure-mgmt-dns/generated_samples/delete_zone.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.dns import DnsManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-dns +# USAGE + python delete_zone.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 = DnsManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subid", + ) + + response = client.zones.begin_delete( + resource_group_name="rg1", + zone_name="zone1", + ).result() + print(response) + + +# x-ms-original-file: specification/dns/resource-manager/Microsoft.Network/stable/2018-05-01/examples/DeleteZone.json +if __name__ == "__main__": + main() diff --git a/sdk/network/azure-mgmt-dns/generated_samples/get_aaaa_recordset.py b/sdk/network/azure-mgmt-dns/generated_samples/get_aaaa_recordset.py new file mode 100644 index 000000000000..8b90cf3adbdb --- /dev/null +++ b/sdk/network/azure-mgmt-dns/generated_samples/get_aaaa_recordset.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.dns import DnsManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-dns +# USAGE + python get_aaaa_recordset.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 = DnsManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subid", + ) + + response = client.record_sets.get( + resource_group_name="rg1", + zone_name="zone1", + relative_record_set_name="record1", + record_type="AAAA", + ) + print(response) + + +# x-ms-original-file: specification/dns/resource-manager/Microsoft.Network/stable/2018-05-01/examples/GetAAAARecordset.json +if __name__ == "__main__": + main() diff --git a/sdk/network/azure-mgmt-dns/generated_samples/get_arecordset.py b/sdk/network/azure-mgmt-dns/generated_samples/get_arecordset.py new file mode 100644 index 000000000000..fa20c70e2c21 --- /dev/null +++ b/sdk/network/azure-mgmt-dns/generated_samples/get_arecordset.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.dns import DnsManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-dns +# USAGE + python get_arecordset.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 = DnsManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subid", + ) + + response = client.record_sets.get( + resource_group_name="rg1", + zone_name="zone1", + relative_record_set_name="record1", + record_type="A", + ) + print(response) + + +# x-ms-original-file: specification/dns/resource-manager/Microsoft.Network/stable/2018-05-01/examples/GetARecordset.json +if __name__ == "__main__": + main() diff --git a/sdk/network/azure-mgmt-dns/generated_samples/get_caa_recordset.py b/sdk/network/azure-mgmt-dns/generated_samples/get_caa_recordset.py new file mode 100644 index 000000000000..7308650ec80d --- /dev/null +++ b/sdk/network/azure-mgmt-dns/generated_samples/get_caa_recordset.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.dns import DnsManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-dns +# USAGE + python get_caa_recordset.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 = DnsManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subid", + ) + + response = client.record_sets.get( + resource_group_name="rg1", + zone_name="zone1", + relative_record_set_name="record1", + record_type="CAA", + ) + print(response) + + +# x-ms-original-file: specification/dns/resource-manager/Microsoft.Network/stable/2018-05-01/examples/GetCaaRecordset.json +if __name__ == "__main__": + main() diff --git a/sdk/network/azure-mgmt-dns/generated_samples/get_cname_recordset.py b/sdk/network/azure-mgmt-dns/generated_samples/get_cname_recordset.py new file mode 100644 index 000000000000..bf447e8e82e6 --- /dev/null +++ b/sdk/network/azure-mgmt-dns/generated_samples/get_cname_recordset.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.dns import DnsManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-dns +# USAGE + python get_cname_recordset.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 = DnsManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subid", + ) + + response = client.record_sets.get( + resource_group_name="rg1", + zone_name="zone1", + relative_record_set_name="record1", + record_type="CNAME", + ) + print(response) + + +# x-ms-original-file: specification/dns/resource-manager/Microsoft.Network/stable/2018-05-01/examples/GetCNAMERecordset.json +if __name__ == "__main__": + main() diff --git a/sdk/network/azure-mgmt-dns/generated_samples/get_dns_resource_reference.py b/sdk/network/azure-mgmt-dns/generated_samples/get_dns_resource_reference.py new file mode 100644 index 000000000000..314e71d466aa --- /dev/null +++ b/sdk/network/azure-mgmt-dns/generated_samples/get_dns_resource_reference.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.dns import DnsManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-dns +# USAGE + python get_dns_resource_reference.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 = DnsManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subid", + ) + + response = client.dns_resource_reference.get_by_target_resources( + parameters={ + "properties": { + "targetResources": [ + { + "id": "/subscriptions/subid/resourceGroups/rg1/providers/Microsoft.Network/trafficManagerProfiles/testpp2" + } + ] + } + }, + ) + print(response) + + +# x-ms-original-file: specification/dns/resource-manager/Microsoft.Network/stable/2018-05-01/examples/GetDnsResourceReference.json +if __name__ == "__main__": + main() diff --git a/sdk/network/azure-mgmt-dns/generated_samples/get_mx_recordset.py b/sdk/network/azure-mgmt-dns/generated_samples/get_mx_recordset.py new file mode 100644 index 000000000000..9b8d01cbba91 --- /dev/null +++ b/sdk/network/azure-mgmt-dns/generated_samples/get_mx_recordset.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.dns import DnsManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-dns +# USAGE + python get_mx_recordset.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 = DnsManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subid", + ) + + response = client.record_sets.get( + resource_group_name="rg1", + zone_name="zone1", + relative_record_set_name="record1", + record_type="MX", + ) + print(response) + + +# x-ms-original-file: specification/dns/resource-manager/Microsoft.Network/stable/2018-05-01/examples/GetMXRecordset.json +if __name__ == "__main__": + main() diff --git a/sdk/network/azure-mgmt-dns/generated_samples/get_ns_recordset.py b/sdk/network/azure-mgmt-dns/generated_samples/get_ns_recordset.py new file mode 100644 index 000000000000..5f515d03055f --- /dev/null +++ b/sdk/network/azure-mgmt-dns/generated_samples/get_ns_recordset.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.dns import DnsManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-dns +# USAGE + python get_ns_recordset.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 = DnsManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subid", + ) + + response = client.record_sets.get( + resource_group_name="rg1", + zone_name="zone1", + relative_record_set_name="record1", + record_type="NS", + ) + print(response) + + +# x-ms-original-file: specification/dns/resource-manager/Microsoft.Network/stable/2018-05-01/examples/GetNSRecordset.json +if __name__ == "__main__": + main() diff --git a/sdk/network/azure-mgmt-dns/generated_samples/get_ptr_recordset.py b/sdk/network/azure-mgmt-dns/generated_samples/get_ptr_recordset.py new file mode 100644 index 000000000000..dd159553280c --- /dev/null +++ b/sdk/network/azure-mgmt-dns/generated_samples/get_ptr_recordset.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.dns import DnsManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-dns +# USAGE + python get_ptr_recordset.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 = DnsManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subid", + ) + + response = client.record_sets.get( + resource_group_name="rg1", + zone_name="0.0.127.in-addr.arpa", + relative_record_set_name="1", + record_type="PTR", + ) + print(response) + + +# x-ms-original-file: specification/dns/resource-manager/Microsoft.Network/stable/2018-05-01/examples/GetPTRRecordset.json +if __name__ == "__main__": + main() diff --git a/sdk/network/azure-mgmt-dns/generated_samples/get_soa_recordset.py b/sdk/network/azure-mgmt-dns/generated_samples/get_soa_recordset.py new file mode 100644 index 000000000000..02c1b5682381 --- /dev/null +++ b/sdk/network/azure-mgmt-dns/generated_samples/get_soa_recordset.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.dns import DnsManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-dns +# USAGE + python get_soa_recordset.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 = DnsManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subid", + ) + + response = client.record_sets.get( + resource_group_name="rg1", + zone_name="zone1", + relative_record_set_name="@", + record_type="SOA", + ) + print(response) + + +# x-ms-original-file: specification/dns/resource-manager/Microsoft.Network/stable/2018-05-01/examples/GetSOARecordset.json +if __name__ == "__main__": + main() diff --git a/sdk/network/azure-mgmt-dns/generated_samples/get_srv_recordset.py b/sdk/network/azure-mgmt-dns/generated_samples/get_srv_recordset.py new file mode 100644 index 000000000000..15e1987099c6 --- /dev/null +++ b/sdk/network/azure-mgmt-dns/generated_samples/get_srv_recordset.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.dns import DnsManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-dns +# USAGE + python get_srv_recordset.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 = DnsManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subid", + ) + + response = client.record_sets.get( + resource_group_name="rg1", + zone_name="zone1", + relative_record_set_name="record1", + record_type="SRV", + ) + print(response) + + +# x-ms-original-file: specification/dns/resource-manager/Microsoft.Network/stable/2018-05-01/examples/GetSRVRecordset.json +if __name__ == "__main__": + main() diff --git a/sdk/network/azure-mgmt-dns/generated_samples/get_txt_recordset.py b/sdk/network/azure-mgmt-dns/generated_samples/get_txt_recordset.py new file mode 100644 index 000000000000..405d76fedc4e --- /dev/null +++ b/sdk/network/azure-mgmt-dns/generated_samples/get_txt_recordset.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.dns import DnsManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-dns +# USAGE + python get_txt_recordset.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 = DnsManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subid", + ) + + response = client.record_sets.get( + resource_group_name="rg1", + zone_name="zone1", + relative_record_set_name="record1", + record_type="TXT", + ) + print(response) + + +# x-ms-original-file: specification/dns/resource-manager/Microsoft.Network/stable/2018-05-01/examples/GetTXTRecordset.json +if __name__ == "__main__": + main() diff --git a/sdk/network/azure-mgmt-dns/generated_samples/get_zone.py b/sdk/network/azure-mgmt-dns/generated_samples/get_zone.py new file mode 100644 index 000000000000..2fbba06f86c4 --- /dev/null +++ b/sdk/network/azure-mgmt-dns/generated_samples/get_zone.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.dns import DnsManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-dns +# USAGE + python get_zone.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 = DnsManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subid", + ) + + response = client.zones.get( + resource_group_name="rg1", + zone_name="zone1", + ) + print(response) + + +# x-ms-original-file: specification/dns/resource-manager/Microsoft.Network/stable/2018-05-01/examples/GetZone.json +if __name__ == "__main__": + main() diff --git a/sdk/network/azure-mgmt-dns/generated_samples/list_aaaa_recordset.py b/sdk/network/azure-mgmt-dns/generated_samples/list_aaaa_recordset.py new file mode 100644 index 000000000000..86b19cecdf11 --- /dev/null +++ b/sdk/network/azure-mgmt-dns/generated_samples/list_aaaa_recordset.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.dns import DnsManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-dns +# USAGE + python list_aaaa_recordset.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 = DnsManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subid", + ) + + response = client.record_sets.list_by_type( + resource_group_name="rg1", + zone_name="zone1", + record_type="AAAA", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/dns/resource-manager/Microsoft.Network/stable/2018-05-01/examples/ListAAAARecordset.json +if __name__ == "__main__": + main() diff --git a/sdk/network/azure-mgmt-dns/generated_samples/list_arecordset.py b/sdk/network/azure-mgmt-dns/generated_samples/list_arecordset.py new file mode 100644 index 000000000000..6c898c73b579 --- /dev/null +++ b/sdk/network/azure-mgmt-dns/generated_samples/list_arecordset.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.dns import DnsManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-dns +# USAGE + python list_arecordset.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 = DnsManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subid", + ) + + response = client.record_sets.list_by_type( + resource_group_name="rg1", + zone_name="zone1", + record_type="A", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/dns/resource-manager/Microsoft.Network/stable/2018-05-01/examples/ListARecordset.json +if __name__ == "__main__": + main() diff --git a/sdk/network/azure-mgmt-dns/generated_samples/list_caa_recordset.py b/sdk/network/azure-mgmt-dns/generated_samples/list_caa_recordset.py new file mode 100644 index 000000000000..38aa04edc2f0 --- /dev/null +++ b/sdk/network/azure-mgmt-dns/generated_samples/list_caa_recordset.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.dns import DnsManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-dns +# USAGE + python list_caa_recordset.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 = DnsManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subid", + ) + + response = client.record_sets.list_by_type( + resource_group_name="rg1", + zone_name="zone1", + record_type="CAA", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/dns/resource-manager/Microsoft.Network/stable/2018-05-01/examples/ListCaaRecordset.json +if __name__ == "__main__": + main() diff --git a/sdk/network/azure-mgmt-dns/generated_samples/list_cname_recordset.py b/sdk/network/azure-mgmt-dns/generated_samples/list_cname_recordset.py new file mode 100644 index 000000000000..ea3c543c1f6b --- /dev/null +++ b/sdk/network/azure-mgmt-dns/generated_samples/list_cname_recordset.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.dns import DnsManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-dns +# USAGE + python list_cname_recordset.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 = DnsManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subid", + ) + + response = client.record_sets.list_by_type( + resource_group_name="rg1", + zone_name="zone1", + record_type="CNAME", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/dns/resource-manager/Microsoft.Network/stable/2018-05-01/examples/ListCNAMERecordset.json +if __name__ == "__main__": + main() diff --git a/sdk/network/azure-mgmt-dns/generated_samples/list_mx_recordset.py b/sdk/network/azure-mgmt-dns/generated_samples/list_mx_recordset.py new file mode 100644 index 000000000000..171622ab8204 --- /dev/null +++ b/sdk/network/azure-mgmt-dns/generated_samples/list_mx_recordset.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.dns import DnsManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-dns +# USAGE + python list_mx_recordset.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 = DnsManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subid", + ) + + response = client.record_sets.list_by_type( + resource_group_name="rg1", + zone_name="zone1", + record_type="MX", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/dns/resource-manager/Microsoft.Network/stable/2018-05-01/examples/ListMXRecordset.json +if __name__ == "__main__": + main() diff --git a/sdk/network/azure-mgmt-dns/generated_samples/list_ns_recordset.py b/sdk/network/azure-mgmt-dns/generated_samples/list_ns_recordset.py new file mode 100644 index 000000000000..c4a412cf3d58 --- /dev/null +++ b/sdk/network/azure-mgmt-dns/generated_samples/list_ns_recordset.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.dns import DnsManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-dns +# USAGE + python list_ns_recordset.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 = DnsManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subid", + ) + + response = client.record_sets.list_by_type( + resource_group_name="rg1", + zone_name="zone1", + record_type="NS", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/dns/resource-manager/Microsoft.Network/stable/2018-05-01/examples/ListNSRecordset.json +if __name__ == "__main__": + main() diff --git a/sdk/network/azure-mgmt-dns/generated_samples/list_ptr_recordset.py b/sdk/network/azure-mgmt-dns/generated_samples/list_ptr_recordset.py new file mode 100644 index 000000000000..9dcf8c2507be --- /dev/null +++ b/sdk/network/azure-mgmt-dns/generated_samples/list_ptr_recordset.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.dns import DnsManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-dns +# USAGE + python list_ptr_recordset.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 = DnsManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subid", + ) + + response = client.record_sets.list_by_type( + resource_group_name="rg1", + zone_name="0.0.127.in-addr.arpa", + record_type="PTR", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/dns/resource-manager/Microsoft.Network/stable/2018-05-01/examples/ListPTRRecordset.json +if __name__ == "__main__": + main() diff --git a/sdk/network/azure-mgmt-dns/generated_samples/list_record_sets_by_zone.py b/sdk/network/azure-mgmt-dns/generated_samples/list_record_sets_by_zone.py new file mode 100644 index 000000000000..5befbff6e0c6 --- /dev/null +++ b/sdk/network/azure-mgmt-dns/generated_samples/list_record_sets_by_zone.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.dns import DnsManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-dns +# USAGE + python list_record_sets_by_zone.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 = DnsManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subid", + ) + + response = client.record_sets.list_by_dns_zone( + resource_group_name="rg1", + zone_name="zone1", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/dns/resource-manager/Microsoft.Network/stable/2018-05-01/examples/ListRecordSetsByZone.json +if __name__ == "__main__": + main() diff --git a/sdk/network/azure-mgmt-dns/generated_samples/list_soa_recordset.py b/sdk/network/azure-mgmt-dns/generated_samples/list_soa_recordset.py new file mode 100644 index 000000000000..32d69bfddb6a --- /dev/null +++ b/sdk/network/azure-mgmt-dns/generated_samples/list_soa_recordset.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.dns import DnsManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-dns +# USAGE + python list_soa_recordset.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 = DnsManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subid", + ) + + response = client.record_sets.list_by_type( + resource_group_name="rg1", + zone_name="zone1", + record_type="SOA", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/dns/resource-manager/Microsoft.Network/stable/2018-05-01/examples/ListSOARecordset.json +if __name__ == "__main__": + main() diff --git a/sdk/network/azure-mgmt-dns/generated_samples/list_srv_recordset.py b/sdk/network/azure-mgmt-dns/generated_samples/list_srv_recordset.py new file mode 100644 index 000000000000..138f27f999ea --- /dev/null +++ b/sdk/network/azure-mgmt-dns/generated_samples/list_srv_recordset.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.dns import DnsManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-dns +# USAGE + python list_srv_recordset.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 = DnsManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subid", + ) + + response = client.record_sets.list_by_type( + resource_group_name="rg1", + zone_name="zone1", + record_type="SRV", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/dns/resource-manager/Microsoft.Network/stable/2018-05-01/examples/ListSRVRecordset.json +if __name__ == "__main__": + main() diff --git a/sdk/network/azure-mgmt-dns/generated_samples/list_txt_recordset.py b/sdk/network/azure-mgmt-dns/generated_samples/list_txt_recordset.py new file mode 100644 index 000000000000..474fe9541e23 --- /dev/null +++ b/sdk/network/azure-mgmt-dns/generated_samples/list_txt_recordset.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.dns import DnsManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-dns +# USAGE + python list_txt_recordset.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 = DnsManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subid", + ) + + response = client.record_sets.list_by_type( + resource_group_name="rg1", + zone_name="zone1", + record_type="TXT", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/dns/resource-manager/Microsoft.Network/stable/2018-05-01/examples/ListTXTRecordset.json +if __name__ == "__main__": + main() diff --git a/sdk/network/azure-mgmt-dns/generated_samples/list_zones_by_resource_group.py b/sdk/network/azure-mgmt-dns/generated_samples/list_zones_by_resource_group.py new file mode 100644 index 000000000000..67af7bb5ec41 --- /dev/null +++ b/sdk/network/azure-mgmt-dns/generated_samples/list_zones_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.dns import DnsManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-dns +# USAGE + python list_zones_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 = DnsManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subid", + ) + + response = client.zones.list_by_resource_group( + resource_group_name="rg1", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/dns/resource-manager/Microsoft.Network/stable/2018-05-01/examples/ListZonesByResourceGroup.json +if __name__ == "__main__": + main() diff --git a/sdk/network/azure-mgmt-dns/generated_samples/list_zones_by_subscription.py b/sdk/network/azure-mgmt-dns/generated_samples/list_zones_by_subscription.py new file mode 100644 index 000000000000..65b6830939cf --- /dev/null +++ b/sdk/network/azure-mgmt-dns/generated_samples/list_zones_by_subscription.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.dns import DnsManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-dns +# USAGE + python list_zones_by_subscription.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 = DnsManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subid", + ) + + response = client.zones.list() + for item in response: + print(item) + + +# x-ms-original-file: specification/dns/resource-manager/Microsoft.Network/stable/2018-05-01/examples/ListZonesBySubscription.json +if __name__ == "__main__": + main() diff --git a/sdk/network/azure-mgmt-dns/generated_samples/patch_aaaa_recordset.py b/sdk/network/azure-mgmt-dns/generated_samples/patch_aaaa_recordset.py new file mode 100644 index 000000000000..ddf0f20b8c76 --- /dev/null +++ b/sdk/network/azure-mgmt-dns/generated_samples/patch_aaaa_recordset.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.dns import DnsManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-dns +# USAGE + python patch_aaaa_recordset.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 = DnsManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subid", + ) + + response = client.record_sets.update( + resource_group_name="rg1", + zone_name="zone1", + relative_record_set_name="record1", + record_type="AAAA", + parameters={"properties": {"metadata": {"key2": "value2"}}}, + ) + print(response) + + +# x-ms-original-file: specification/dns/resource-manager/Microsoft.Network/stable/2018-05-01/examples/PatchAAAARecordset.json +if __name__ == "__main__": + main() diff --git a/sdk/network/azure-mgmt-dns/generated_samples/patch_arecordset.py b/sdk/network/azure-mgmt-dns/generated_samples/patch_arecordset.py new file mode 100644 index 000000000000..a53aea8ce03b --- /dev/null +++ b/sdk/network/azure-mgmt-dns/generated_samples/patch_arecordset.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.dns import DnsManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-dns +# USAGE + python patch_arecordset.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 = DnsManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subid", + ) + + response = client.record_sets.update( + resource_group_name="rg1", + zone_name="zone1", + relative_record_set_name="record1", + record_type="A", + parameters={"properties": {"metadata": {"key2": "value2"}}}, + ) + print(response) + + +# x-ms-original-file: specification/dns/resource-manager/Microsoft.Network/stable/2018-05-01/examples/PatchARecordset.json +if __name__ == "__main__": + main() diff --git a/sdk/network/azure-mgmt-dns/generated_samples/patch_caa_recordset.py b/sdk/network/azure-mgmt-dns/generated_samples/patch_caa_recordset.py new file mode 100644 index 000000000000..9ef9e4b6fd80 --- /dev/null +++ b/sdk/network/azure-mgmt-dns/generated_samples/patch_caa_recordset.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.dns import DnsManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-dns +# USAGE + python patch_caa_recordset.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 = DnsManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subid", + ) + + response = client.record_sets.update( + resource_group_name="rg1", + zone_name="zone1", + relative_record_set_name="record1", + record_type="CAA", + parameters={"properties": {"metadata": {"key2": "value2"}}}, + ) + print(response) + + +# x-ms-original-file: specification/dns/resource-manager/Microsoft.Network/stable/2018-05-01/examples/PatchCaaRecordset.json +if __name__ == "__main__": + main() diff --git a/sdk/network/azure-mgmt-dns/generated_samples/patch_cname_recordset.py b/sdk/network/azure-mgmt-dns/generated_samples/patch_cname_recordset.py new file mode 100644 index 000000000000..92d2f95f10e3 --- /dev/null +++ b/sdk/network/azure-mgmt-dns/generated_samples/patch_cname_recordset.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.dns import DnsManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-dns +# USAGE + python patch_cname_recordset.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 = DnsManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subid", + ) + + response = client.record_sets.update( + resource_group_name="rg1", + zone_name="zone1", + relative_record_set_name="record1", + record_type="CNAME", + parameters={"properties": {"metadata": {"key2": "value2"}}}, + ) + print(response) + + +# x-ms-original-file: specification/dns/resource-manager/Microsoft.Network/stable/2018-05-01/examples/PatchCNAMERecordset.json +if __name__ == "__main__": + main() diff --git a/sdk/network/azure-mgmt-dns/generated_samples/patch_mx_recordset.py b/sdk/network/azure-mgmt-dns/generated_samples/patch_mx_recordset.py new file mode 100644 index 000000000000..484461698e3f --- /dev/null +++ b/sdk/network/azure-mgmt-dns/generated_samples/patch_mx_recordset.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.dns import DnsManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-dns +# USAGE + python patch_mx_recordset.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 = DnsManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subid", + ) + + response = client.record_sets.update( + resource_group_name="rg1", + zone_name="zone1", + relative_record_set_name="record1", + record_type="MX", + parameters={"properties": {"metadata": {"key2": "value2"}}}, + ) + print(response) + + +# x-ms-original-file: specification/dns/resource-manager/Microsoft.Network/stable/2018-05-01/examples/PatchMXRecordset.json +if __name__ == "__main__": + main() diff --git a/sdk/network/azure-mgmt-dns/generated_samples/patch_ns_recordset.py b/sdk/network/azure-mgmt-dns/generated_samples/patch_ns_recordset.py new file mode 100644 index 000000000000..348d41d936db --- /dev/null +++ b/sdk/network/azure-mgmt-dns/generated_samples/patch_ns_recordset.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.dns import DnsManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-dns +# USAGE + python patch_ns_recordset.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 = DnsManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subid", + ) + + response = client.record_sets.update( + resource_group_name="rg1", + zone_name="zone1", + relative_record_set_name="record1", + record_type="NS", + parameters={"properties": {"metadata": {"key2": "value2"}}}, + ) + print(response) + + +# x-ms-original-file: specification/dns/resource-manager/Microsoft.Network/stable/2018-05-01/examples/PatchNSRecordset.json +if __name__ == "__main__": + main() diff --git a/sdk/network/azure-mgmt-dns/generated_samples/patch_ptr_recordset.py b/sdk/network/azure-mgmt-dns/generated_samples/patch_ptr_recordset.py new file mode 100644 index 000000000000..805c17575e9c --- /dev/null +++ b/sdk/network/azure-mgmt-dns/generated_samples/patch_ptr_recordset.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.dns import DnsManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-dns +# USAGE + python patch_ptr_recordset.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 = DnsManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subid", + ) + + response = client.record_sets.update( + resource_group_name="rg1", + zone_name="0.0.127.in-addr.arpa", + relative_record_set_name="1", + record_type="PTR", + parameters={"properties": {"metadata": {"key2": "value2"}}}, + ) + print(response) + + +# x-ms-original-file: specification/dns/resource-manager/Microsoft.Network/stable/2018-05-01/examples/PatchPTRRecordset.json +if __name__ == "__main__": + main() diff --git a/sdk/network/azure-mgmt-dns/generated_samples/patch_soa_recordset.py b/sdk/network/azure-mgmt-dns/generated_samples/patch_soa_recordset.py new file mode 100644 index 000000000000..61c97104473f --- /dev/null +++ b/sdk/network/azure-mgmt-dns/generated_samples/patch_soa_recordset.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.dns import DnsManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-dns +# USAGE + python patch_soa_recordset.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 = DnsManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subid", + ) + + response = client.record_sets.update( + resource_group_name="rg1", + zone_name="zone1", + relative_record_set_name="@", + record_type="SOA", + parameters={"properties": {"metadata": {"key2": "value2"}}}, + ) + print(response) + + +# x-ms-original-file: specification/dns/resource-manager/Microsoft.Network/stable/2018-05-01/examples/PatchSOARecordset.json +if __name__ == "__main__": + main() diff --git a/sdk/network/azure-mgmt-dns/generated_samples/patch_srv_recordset.py b/sdk/network/azure-mgmt-dns/generated_samples/patch_srv_recordset.py new file mode 100644 index 000000000000..a7c39c5882dd --- /dev/null +++ b/sdk/network/azure-mgmt-dns/generated_samples/patch_srv_recordset.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.dns import DnsManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-dns +# USAGE + python patch_srv_recordset.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 = DnsManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subid", + ) + + response = client.record_sets.update( + resource_group_name="rg1", + zone_name="zone1", + relative_record_set_name="record1", + record_type="SRV", + parameters={"properties": {"metadata": {"key2": "value2"}}}, + ) + print(response) + + +# x-ms-original-file: specification/dns/resource-manager/Microsoft.Network/stable/2018-05-01/examples/PatchSRVRecordset.json +if __name__ == "__main__": + main() diff --git a/sdk/network/azure-mgmt-dns/generated_samples/patch_txt_recordset.py b/sdk/network/azure-mgmt-dns/generated_samples/patch_txt_recordset.py new file mode 100644 index 000000000000..4329574087fe --- /dev/null +++ b/sdk/network/azure-mgmt-dns/generated_samples/patch_txt_recordset.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.dns import DnsManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-dns +# USAGE + python patch_txt_recordset.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 = DnsManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subid", + ) + + response = client.record_sets.update( + resource_group_name="rg1", + zone_name="zone1", + relative_record_set_name="record1", + record_type="TXT", + parameters={"properties": {"metadata": {"key2": "value2"}}}, + ) + print(response) + + +# x-ms-original-file: specification/dns/resource-manager/Microsoft.Network/stable/2018-05-01/examples/PatchTXTRecordset.json +if __name__ == "__main__": + main() diff --git a/sdk/network/azure-mgmt-dns/generated_samples/patch_zone.py b/sdk/network/azure-mgmt-dns/generated_samples/patch_zone.py new file mode 100644 index 000000000000..18522c3e8634 --- /dev/null +++ b/sdk/network/azure-mgmt-dns/generated_samples/patch_zone.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.dns import DnsManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-dns +# USAGE + python patch_zone.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 = DnsManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subid", + ) + + response = client.zones.update( + resource_group_name="rg1", + zone_name="zone1", + parameters={"tags": {"key2": "value2"}}, + ) + print(response) + + +# x-ms-original-file: specification/dns/resource-manager/Microsoft.Network/stable/2018-05-01/examples/PatchZone.json +if __name__ == "__main__": + main()