From 26ad4a64ee4aa28abb533dfd108d103ce8ec5f1a Mon Sep 17 00:00:00 2001 From: SDKAuto Date: Thu, 27 Oct 2022 11:14:33 +0000 Subject: [PATCH] CodeGen from PR 21308 in Azure/azure-rest-api-specs [Hub Generated] Publish private branch 'release-trafficmanager-Microsoft.Network-2022-04-01-preview' (#21308) * Adds base for updating Microsoft.Network from version stable/2018-08-01 to version 2022-04-01-preview * Updates readme * Updates API version in new specs and examples * Add new property AlwaysServer for endpoints. * Fix examples, update swagger to sdk in the readme. * Added a new example for alwaysServe * Use parameters like SubsId and apiVersion from common-types/v3 * Use parameter ResourceGroupNameParameter from common-types/v3 * Use ErrorDetail obj from common-types/v3 and remove CloudErrorObject. * Revert breaking changes: Use ErrorDetail obj from common-types/v3 and remove CloudErrorObject. --- .../azure-mgmt-trafficmanager/_meta.json | 12 +- .../azure/mgmt/trafficmanager/__init__.py | 18 +- .../mgmt/trafficmanager/_configuration.py | 55 +- .../azure/mgmt/trafficmanager/_metadata.json | 106 - .../azure/mgmt/trafficmanager/_patch.py | 2 +- .../mgmt/trafficmanager/_serialization.py | 1970 +++++++++++++++++ .../_traffic_manager_management_client.py | 46 +- .../azure/mgmt/trafficmanager/_vendor.py | 6 +- .../azure/mgmt/trafficmanager/_version.py | 2 +- .../azure/mgmt/trafficmanager/aio/__init__.py | 18 +- .../mgmt/trafficmanager/aio/_configuration.py | 57 +- .../azure/mgmt/trafficmanager/aio/_patch.py | 2 +- .../aio/_traffic_manager_management_client.py | 46 +- .../trafficmanager/aio/operations/__init__.py | 16 +- .../aio/operations/_endpoints_operations.py | 452 +++- .../_geographic_hierarchies_operations.py | 96 +- .../aio/operations/_heat_map_operations.py | 109 +- .../trafficmanager/aio/operations/_patch.py | 20 + .../aio/operations/_profiles_operations.py | 635 ++++-- ...ic_manager_user_metrics_keys_operations.py | 188 +- .../mgmt/trafficmanager/models/__init__.py | 92 +- .../mgmt/trafficmanager/models/_models_py3.py | 560 +++-- .../mgmt/trafficmanager/models/_patch.py | 20 + ...traffic_manager_management_client_enums.py | 53 +- .../trafficmanager/operations/__init__.py | 16 +- .../operations/_endpoints_operations.py | 653 ++++-- .../_geographic_hierarchies_operations.py | 137 +- .../operations/_heat_map_operations.py | 169 +- .../mgmt/trafficmanager/operations/_patch.py | 20 + .../operations/_profiles_operations.py | 955 +++++--- ...ic_manager_user_metrics_keys_operations.py | 319 +-- .../endpoint_delete_external.py | 43 + .../endpoint_get_external_with_geo_mapping.py | 43 + .../endpoint_get_external_with_location.py | 43 + ...dpoint_get_external_with_subnet_mapping.py | 43 + .../endpoint_patch_external_target.py | 49 + ...endpoint_put_external_with_always_serve.py | 53 + ...dpoint_put_external_with_custom_headers.py | 53 + .../endpoint_put_external_with_geo_mapping.py | 52 + .../endpoint_put_external_with_location.py | 52 + ...dpoint_put_external_with_subnet_mapping.py | 52 + .../geographic_hierarchy_getdefault.py | 38 + .../generated_samples/heat_map_get.py | 41 + .../heat_map_get_with_null_values.py | 41 + .../heat_map_get_with_top_left_bot_right.py | 41 + .../generated_samples/list_by_subscription.py | 39 + .../list_profiles_by_resource_group.py | 41 + ...availability_test_name_available_post21.py | 40 + ...lability_test_name_not_available_post23.py | 40 + .../generated_samples/profile_delete.py | 41 + .../profile_get_with_endpoints.py | 41 + .../profile_get_with_traffic_view_disabled.py | 41 + .../profile_get_with_traffic_view_enabled.py | 41 + .../profile_patch_monitor_config.py | 57 + .../profile_put_multi_value.py | 52 + .../profile_put_no_endpoints.py | 50 + .../profile_put_with_aliasing.py | 69 + .../profile_put_with_custom_headers.py | 75 + .../profile_put_with_endpoints.py | 68 + .../profile_put_with_nested_endpoints.py | 85 + ...raffic_manager_user_metrics_keys_delete.py | 38 + .../traffic_manager_user_metrics_keys_get.py | 38 + .../traffic_manager_user_metrics_keys_put.py | 38 + 63 files changed, 6559 insertions(+), 1829 deletions(-) delete mode 100644 sdk/trafficmanager/azure-mgmt-trafficmanager/azure/mgmt/trafficmanager/_metadata.json create mode 100644 sdk/trafficmanager/azure-mgmt-trafficmanager/azure/mgmt/trafficmanager/_serialization.py create mode 100644 sdk/trafficmanager/azure-mgmt-trafficmanager/azure/mgmt/trafficmanager/aio/operations/_patch.py create mode 100644 sdk/trafficmanager/azure-mgmt-trafficmanager/azure/mgmt/trafficmanager/models/_patch.py create mode 100644 sdk/trafficmanager/azure-mgmt-trafficmanager/azure/mgmt/trafficmanager/operations/_patch.py create mode 100644 sdk/trafficmanager/azure-mgmt-trafficmanager/generated_samples/endpoint_delete_external.py create mode 100644 sdk/trafficmanager/azure-mgmt-trafficmanager/generated_samples/endpoint_get_external_with_geo_mapping.py create mode 100644 sdk/trafficmanager/azure-mgmt-trafficmanager/generated_samples/endpoint_get_external_with_location.py create mode 100644 sdk/trafficmanager/azure-mgmt-trafficmanager/generated_samples/endpoint_get_external_with_subnet_mapping.py create mode 100644 sdk/trafficmanager/azure-mgmt-trafficmanager/generated_samples/endpoint_patch_external_target.py create mode 100644 sdk/trafficmanager/azure-mgmt-trafficmanager/generated_samples/endpoint_put_external_with_always_serve.py create mode 100644 sdk/trafficmanager/azure-mgmt-trafficmanager/generated_samples/endpoint_put_external_with_custom_headers.py create mode 100644 sdk/trafficmanager/azure-mgmt-trafficmanager/generated_samples/endpoint_put_external_with_geo_mapping.py create mode 100644 sdk/trafficmanager/azure-mgmt-trafficmanager/generated_samples/endpoint_put_external_with_location.py create mode 100644 sdk/trafficmanager/azure-mgmt-trafficmanager/generated_samples/endpoint_put_external_with_subnet_mapping.py create mode 100644 sdk/trafficmanager/azure-mgmt-trafficmanager/generated_samples/geographic_hierarchy_getdefault.py create mode 100644 sdk/trafficmanager/azure-mgmt-trafficmanager/generated_samples/heat_map_get.py create mode 100644 sdk/trafficmanager/azure-mgmt-trafficmanager/generated_samples/heat_map_get_with_null_values.py create mode 100644 sdk/trafficmanager/azure-mgmt-trafficmanager/generated_samples/heat_map_get_with_top_left_bot_right.py create mode 100644 sdk/trafficmanager/azure-mgmt-trafficmanager/generated_samples/list_by_subscription.py create mode 100644 sdk/trafficmanager/azure-mgmt-trafficmanager/generated_samples/list_profiles_by_resource_group.py create mode 100644 sdk/trafficmanager/azure-mgmt-trafficmanager/generated_samples/name_availability_test_name_available_post21.py create mode 100644 sdk/trafficmanager/azure-mgmt-trafficmanager/generated_samples/name_availability_test_name_not_available_post23.py create mode 100644 sdk/trafficmanager/azure-mgmt-trafficmanager/generated_samples/profile_delete.py create mode 100644 sdk/trafficmanager/azure-mgmt-trafficmanager/generated_samples/profile_get_with_endpoints.py create mode 100644 sdk/trafficmanager/azure-mgmt-trafficmanager/generated_samples/profile_get_with_traffic_view_disabled.py create mode 100644 sdk/trafficmanager/azure-mgmt-trafficmanager/generated_samples/profile_get_with_traffic_view_enabled.py create mode 100644 sdk/trafficmanager/azure-mgmt-trafficmanager/generated_samples/profile_patch_monitor_config.py create mode 100644 sdk/trafficmanager/azure-mgmt-trafficmanager/generated_samples/profile_put_multi_value.py create mode 100644 sdk/trafficmanager/azure-mgmt-trafficmanager/generated_samples/profile_put_no_endpoints.py create mode 100644 sdk/trafficmanager/azure-mgmt-trafficmanager/generated_samples/profile_put_with_aliasing.py create mode 100644 sdk/trafficmanager/azure-mgmt-trafficmanager/generated_samples/profile_put_with_custom_headers.py create mode 100644 sdk/trafficmanager/azure-mgmt-trafficmanager/generated_samples/profile_put_with_endpoints.py create mode 100644 sdk/trafficmanager/azure-mgmt-trafficmanager/generated_samples/profile_put_with_nested_endpoints.py create mode 100644 sdk/trafficmanager/azure-mgmt-trafficmanager/generated_samples/traffic_manager_user_metrics_keys_delete.py create mode 100644 sdk/trafficmanager/azure-mgmt-trafficmanager/generated_samples/traffic_manager_user_metrics_keys_get.py create mode 100644 sdk/trafficmanager/azure-mgmt-trafficmanager/generated_samples/traffic_manager_user_metrics_keys_put.py diff --git a/sdk/trafficmanager/azure-mgmt-trafficmanager/_meta.json b/sdk/trafficmanager/azure-mgmt-trafficmanager/_meta.json index 311921bec638..ce50fd3bc071 100644 --- a/sdk/trafficmanager/azure-mgmt-trafficmanager/_meta.json +++ b/sdk/trafficmanager/azure-mgmt-trafficmanager/_meta.json @@ -1,11 +1,11 @@ { - "autorest": "3.7.2", + "commit": "cf0b8f61c70927094eae34082c66be5ed4e48b86", + "repository_url": "https://github.com/Azure/azure-rest-api-specs", + "autorest": "3.9.2", "use": [ - "@autorest/python@5.12.0", - "@autorest/modelerfour@4.19.3" + "@autorest/python@6.2.1", + "@autorest/modelerfour@4.24.3" ], - "commit": "d72b193573bb076d190e410adfd2bb95b569fbb6", - "repository_url": "https://github.com/Azure/azure-rest-api-specs", - "autorest_command": "autorest specification/trafficmanager/resource-manager/readme.md --multiapi --python --python-mode=update --python-sdks-folder=/home/vsts/work/1/s/azure-sdk-for-python/sdk --python3-only --track2 --use=@autorest/python@5.12.0 --use=@autorest/modelerfour@4.19.3 --version=3.7.2", + "autorest_command": "autorest specification/trafficmanager/resource-manager/readme.md --generate-sample=True --include-x-ms-examples-original-file=True --python --python-sdks-folder=/mnt/vss/_work/1/s/azure-sdk-for-python/sdk --use=@autorest/python@6.2.1 --use=@autorest/modelerfour@4.24.3 --version=3.9.2 --version-tolerant=False", "readme": "specification/trafficmanager/resource-manager/readme.md" } \ No newline at end of file diff --git a/sdk/trafficmanager/azure-mgmt-trafficmanager/azure/mgmt/trafficmanager/__init__.py b/sdk/trafficmanager/azure-mgmt-trafficmanager/azure/mgmt/trafficmanager/__init__.py index 2b47f1508ed6..34c53d4b66b4 100644 --- a/sdk/trafficmanager/azure-mgmt-trafficmanager/azure/mgmt/trafficmanager/__init__.py +++ b/sdk/trafficmanager/azure-mgmt-trafficmanager/azure/mgmt/trafficmanager/__init__.py @@ -10,9 +10,17 @@ from ._version import VERSION __version__ = VERSION -__all__ = ['TrafficManagerManagementClient'] -# `._patch.py` is used for handwritten extensions to the generated code -# Example: https://github.com/Azure/azure-sdk-for-python/blob/main/doc/dev/customize_code/how-to-patch-sdk-code.md -from ._patch import patch_sdk -patch_sdk() +try: + from ._patch import __all__ as _patch_all + from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import +except ImportError: + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "TrafficManagerManagementClient", +] +__all__.extend([p for p in _patch_all if p not in __all__]) + +_patch_sdk() diff --git a/sdk/trafficmanager/azure-mgmt-trafficmanager/azure/mgmt/trafficmanager/_configuration.py b/sdk/trafficmanager/azure-mgmt-trafficmanager/azure/mgmt/trafficmanager/_configuration.py index cf24a6be1a94..b91cb0898220 100644 --- a/sdk/trafficmanager/azure-mgmt-trafficmanager/azure/mgmt/trafficmanager/_configuration.py +++ b/sdk/trafficmanager/azure-mgmt-trafficmanager/azure/mgmt/trafficmanager/_configuration.py @@ -6,6 +6,7 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +import sys from typing import Any, TYPE_CHECKING from azure.core.configuration import Configuration @@ -14,30 +15,35 @@ from ._version import VERSION +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports + if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials import TokenCredential -class TrafficManagerManagementClientConfiguration(Configuration): +class TrafficManagerManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes """Configuration for TrafficManagerManagementClient. 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: Gets subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. + :param subscription_id: The ID of the target subscription. Required. :type subscription_id: str + :keyword api_version: Api Version. Default value is "2022-04-01-preview". Note that overriding + this default value may result in unsupported behavior. + :paramtype api_version: str """ - def __init__( - self, - credential: "TokenCredential", - subscription_id: str, - **kwargs: Any - ) -> None: + def __init__(self, credential: "TokenCredential", subscription_id: str, **kwargs: Any) -> None: super(TrafficManagerManagementClientConfiguration, self).__init__(**kwargs) + api_version = kwargs.pop("api_version", "2022-04-01-preview") # type: Literal["2022-04-01-preview"] + if credential is None: raise ValueError("Parameter 'credential' must not be None.") if subscription_id is None: @@ -45,24 +51,25 @@ def __init__( self.credential = credential self.subscription_id = subscription_id - self.api_version = "2018-08-01" - self.credential_scopes = kwargs.pop('credential_scopes', ['https://management.azure.com/.default']) - kwargs.setdefault('sdk_moniker', 'mgmt-trafficmanager/{}'.format(VERSION)) + self.api_version = api_version + self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "mgmt-trafficmanager/{}".format(VERSION)) self._configure(**kwargs) def _configure( - self, - **kwargs # type: Any + self, **kwargs # type: Any ): # type: (...) -> None - self.user_agent_policy = kwargs.get('user_agent_policy') or policies.UserAgentPolicy(**kwargs) - self.headers_policy = kwargs.get('headers_policy') or policies.HeadersPolicy(**kwargs) - self.proxy_policy = kwargs.get('proxy_policy') or policies.ProxyPolicy(**kwargs) - self.logging_policy = kwargs.get('logging_policy') or policies.NetworkTraceLoggingPolicy(**kwargs) - self.http_logging_policy = kwargs.get('http_logging_policy') or ARMHttpLoggingPolicy(**kwargs) - self.retry_policy = kwargs.get('retry_policy') or policies.RetryPolicy(**kwargs) - self.custom_hook_policy = kwargs.get('custom_hook_policy') or policies.CustomHookPolicy(**kwargs) - self.redirect_policy = kwargs.get('redirect_policy') or policies.RedirectPolicy(**kwargs) - self.authentication_policy = kwargs.get('authentication_policy') + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.RetryPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.RedirectPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") if self.credential and not self.authentication_policy: - self.authentication_policy = ARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs) + self.authentication_policy = ARMChallengeAuthenticationPolicy( + self.credential, *self.credential_scopes, **kwargs + ) diff --git a/sdk/trafficmanager/azure-mgmt-trafficmanager/azure/mgmt/trafficmanager/_metadata.json b/sdk/trafficmanager/azure-mgmt-trafficmanager/azure/mgmt/trafficmanager/_metadata.json deleted file mode 100644 index a1b0830e9a40..000000000000 --- a/sdk/trafficmanager/azure-mgmt-trafficmanager/azure/mgmt/trafficmanager/_metadata.json +++ /dev/null @@ -1,106 +0,0 @@ -{ - "chosen_version": "2018-08-01", - "total_api_version_list": ["2018-08-01"], - "client": { - "name": "TrafficManagerManagementClient", - "filename": "_traffic_manager_management_client", - "description": "TrafficManagerManagementClient.", - "host_value": "\"https://management.azure.com\"", - "parameterized_host_template": null, - "azure_arm": true, - "has_lro_operations": false, - "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\": [\"TrafficManagerManagementClientConfiguration\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}}", - "async_imports": "{\"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"], \"azure.core.credentials\": [\"TokenCredential\"]}}, \"regular\": {\"azurecore\": {\"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"], \"msrest\": [\"Deserializer\", \"Serializer\"], \"azure.mgmt.core\": [\"AsyncARMPipelineClient\"]}, \"local\": {\"._configuration\": [\"TrafficManagerManagementClientConfiguration\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}}" - }, - "global_parameters": { - "sync": { - "credential": { - "signature": "credential, # type: \"TokenCredential\"", - "description": "Credential needed for the client to connect to Azure.", - "docstring_type": "~azure.core.credentials.TokenCredential", - "required": true - }, - "subscription_id": { - "signature": "subscription_id, # type: str", - "description": "Gets subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call.", - "docstring_type": "str", - "required": true - } - }, - "async": { - "credential": { - "signature": "credential: \"AsyncTokenCredential\",", - "description": "Credential needed for the client to connect to Azure.", - "docstring_type": "~azure.core.credentials_async.AsyncTokenCredential", - "required": true - }, - "subscription_id": { - "signature": "subscription_id: str,", - "description": "Gets subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call.", - "docstring_type": "str", - "required": true - } - }, - "constant": { - }, - "call": "credential, subscription_id", - "service_client_specific": { - "sync": { - "api_version": { - "signature": "api_version=None, # type: Optional[str]", - "description": "API version to use if no profile is provided, or if missing in profile.", - "docstring_type": "str", - "required": false - }, - "base_url": { - "signature": "base_url=\"https://management.azure.com\", # type: str", - "description": "Service URL", - "docstring_type": "str", - "required": false - }, - "profile": { - "signature": "profile=KnownProfiles.default, # type: KnownProfiles", - "description": "A profile definition, from KnownProfiles to dict.", - "docstring_type": "azure.profiles.KnownProfiles", - "required": false - } - }, - "async": { - "api_version": { - "signature": "api_version: Optional[str] = None,", - "description": "API version to use if no profile is provided, or if missing in profile.", - "docstring_type": "str", - "required": false - }, - "base_url": { - "signature": "base_url: str = \"https://management.azure.com\",", - "description": "Service URL", - "docstring_type": "str", - "required": false - }, - "profile": { - "signature": "profile: KnownProfiles = KnownProfiles.default,", - "description": "A profile definition, from KnownProfiles to dict.", - "docstring_type": "azure.profiles.KnownProfiles", - "required": false - } - } - } - }, - "config": { - "credential": true, - "credential_scopes": ["https://management.azure.com/.default"], - "credential_call_sync": "ARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs)", - "credential_call_async": "AsyncARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs)", - "sync_imports": "{\"regular\": {\"azurecore\": {\"azure.core.configuration\": [\"Configuration\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMChallengeAuthenticationPolicy\", \"ARMHttpLoggingPolicy\"]}, \"local\": {\"._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", - "async_imports": "{\"regular\": {\"azurecore\": {\"azure.core.configuration\": [\"Configuration\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMHttpLoggingPolicy\", \"AsyncARMChallengeAuthenticationPolicy\"]}, \"local\": {\".._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" - }, - "operation_groups": { - "endpoints": "EndpointsOperations", - "profiles": "ProfilesOperations", - "geographic_hierarchies": "GeographicHierarchiesOperations", - "heat_map": "HeatMapOperations", - "traffic_manager_user_metrics_keys": "TrafficManagerUserMetricsKeysOperations" - } -} \ No newline at end of file diff --git a/sdk/trafficmanager/azure-mgmt-trafficmanager/azure/mgmt/trafficmanager/_patch.py b/sdk/trafficmanager/azure-mgmt-trafficmanager/azure/mgmt/trafficmanager/_patch.py index 74e48ecd07cf..f99e77fef986 100644 --- a/sdk/trafficmanager/azure-mgmt-trafficmanager/azure/mgmt/trafficmanager/_patch.py +++ b/sdk/trafficmanager/azure-mgmt-trafficmanager/azure/mgmt/trafficmanager/_patch.py @@ -28,4 +28,4 @@ # This file is used for handwritten extensions to the generated code. Example: # https://github.com/Azure/azure-sdk-for-python/blob/main/doc/dev/customize_code/how-to-patch-sdk-code.md def patch_sdk(): - pass \ No newline at end of file + pass diff --git a/sdk/trafficmanager/azure-mgmt-trafficmanager/azure/mgmt/trafficmanager/_serialization.py b/sdk/trafficmanager/azure-mgmt-trafficmanager/azure/mgmt/trafficmanager/_serialization.py new file mode 100644 index 000000000000..7c1dedb5133d --- /dev/null +++ b/sdk/trafficmanager/azure-mgmt-trafficmanager/azure/mgmt/trafficmanager/_serialization.py @@ -0,0 +1,1970 @@ +# -------------------------------------------------------------------------- +# +# Copyright (c) Microsoft Corporation. All rights reserved. +# +# The MIT License (MIT) +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the ""Software""), to +# deal in the Software without restriction, including without limitation the +# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +# sell copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +# IN THE SOFTWARE. +# +# -------------------------------------------------------------------------- + +# pylint: skip-file + +from base64 import b64decode, b64encode +import calendar +import datetime +import decimal +import email +from enum import Enum +import json +import logging +import re +import sys +import codecs + +try: + from urllib import quote # type: ignore +except ImportError: + from urllib.parse import quote # type: ignore +import xml.etree.ElementTree as ET + +import isodate + +from typing import Dict, Any, cast, TYPE_CHECKING + +from azure.core.exceptions import DeserializationError, SerializationError, raise_with_traceback + +_BOM = codecs.BOM_UTF8.decode(encoding="utf-8") + +if TYPE_CHECKING: + from typing import Optional, Union, AnyStr, IO, Mapping + + +class RawDeserializer: + + # Accept "text" because we're open minded people... + JSON_REGEXP = re.compile(r"^(application|text)/([a-z+.]+\+)?json$") + + # Name used in context + CONTEXT_NAME = "deserialized_data" + + @classmethod + def deserialize_from_text(cls, data, content_type=None): + # type: (Optional[Union[AnyStr, IO]], Optional[str]) -> Any + """Decode data according to content-type. + + Accept a stream of data as well, but will be load at once in memory for now. + + If no content-type, will return the string version (not bytes, not stream) + + :param data: Input, could be bytes or stream (will be decoded with UTF8) or text + :type data: str or bytes or IO + :param str content_type: The content type. + """ + if hasattr(data, "read"): + # Assume a stream + data = cast(IO, data).read() + + if isinstance(data, bytes): + data_as_str = data.decode(encoding="utf-8-sig") + else: + # Explain to mypy the correct type. + data_as_str = cast(str, data) + + # Remove Byte Order Mark if present in string + data_as_str = data_as_str.lstrip(_BOM) + + if content_type is None: + return data + + if cls.JSON_REGEXP.match(content_type): + try: + return json.loads(data_as_str) + except ValueError as err: + raise DeserializationError("JSON is invalid: {}".format(err), err) + elif "xml" in (content_type or []): + try: + + try: + if isinstance(data, unicode): # type: ignore + # If I'm Python 2.7 and unicode XML will scream if I try a "fromstring" on unicode string + data_as_str = data_as_str.encode(encoding="utf-8") # type: ignore + except NameError: + pass + + return ET.fromstring(data_as_str) # nosec + except ET.ParseError: + # It might be because the server has an issue, and returned JSON with + # content-type XML.... + # So let's try a JSON load, and if it's still broken + # let's flow the initial exception + def _json_attemp(data): + try: + return True, json.loads(data) + except ValueError: + return False, None # Don't care about this one + + success, json_result = _json_attemp(data) + if success: + return json_result + # If i'm here, it's not JSON, it's not XML, let's scream + # and raise the last context in this block (the XML exception) + # The function hack is because Py2.7 messes up with exception + # context otherwise. + _LOGGER.critical("Wasn't XML not JSON, failing") + raise_with_traceback(DeserializationError, "XML is invalid") + raise DeserializationError("Cannot deserialize content-type: {}".format(content_type)) + + @classmethod + def deserialize_from_http_generics(cls, body_bytes, headers): + # type: (Optional[Union[AnyStr, IO]], Mapping) -> Any + """Deserialize from HTTP response. + + Use bytes and headers to NOT use any requests/aiohttp or whatever + specific implementation. + Headers will tested for "content-type" + """ + # Try to use content-type from headers if available + content_type = None + if "content-type" in headers: + content_type = headers["content-type"].split(";")[0].strip().lower() + # Ouch, this server did not declare what it sent... + # Let's guess it's JSON... + # Also, since Autorest was considering that an empty body was a valid JSON, + # need that test as well.... + else: + content_type = "application/json" + + if body_bytes: + return cls.deserialize_from_text(body_bytes, content_type) + return None + + +try: + basestring # type: ignore + unicode_str = unicode # type: ignore +except NameError: + basestring = str # type: ignore + unicode_str = str # type: ignore + +_LOGGER = logging.getLogger(__name__) + +try: + _long_type = long # type: ignore +except NameError: + _long_type = int + + +class UTC(datetime.tzinfo): + """Time Zone info for handling UTC""" + + def utcoffset(self, dt): + """UTF offset for UTC is 0.""" + return datetime.timedelta(0) + + def tzname(self, dt): + """Timestamp representation.""" + return "Z" + + def dst(self, dt): + """No daylight saving for UTC.""" + return datetime.timedelta(hours=1) + + +try: + from datetime import timezone as _FixedOffset +except ImportError: # Python 2.7 + + class _FixedOffset(datetime.tzinfo): # type: ignore + """Fixed offset in minutes east from UTC. + Copy/pasted from Python doc + :param datetime.timedelta offset: offset in timedelta format + """ + + def __init__(self, offset): + self.__offset = offset + + def utcoffset(self, dt): + return self.__offset + + def tzname(self, dt): + return str(self.__offset.total_seconds() / 3600) + + def __repr__(self): + return "".format(self.tzname(None)) + + def dst(self, dt): + return datetime.timedelta(0) + + def __getinitargs__(self): + return (self.__offset,) + + +try: + from datetime import timezone + + TZ_UTC = timezone.utc # type: ignore +except ImportError: + TZ_UTC = UTC() # type: ignore + +_FLATTEN = re.compile(r"(? y, + "minimum": lambda x, y: x < y, + "maximum": lambda x, y: x > y, + "minimum_ex": lambda x, y: x <= y, + "maximum_ex": lambda x, y: x >= y, + "min_items": lambda x, y: len(x) < y, + "max_items": lambda x, y: len(x) > y, + "pattern": lambda x, y: not re.match(y, x, re.UNICODE), + "unique": lambda x, y: len(x) != len(set(x)), + "multiple": lambda x, y: x % y != 0, + } + + def __init__(self, classes=None): + self.serialize_type = { + "iso-8601": Serializer.serialize_iso, + "rfc-1123": Serializer.serialize_rfc, + "unix-time": Serializer.serialize_unix, + "duration": Serializer.serialize_duration, + "date": Serializer.serialize_date, + "time": Serializer.serialize_time, + "decimal": Serializer.serialize_decimal, + "long": Serializer.serialize_long, + "bytearray": Serializer.serialize_bytearray, + "base64": Serializer.serialize_base64, + "object": self.serialize_object, + "[]": self.serialize_iter, + "{}": self.serialize_dict, + } + self.dependencies = dict(classes) if classes else {} + self.key_transformer = full_restapi_key_transformer + self.client_side_validation = True + + def _serialize(self, target_obj, data_type=None, **kwargs): + """Serialize data into a string according to type. + + :param target_obj: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: str, dict + :raises: SerializationError if serialization fails. + """ + key_transformer = kwargs.get("key_transformer", self.key_transformer) + keep_readonly = kwargs.get("keep_readonly", False) + if target_obj is None: + return None + + attr_name = None + class_name = target_obj.__class__.__name__ + + if data_type: + return self.serialize_data(target_obj, data_type, **kwargs) + + if not hasattr(target_obj, "_attribute_map"): + data_type = type(target_obj).__name__ + if data_type in self.basic_types.values(): + return self.serialize_data(target_obj, data_type, **kwargs) + + # Force "is_xml" kwargs if we detect a XML model + try: + is_xml_model_serialization = kwargs["is_xml"] + except KeyError: + is_xml_model_serialization = kwargs.setdefault("is_xml", target_obj.is_xml_model()) + + serialized = {} + if is_xml_model_serialization: + serialized = target_obj._create_xml_node() + try: + attributes = target_obj._attribute_map + for attr, attr_desc in attributes.items(): + attr_name = attr + if not keep_readonly and target_obj._validation.get(attr_name, {}).get("readonly", False): + continue + + if attr_name == "additional_properties" and attr_desc["key"] == "": + if target_obj.additional_properties is not None: + serialized.update(target_obj.additional_properties) + continue + try: + + orig_attr = getattr(target_obj, attr) + if is_xml_model_serialization: + pass # Don't provide "transformer" for XML for now. Keep "orig_attr" + else: # JSON + keys, orig_attr = key_transformer(attr, attr_desc.copy(), orig_attr) + keys = keys if isinstance(keys, list) else [keys] + + kwargs["serialization_ctxt"] = attr_desc + new_attr = self.serialize_data(orig_attr, attr_desc["type"], **kwargs) + + if is_xml_model_serialization: + xml_desc = attr_desc.get("xml", {}) + xml_name = xml_desc.get("name", attr_desc["key"]) + xml_prefix = xml_desc.get("prefix", None) + xml_ns = xml_desc.get("ns", None) + if xml_desc.get("attr", False): + if xml_ns: + ET.register_namespace(xml_prefix, xml_ns) + xml_name = "{}{}".format(xml_ns, xml_name) + serialized.set(xml_name, new_attr) + continue + if xml_desc.get("text", False): + serialized.text = new_attr + continue + if isinstance(new_attr, list): + serialized.extend(new_attr) + elif isinstance(new_attr, ET.Element): + # If the down XML has no XML/Name, we MUST replace the tag with the local tag. But keeping the namespaces. + if "name" not in getattr(orig_attr, "_xml_map", {}): + splitted_tag = new_attr.tag.split("}") + if len(splitted_tag) == 2: # Namespace + new_attr.tag = "}".join([splitted_tag[0], xml_name]) + else: + new_attr.tag = xml_name + serialized.append(new_attr) + else: # That's a basic type + # Integrate namespace if necessary + local_node = _create_xml_node(xml_name, xml_prefix, xml_ns) + local_node.text = unicode_str(new_attr) + serialized.append(local_node) + else: # JSON + for k in reversed(keys): + unflattened = {k: new_attr} + new_attr = unflattened + + _new_attr = new_attr + _serialized = serialized + for k in keys: + if k not in _serialized: + _serialized.update(_new_attr) + _new_attr = _new_attr[k] + _serialized = _serialized[k] + except ValueError: + continue + + except (AttributeError, KeyError, TypeError) as err: + msg = "Attribute {} in object {} cannot be serialized.\n{}".format(attr_name, class_name, str(target_obj)) + raise_with_traceback(SerializationError, msg, err) + else: + return serialized + + def body(self, data, data_type, **kwargs): + """Serialize data intended for a request body. + + :param data: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: dict + :raises: SerializationError if serialization fails. + :raises: ValueError if data is None + """ + + # Just in case this is a dict + internal_data_type = data_type.strip("[]{}") + internal_data_type = self.dependencies.get(internal_data_type, None) + try: + is_xml_model_serialization = kwargs["is_xml"] + except KeyError: + if internal_data_type and issubclass(internal_data_type, Model): + is_xml_model_serialization = kwargs.setdefault("is_xml", internal_data_type.is_xml_model()) + else: + is_xml_model_serialization = False + if internal_data_type and not isinstance(internal_data_type, Enum): + try: + deserializer = Deserializer(self.dependencies) + # Since it's on serialization, it's almost sure that format is not JSON REST + # We're not able to deal with additional properties for now. + deserializer.additional_properties_detection = False + if is_xml_model_serialization: + deserializer.key_extractors = [ + attribute_key_case_insensitive_extractor, + ] + else: + deserializer.key_extractors = [ + rest_key_case_insensitive_extractor, + attribute_key_case_insensitive_extractor, + last_rest_key_case_insensitive_extractor, + ] + data = deserializer._deserialize(data_type, data) + except DeserializationError as err: + raise_with_traceback(SerializationError, "Unable to build a model: " + str(err), err) + + return self._serialize(data, data_type, **kwargs) + + def url(self, name, data, data_type, **kwargs): + """Serialize data intended for a URL path. + + :param data: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: str + :raises: TypeError if serialization fails. + :raises: ValueError if data is None + """ + try: + output = self.serialize_data(data, data_type, **kwargs) + if data_type == "bool": + output = json.dumps(output) + + if kwargs.get("skip_quote") is True: + output = str(output) + else: + output = quote(str(output), safe="") + except SerializationError: + raise TypeError("{} must be type {}.".format(name, data_type)) + else: + return output + + def query(self, name, data, data_type, **kwargs): + """Serialize data intended for a URL query. + + :param data: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: str + :raises: TypeError if serialization fails. + :raises: ValueError if data is None + """ + try: + # Treat the list aside, since we don't want to encode the div separator + if data_type.startswith("["): + internal_data_type = data_type[1:-1] + data = [self.serialize_data(d, internal_data_type, **kwargs) if d is not None else "" for d in data] + if not kwargs.get("skip_quote", False): + data = [quote(str(d), safe="") for d in data] + return str(self.serialize_iter(data, internal_data_type, **kwargs)) + + # Not a list, regular serialization + output = self.serialize_data(data, data_type, **kwargs) + if data_type == "bool": + output = json.dumps(output) + if kwargs.get("skip_quote") is True: + output = str(output) + else: + output = quote(str(output), safe="") + except SerializationError: + raise TypeError("{} must be type {}.".format(name, data_type)) + else: + return str(output) + + def header(self, name, data, data_type, **kwargs): + """Serialize data intended for a request header. + + :param data: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: str + :raises: TypeError if serialization fails. + :raises: ValueError if data is None + """ + try: + if data_type in ["[str]"]: + data = ["" if d is None else d for d in data] + + output = self.serialize_data(data, data_type, **kwargs) + if data_type == "bool": + output = json.dumps(output) + except SerializationError: + raise TypeError("{} must be type {}.".format(name, data_type)) + else: + return str(output) + + def serialize_data(self, data, data_type, **kwargs): + """Serialize generic data according to supplied data type. + + :param data: The data to be serialized. + :param str data_type: The type to be serialized from. + :param bool required: Whether it's essential that the data not be + empty or None + :raises: AttributeError if required data is None. + :raises: ValueError if data is None + :raises: SerializationError if serialization fails. + """ + if data is None: + raise ValueError("No value for given attribute") + + try: + if data_type in self.basic_types.values(): + return self.serialize_basic(data, data_type, **kwargs) + + elif data_type in self.serialize_type: + return self.serialize_type[data_type](data, **kwargs) + + # If dependencies is empty, try with current data class + # It has to be a subclass of Enum anyway + enum_type = self.dependencies.get(data_type, data.__class__) + if issubclass(enum_type, Enum): + return Serializer.serialize_enum(data, enum_obj=enum_type) + + iter_type = data_type[0] + data_type[-1] + if iter_type in self.serialize_type: + return self.serialize_type[iter_type](data, data_type[1:-1], **kwargs) + + except (ValueError, TypeError) as err: + msg = "Unable to serialize value: {!r} as type: {!r}." + raise_with_traceback(SerializationError, msg.format(data, data_type), err) + else: + return self._serialize(data, **kwargs) + + @classmethod + def _get_custom_serializers(cls, data_type, **kwargs): + custom_serializer = kwargs.get("basic_types_serializers", {}).get(data_type) + if custom_serializer: + return custom_serializer + if kwargs.get("is_xml", False): + return cls._xml_basic_types_serializers.get(data_type) + + @classmethod + def serialize_basic(cls, data, data_type, **kwargs): + """Serialize basic builting data type. + Serializes objects to str, int, float or bool. + + Possible kwargs: + - basic_types_serializers dict[str, callable] : If set, use the callable as serializer + - is_xml bool : If set, use xml_basic_types_serializers + + :param data: Object to be serialized. + :param str data_type: Type of object in the iterable. + """ + custom_serializer = cls._get_custom_serializers(data_type, **kwargs) + if custom_serializer: + return custom_serializer(data) + if data_type == "str": + return cls.serialize_unicode(data) + return eval(data_type)(data) # nosec + + @classmethod + def serialize_unicode(cls, data): + """Special handling for serializing unicode strings in Py2. + Encode to UTF-8 if unicode, otherwise handle as a str. + + :param data: Object to be serialized. + :rtype: str + """ + try: # If I received an enum, return its value + return data.value + except AttributeError: + pass + + try: + if isinstance(data, unicode): + # Don't change it, JSON and XML ElementTree are totally able + # to serialize correctly u'' strings + return data + except NameError: + return str(data) + else: + return str(data) + + def serialize_iter(self, data, iter_type, div=None, **kwargs): + """Serialize iterable. + + Supported kwargs: + - serialization_ctxt dict : The current entry of _attribute_map, or same format. + serialization_ctxt['type'] should be same as data_type. + - is_xml bool : If set, serialize as XML + + :param list attr: Object to be serialized. + :param str iter_type: Type of object in the iterable. + :param bool required: Whether the objects in the iterable must + not be None or empty. + :param str div: If set, this str will be used to combine the elements + in the iterable into a combined string. Default is 'None'. + :rtype: list, str + """ + if isinstance(data, str): + raise SerializationError("Refuse str type as a valid iter type.") + + serialization_ctxt = kwargs.get("serialization_ctxt", {}) + is_xml = kwargs.get("is_xml", False) + + serialized = [] + for d in data: + try: + serialized.append(self.serialize_data(d, iter_type, **kwargs)) + except ValueError: + serialized.append(None) + + if div: + serialized = ["" if s is None else str(s) for s in serialized] + serialized = div.join(serialized) + + if "xml" in serialization_ctxt or is_xml: + # XML serialization is more complicated + xml_desc = serialization_ctxt.get("xml", {}) + xml_name = xml_desc.get("name") + if not xml_name: + xml_name = serialization_ctxt["key"] + + # Create a wrap node if necessary (use the fact that Element and list have "append") + is_wrapped = xml_desc.get("wrapped", False) + node_name = xml_desc.get("itemsName", xml_name) + if is_wrapped: + final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) + else: + final_result = [] + # All list elements to "local_node" + for el in serialized: + if isinstance(el, ET.Element): + el_node = el + else: + el_node = _create_xml_node(node_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) + if el is not None: # Otherwise it writes "None" :-p + el_node.text = str(el) + final_result.append(el_node) + return final_result + return serialized + + def serialize_dict(self, attr, dict_type, **kwargs): + """Serialize a dictionary of objects. + + :param dict attr: Object to be serialized. + :param str dict_type: Type of object in the dictionary. + :param bool required: Whether the objects in the dictionary must + not be None or empty. + :rtype: dict + """ + serialization_ctxt = kwargs.get("serialization_ctxt", {}) + serialized = {} + for key, value in attr.items(): + try: + serialized[self.serialize_unicode(key)] = self.serialize_data(value, dict_type, **kwargs) + except ValueError: + serialized[self.serialize_unicode(key)] = None + + if "xml" in serialization_ctxt: + # XML serialization is more complicated + xml_desc = serialization_ctxt["xml"] + xml_name = xml_desc["name"] + + final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) + for key, value in serialized.items(): + ET.SubElement(final_result, key).text = value + return final_result + + return serialized + + def serialize_object(self, attr, **kwargs): + """Serialize a generic object. + This will be handled as a dictionary. If object passed in is not + a basic type (str, int, float, dict, list) it will simply be + cast to str. + + :param dict attr: Object to be serialized. + :rtype: dict or str + """ + if attr is None: + return None + if isinstance(attr, ET.Element): + return attr + obj_type = type(attr) + if obj_type in self.basic_types: + return self.serialize_basic(attr, self.basic_types[obj_type], **kwargs) + if obj_type is _long_type: + return self.serialize_long(attr) + if obj_type is unicode_str: + return self.serialize_unicode(attr) + if obj_type is datetime.datetime: + return self.serialize_iso(attr) + if obj_type is datetime.date: + return self.serialize_date(attr) + if obj_type is datetime.time: + return self.serialize_time(attr) + if obj_type is datetime.timedelta: + return self.serialize_duration(attr) + if obj_type is decimal.Decimal: + return self.serialize_decimal(attr) + + # If it's a model or I know this dependency, serialize as a Model + elif obj_type in self.dependencies.values() or isinstance(attr, Model): + return self._serialize(attr) + + if obj_type == dict: + serialized = {} + for key, value in attr.items(): + try: + serialized[self.serialize_unicode(key)] = self.serialize_object(value, **kwargs) + except ValueError: + serialized[self.serialize_unicode(key)] = None + return serialized + + if obj_type == list: + serialized = [] + for obj in attr: + try: + serialized.append(self.serialize_object(obj, **kwargs)) + except ValueError: + pass + return serialized + return str(attr) + + @staticmethod + def serialize_enum(attr, enum_obj=None): + try: + result = attr.value + except AttributeError: + result = attr + try: + enum_obj(result) + return result + except ValueError: + for enum_value in enum_obj: + if enum_value.value.lower() == str(attr).lower(): + return enum_value.value + error = "{!r} is not valid value for enum {!r}" + raise SerializationError(error.format(attr, enum_obj)) + + @staticmethod + def serialize_bytearray(attr, **kwargs): + """Serialize bytearray into base-64 string. + + :param attr: Object to be serialized. + :rtype: str + """ + return b64encode(attr).decode() + + @staticmethod + def serialize_base64(attr, **kwargs): + """Serialize str into base-64 string. + + :param attr: Object to be serialized. + :rtype: str + """ + encoded = b64encode(attr).decode("ascii") + return encoded.strip("=").replace("+", "-").replace("/", "_") + + @staticmethod + def serialize_decimal(attr, **kwargs): + """Serialize Decimal object to float. + + :param attr: Object to be serialized. + :rtype: float + """ + return float(attr) + + @staticmethod + def serialize_long(attr, **kwargs): + """Serialize long (Py2) or int (Py3). + + :param attr: Object to be serialized. + :rtype: int/long + """ + return _long_type(attr) + + @staticmethod + def serialize_date(attr, **kwargs): + """Serialize Date object into ISO-8601 formatted string. + + :param Date attr: Object to be serialized. + :rtype: str + """ + if isinstance(attr, str): + attr = isodate.parse_date(attr) + t = "{:04}-{:02}-{:02}".format(attr.year, attr.month, attr.day) + return t + + @staticmethod + def serialize_time(attr, **kwargs): + """Serialize Time object into ISO-8601 formatted string. + + :param datetime.time attr: Object to be serialized. + :rtype: str + """ + if isinstance(attr, str): + attr = isodate.parse_time(attr) + t = "{:02}:{:02}:{:02}".format(attr.hour, attr.minute, attr.second) + if attr.microsecond: + t += ".{:02}".format(attr.microsecond) + return t + + @staticmethod + def serialize_duration(attr, **kwargs): + """Serialize TimeDelta object into ISO-8601 formatted string. + + :param TimeDelta attr: Object to be serialized. + :rtype: str + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + return isodate.duration_isoformat(attr) + + @staticmethod + def serialize_rfc(attr, **kwargs): + """Serialize Datetime object into RFC-1123 formatted string. + + :param Datetime attr: Object to be serialized. + :rtype: str + :raises: TypeError if format invalid. + """ + try: + if not attr.tzinfo: + _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") + utc = attr.utctimetuple() + except AttributeError: + raise TypeError("RFC1123 object must be valid Datetime object.") + + return "{}, {:02} {} {:04} {:02}:{:02}:{:02} GMT".format( + Serializer.days[utc.tm_wday], + utc.tm_mday, + Serializer.months[utc.tm_mon], + utc.tm_year, + utc.tm_hour, + utc.tm_min, + utc.tm_sec, + ) + + @staticmethod + def serialize_iso(attr, **kwargs): + """Serialize Datetime object into ISO-8601 formatted string. + + :param Datetime attr: Object to be serialized. + :rtype: str + :raises: SerializationError if format invalid. + """ + if isinstance(attr, str): + attr = isodate.parse_datetime(attr) + try: + if not attr.tzinfo: + _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") + utc = attr.utctimetuple() + if utc.tm_year > 9999 or utc.tm_year < 1: + raise OverflowError("Hit max or min date") + + microseconds = str(attr.microsecond).rjust(6, "0").rstrip("0").ljust(3, "0") + if microseconds: + microseconds = "." + microseconds + date = "{:04}-{:02}-{:02}T{:02}:{:02}:{:02}".format( + utc.tm_year, utc.tm_mon, utc.tm_mday, utc.tm_hour, utc.tm_min, utc.tm_sec + ) + return date + microseconds + "Z" + except (ValueError, OverflowError) as err: + msg = "Unable to serialize datetime object." + raise_with_traceback(SerializationError, msg, err) + except AttributeError as err: + msg = "ISO-8601 object must be valid Datetime object." + raise_with_traceback(TypeError, msg, err) + + @staticmethod + def serialize_unix(attr, **kwargs): + """Serialize Datetime object into IntTime format. + This is represented as seconds. + + :param Datetime attr: Object to be serialized. + :rtype: int + :raises: SerializationError if format invalid + """ + if isinstance(attr, int): + return attr + try: + if not attr.tzinfo: + _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") + return int(calendar.timegm(attr.utctimetuple())) + except AttributeError: + raise TypeError("Unix time object must be valid Datetime object.") + + +def rest_key_extractor(attr, attr_desc, data): + key = attr_desc["key"] + working_data = data + + while "." in key: + dict_keys = _FLATTEN.split(key) + if len(dict_keys) == 1: + key = _decode_attribute_map_key(dict_keys[0]) + break + working_key = _decode_attribute_map_key(dict_keys[0]) + working_data = working_data.get(working_key, data) + if working_data is None: + # If at any point while following flatten JSON path see None, it means + # that all properties under are None as well + # https://github.com/Azure/msrest-for-python/issues/197 + return None + key = ".".join(dict_keys[1:]) + + return working_data.get(key) + + +def rest_key_case_insensitive_extractor(attr, attr_desc, data): + key = attr_desc["key"] + working_data = data + + while "." in key: + dict_keys = _FLATTEN.split(key) + if len(dict_keys) == 1: + key = _decode_attribute_map_key(dict_keys[0]) + break + working_key = _decode_attribute_map_key(dict_keys[0]) + working_data = attribute_key_case_insensitive_extractor(working_key, None, working_data) + if working_data is None: + # If at any point while following flatten JSON path see None, it means + # that all properties under are None as well + # https://github.com/Azure/msrest-for-python/issues/197 + return None + key = ".".join(dict_keys[1:]) + + if working_data: + return attribute_key_case_insensitive_extractor(key, None, working_data) + + +def last_rest_key_extractor(attr, attr_desc, data): + """Extract the attribute in "data" based on the last part of the JSON path key.""" + key = attr_desc["key"] + dict_keys = _FLATTEN.split(key) + return attribute_key_extractor(dict_keys[-1], None, data) + + +def last_rest_key_case_insensitive_extractor(attr, attr_desc, data): + """Extract the attribute in "data" based on the last part of the JSON path key. + + This is the case insensitive version of "last_rest_key_extractor" + """ + key = attr_desc["key"] + dict_keys = _FLATTEN.split(key) + return attribute_key_case_insensitive_extractor(dict_keys[-1], None, data) + + +def attribute_key_extractor(attr, _, data): + return data.get(attr) + + +def attribute_key_case_insensitive_extractor(attr, _, data): + found_key = None + lower_attr = attr.lower() + for key in data: + if lower_attr == key.lower(): + found_key = key + break + + return data.get(found_key) + + +def _extract_name_from_internal_type(internal_type): + """Given an internal type XML description, extract correct XML name with namespace. + + :param dict internal_type: An model type + :rtype: tuple + :returns: A tuple XML name + namespace dict + """ + internal_type_xml_map = getattr(internal_type, "_xml_map", {}) + xml_name = internal_type_xml_map.get("name", internal_type.__name__) + xml_ns = internal_type_xml_map.get("ns", None) + if xml_ns: + xml_name = "{}{}".format(xml_ns, xml_name) + return xml_name + + +def xml_key_extractor(attr, attr_desc, data): + if isinstance(data, dict): + return None + + # Test if this model is XML ready first + if not isinstance(data, ET.Element): + return None + + xml_desc = attr_desc.get("xml", {}) + xml_name = xml_desc.get("name", attr_desc["key"]) + + # Look for a children + is_iter_type = attr_desc["type"].startswith("[") + is_wrapped = xml_desc.get("wrapped", False) + internal_type = attr_desc.get("internalType", None) + internal_type_xml_map = getattr(internal_type, "_xml_map", {}) + + # Integrate namespace if necessary + xml_ns = xml_desc.get("ns", internal_type_xml_map.get("ns", None)) + if xml_ns: + xml_name = "{}{}".format(xml_ns, xml_name) + + # If it's an attribute, that's simple + if xml_desc.get("attr", False): + return data.get(xml_name) + + # If it's x-ms-text, that's simple too + if xml_desc.get("text", False): + return data.text + + # Scenario where I take the local name: + # - Wrapped node + # - Internal type is an enum (considered basic types) + # - Internal type has no XML/Name node + if is_wrapped or (internal_type and (issubclass(internal_type, Enum) or "name" not in internal_type_xml_map)): + children = data.findall(xml_name) + # If internal type has a local name and it's not a list, I use that name + elif not is_iter_type and internal_type and "name" in internal_type_xml_map: + xml_name = _extract_name_from_internal_type(internal_type) + children = data.findall(xml_name) + # That's an array + else: + if internal_type: # Complex type, ignore itemsName and use the complex type name + items_name = _extract_name_from_internal_type(internal_type) + else: + items_name = xml_desc.get("itemsName", xml_name) + children = data.findall(items_name) + + if len(children) == 0: + if is_iter_type: + if is_wrapped: + return None # is_wrapped no node, we want None + else: + return [] # not wrapped, assume empty list + return None # Assume it's not there, maybe an optional node. + + # If is_iter_type and not wrapped, return all found children + if is_iter_type: + if not is_wrapped: + return children + else: # Iter and wrapped, should have found one node only (the wrap one) + if len(children) != 1: + raise DeserializationError( + "Tried to deserialize an array not wrapped, and found several nodes '{}'. Maybe you should declare this array as wrapped?".format( + xml_name + ) + ) + return list(children[0]) # Might be empty list and that's ok. + + # Here it's not a itertype, we should have found one element only or empty + if len(children) > 1: + raise DeserializationError("Find several XML '{}' where it was not expected".format(xml_name)) + return children[0] + + +class Deserializer(object): + """Response object model deserializer. + + :param dict classes: Class type dictionary for deserializing complex types. + :ivar list key_extractors: Ordered list of extractors to be used by this deserializer. + """ + + basic_types = {str: "str", int: "int", bool: "bool", float: "float"} + + valid_date = re.compile(r"\d{4}[-]\d{2}[-]\d{2}T\d{2}:\d{2}:\d{2}" r"\.?\d*Z?[-+]?[\d{2}]?:?[\d{2}]?") + + def __init__(self, classes=None): + self.deserialize_type = { + "iso-8601": Deserializer.deserialize_iso, + "rfc-1123": Deserializer.deserialize_rfc, + "unix-time": Deserializer.deserialize_unix, + "duration": Deserializer.deserialize_duration, + "date": Deserializer.deserialize_date, + "time": Deserializer.deserialize_time, + "decimal": Deserializer.deserialize_decimal, + "long": Deserializer.deserialize_long, + "bytearray": Deserializer.deserialize_bytearray, + "base64": Deserializer.deserialize_base64, + "object": self.deserialize_object, + "[]": self.deserialize_iter, + "{}": self.deserialize_dict, + } + self.deserialize_expected_types = { + "duration": (isodate.Duration, datetime.timedelta), + "iso-8601": (datetime.datetime), + } + self.dependencies = dict(classes) if classes else {} + self.key_extractors = [rest_key_extractor, xml_key_extractor] + # Additional properties only works if the "rest_key_extractor" is used to + # extract the keys. Making it to work whatever the key extractor is too much + # complicated, with no real scenario for now. + # So adding a flag to disable additional properties detection. This flag should be + # used if your expect the deserialization to NOT come from a JSON REST syntax. + # Otherwise, result are unexpected + self.additional_properties_detection = True + + def __call__(self, target_obj, response_data, content_type=None): + """Call the deserializer to process a REST response. + + :param str target_obj: Target data type to deserialize to. + :param requests.Response response_data: REST response object. + :param str content_type: Swagger "produces" if available. + :raises: DeserializationError if deserialization fails. + :return: Deserialized object. + """ + data = self._unpack_content(response_data, content_type) + return self._deserialize(target_obj, data) + + def _deserialize(self, target_obj, data): + """Call the deserializer on a model. + + Data needs to be already deserialized as JSON or XML ElementTree + + :param str target_obj: Target data type to deserialize to. + :param object data: Object to deserialize. + :raises: DeserializationError if deserialization fails. + :return: Deserialized object. + """ + # This is already a model, go recursive just in case + if hasattr(data, "_attribute_map"): + constants = [name for name, config in getattr(data, "_validation", {}).items() if config.get("constant")] + try: + for attr, mapconfig in data._attribute_map.items(): + if attr in constants: + continue + value = getattr(data, attr) + if value is None: + continue + local_type = mapconfig["type"] + internal_data_type = local_type.strip("[]{}") + if internal_data_type not in self.dependencies or isinstance(internal_data_type, Enum): + continue + setattr(data, attr, self._deserialize(local_type, value)) + return data + except AttributeError: + return + + response, class_name = self._classify_target(target_obj, data) + + if isinstance(response, basestring): + return self.deserialize_data(data, response) + elif isinstance(response, type) and issubclass(response, Enum): + return self.deserialize_enum(data, response) + + if data is None: + return data + try: + attributes = response._attribute_map + d_attrs = {} + for attr, attr_desc in attributes.items(): + # Check empty string. If it's not empty, someone has a real "additionalProperties"... + if attr == "additional_properties" and attr_desc["key"] == "": + continue + raw_value = None + # Enhance attr_desc with some dynamic data + attr_desc = attr_desc.copy() # Do a copy, do not change the real one + internal_data_type = attr_desc["type"].strip("[]{}") + if internal_data_type in self.dependencies: + attr_desc["internalType"] = self.dependencies[internal_data_type] + + for key_extractor in self.key_extractors: + found_value = key_extractor(attr, attr_desc, data) + if found_value is not None: + if raw_value is not None and raw_value != found_value: + msg = ( + "Ignoring extracted value '%s' from %s for key '%s'" + " (duplicate extraction, follow extractors order)" + ) + _LOGGER.warning(msg, found_value, key_extractor, attr) + continue + raw_value = found_value + + value = self.deserialize_data(raw_value, attr_desc["type"]) + d_attrs[attr] = value + except (AttributeError, TypeError, KeyError) as err: + msg = "Unable to deserialize to object: " + class_name + raise_with_traceback(DeserializationError, msg, err) + else: + additional_properties = self._build_additional_properties(attributes, data) + return self._instantiate_model(response, d_attrs, additional_properties) + + def _build_additional_properties(self, attribute_map, data): + if not self.additional_properties_detection: + return None + if "additional_properties" in attribute_map and attribute_map.get("additional_properties", {}).get("key") != "": + # Check empty string. If it's not empty, someone has a real "additionalProperties" + return None + if isinstance(data, ET.Element): + data = {el.tag: el.text for el in data} + + known_keys = { + _decode_attribute_map_key(_FLATTEN.split(desc["key"])[0]) + for desc in attribute_map.values() + if desc["key"] != "" + } + present_keys = set(data.keys()) + missing_keys = present_keys - known_keys + return {key: data[key] for key in missing_keys} + + def _classify_target(self, target, data): + """Check to see whether the deserialization target object can + be classified into a subclass. + Once classification has been determined, initialize object. + + :param str target: The target object type to deserialize to. + :param str/dict data: The response data to deseralize. + """ + if target is None: + return None, None + + if isinstance(target, basestring): + try: + target = self.dependencies[target] + except KeyError: + return target, target + + try: + target = target._classify(data, self.dependencies) + except AttributeError: + pass # Target is not a Model, no classify + return target, target.__class__.__name__ + + def failsafe_deserialize(self, target_obj, data, content_type=None): + """Ignores any errors encountered in deserialization, + and falls back to not deserializing the object. Recommended + for use in error deserialization, as we want to return the + HttpResponseError to users, and not have them deal with + a deserialization error. + + :param str target_obj: The target object type to deserialize to. + :param str/dict data: The response data to deseralize. + :param str content_type: Swagger "produces" if available. + """ + try: + return self(target_obj, data, content_type=content_type) + except: + _LOGGER.debug( + "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True + ) + return None + + @staticmethod + def _unpack_content(raw_data, content_type=None): + """Extract the correct structure for deserialization. + + If raw_data is a PipelineResponse, try to extract the result of RawDeserializer. + if we can't, raise. Your Pipeline should have a RawDeserializer. + + If not a pipeline response and raw_data is bytes or string, use content-type + to decode it. If no content-type, try JSON. + + If raw_data is something else, bypass all logic and return it directly. + + :param raw_data: Data to be processed. + :param content_type: How to parse if raw_data is a string/bytes. + :raises JSONDecodeError: If JSON is requested and parsing is impossible. + :raises UnicodeDecodeError: If bytes is not UTF8 + """ + # Assume this is enough to detect a Pipeline Response without importing it + context = getattr(raw_data, "context", {}) + if context: + if RawDeserializer.CONTEXT_NAME in context: + return context[RawDeserializer.CONTEXT_NAME] + raise ValueError("This pipeline didn't have the RawDeserializer policy; can't deserialize") + + # Assume this is enough to recognize universal_http.ClientResponse without importing it + if hasattr(raw_data, "body"): + return RawDeserializer.deserialize_from_http_generics(raw_data.text(), raw_data.headers) + + # Assume this enough to recognize requests.Response without importing it. + if hasattr(raw_data, "_content_consumed"): + return RawDeserializer.deserialize_from_http_generics(raw_data.text, raw_data.headers) + + if isinstance(raw_data, (basestring, bytes)) or hasattr(raw_data, "read"): + return RawDeserializer.deserialize_from_text(raw_data, content_type) + return raw_data + + def _instantiate_model(self, response, attrs, additional_properties=None): + """Instantiate a response model passing in deserialized args. + + :param response: The response model class. + :param d_attrs: The deserialized response attributes. + """ + if callable(response): + subtype = getattr(response, "_subtype_map", {}) + try: + readonly = [k for k, v in response._validation.items() if v.get("readonly")] + const = [k for k, v in response._validation.items() if v.get("constant")] + kwargs = {k: v for k, v in attrs.items() if k not in subtype and k not in readonly + const} + response_obj = response(**kwargs) + for attr in readonly: + setattr(response_obj, attr, attrs.get(attr)) + if additional_properties: + response_obj.additional_properties = additional_properties + return response_obj + except TypeError as err: + msg = "Unable to deserialize {} into model {}. ".format(kwargs, response) + raise DeserializationError(msg + str(err)) + else: + try: + for attr, value in attrs.items(): + setattr(response, attr, value) + return response + except Exception as exp: + msg = "Unable to populate response model. " + msg += "Type: {}, Error: {}".format(type(response), exp) + raise DeserializationError(msg) + + def deserialize_data(self, data, data_type): + """Process data for deserialization according to data type. + + :param str data: The response string to be deserialized. + :param str data_type: The type to deserialize to. + :raises: DeserializationError if deserialization fails. + :return: Deserialized object. + """ + if data is None: + return data + + try: + if not data_type: + return data + if data_type in self.basic_types.values(): + return self.deserialize_basic(data, data_type) + if data_type in self.deserialize_type: + if isinstance(data, self.deserialize_expected_types.get(data_type, tuple())): + return data + + is_a_text_parsing_type = lambda x: x not in ["object", "[]", r"{}"] + if isinstance(data, ET.Element) and is_a_text_parsing_type(data_type) and not data.text: + return None + data_val = self.deserialize_type[data_type](data) + return data_val + + iter_type = data_type[0] + data_type[-1] + if iter_type in self.deserialize_type: + return self.deserialize_type[iter_type](data, data_type[1:-1]) + + obj_type = self.dependencies[data_type] + if issubclass(obj_type, Enum): + if isinstance(data, ET.Element): + data = data.text + return self.deserialize_enum(data, obj_type) + + except (ValueError, TypeError, AttributeError) as err: + msg = "Unable to deserialize response data." + msg += " Data: {}, {}".format(data, data_type) + raise_with_traceback(DeserializationError, msg, err) + else: + return self._deserialize(obj_type, data) + + def deserialize_iter(self, attr, iter_type): + """Deserialize an iterable. + + :param list attr: Iterable to be deserialized. + :param str iter_type: The type of object in the iterable. + :rtype: list + """ + if attr is None: + return None + if isinstance(attr, ET.Element): # If I receive an element here, get the children + attr = list(attr) + if not isinstance(attr, (list, set)): + raise DeserializationError("Cannot deserialize as [{}] an object of type {}".format(iter_type, type(attr))) + return [self.deserialize_data(a, iter_type) for a in attr] + + def deserialize_dict(self, attr, dict_type): + """Deserialize a dictionary. + + :param dict/list attr: Dictionary to be deserialized. Also accepts + a list of key, value pairs. + :param str dict_type: The object type of the items in the dictionary. + :rtype: dict + """ + if isinstance(attr, list): + return {x["key"]: self.deserialize_data(x["value"], dict_type) for x in attr} + + if isinstance(attr, ET.Element): + # Transform value into {"Key": "value"} + attr = {el.tag: el.text for el in attr} + return {k: self.deserialize_data(v, dict_type) for k, v in attr.items()} + + def deserialize_object(self, attr, **kwargs): + """Deserialize a generic object. + This will be handled as a dictionary. + + :param dict attr: Dictionary to be deserialized. + :rtype: dict + :raises: TypeError if non-builtin datatype encountered. + """ + if attr is None: + return None + if isinstance(attr, ET.Element): + # Do no recurse on XML, just return the tree as-is + return attr + if isinstance(attr, basestring): + return self.deserialize_basic(attr, "str") + obj_type = type(attr) + if obj_type in self.basic_types: + return self.deserialize_basic(attr, self.basic_types[obj_type]) + if obj_type is _long_type: + return self.deserialize_long(attr) + + if obj_type == dict: + deserialized = {} + for key, value in attr.items(): + try: + deserialized[key] = self.deserialize_object(value, **kwargs) + except ValueError: + deserialized[key] = None + return deserialized + + if obj_type == list: + deserialized = [] + for obj in attr: + try: + deserialized.append(self.deserialize_object(obj, **kwargs)) + except ValueError: + pass + return deserialized + + else: + error = "Cannot deserialize generic object with type: " + raise TypeError(error + str(obj_type)) + + def deserialize_basic(self, attr, data_type): + """Deserialize basic builtin data type from string. + Will attempt to convert to str, int, float and bool. + This function will also accept '1', '0', 'true' and 'false' as + valid bool values. + + :param str attr: response string to be deserialized. + :param str data_type: deserialization data type. + :rtype: str, int, float or bool + :raises: TypeError if string format is not valid. + """ + # If we're here, data is supposed to be a basic type. + # If it's still an XML node, take the text + if isinstance(attr, ET.Element): + attr = attr.text + if not attr: + if data_type == "str": + # None or '', node is empty string. + return "" + else: + # None or '', node with a strong type is None. + # Don't try to model "empty bool" or "empty int" + return None + + if data_type == "bool": + if attr in [True, False, 1, 0]: + return bool(attr) + elif isinstance(attr, basestring): + if attr.lower() in ["true", "1"]: + return True + elif attr.lower() in ["false", "0"]: + return False + raise TypeError("Invalid boolean value: {}".format(attr)) + + if data_type == "str": + return self.deserialize_unicode(attr) + return eval(data_type)(attr) # nosec + + @staticmethod + def deserialize_unicode(data): + """Preserve unicode objects in Python 2, otherwise return data + as a string. + + :param str data: response string to be deserialized. + :rtype: str or unicode + """ + # We might be here because we have an enum modeled as string, + # and we try to deserialize a partial dict with enum inside + if isinstance(data, Enum): + return data + + # Consider this is real string + try: + if isinstance(data, unicode): + return data + except NameError: + return str(data) + else: + return str(data) + + @staticmethod + def deserialize_enum(data, enum_obj): + """Deserialize string into enum object. + + If the string is not a valid enum value it will be returned as-is + and a warning will be logged. + + :param str data: Response string to be deserialized. If this value is + None or invalid it will be returned as-is. + :param Enum enum_obj: Enum object to deserialize to. + :rtype: Enum + """ + if isinstance(data, enum_obj) or data is None: + return data + if isinstance(data, Enum): + data = data.value + if isinstance(data, int): + # Workaround. We might consider remove it in the future. + # https://github.com/Azure/azure-rest-api-specs/issues/141 + try: + return list(enum_obj.__members__.values())[data] + except IndexError: + error = "{!r} is not a valid index for enum {!r}" + raise DeserializationError(error.format(data, enum_obj)) + try: + return enum_obj(str(data)) + except ValueError: + for enum_value in enum_obj: + if enum_value.value.lower() == str(data).lower(): + return enum_value + # We don't fail anymore for unknown value, we deserialize as a string + _LOGGER.warning("Deserializer is not able to find %s as valid enum in %s", data, enum_obj) + return Deserializer.deserialize_unicode(data) + + @staticmethod + def deserialize_bytearray(attr): + """Deserialize string into bytearray. + + :param str attr: response string to be deserialized. + :rtype: bytearray + :raises: TypeError if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + return bytearray(b64decode(attr)) + + @staticmethod + def deserialize_base64(attr): + """Deserialize base64 encoded string into string. + + :param str attr: response string to be deserialized. + :rtype: bytearray + :raises: TypeError if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + padding = "=" * (3 - (len(attr) + 3) % 4) + attr = attr + padding + encoded = attr.replace("-", "+").replace("_", "/") + return b64decode(encoded) + + @staticmethod + def deserialize_decimal(attr): + """Deserialize string into Decimal object. + + :param str attr: response string to be deserialized. + :rtype: Decimal + :raises: DeserializationError if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + return decimal.Decimal(attr) + except decimal.DecimalException as err: + msg = "Invalid decimal {}".format(attr) + raise_with_traceback(DeserializationError, msg, err) + + @staticmethod + def deserialize_long(attr): + """Deserialize string into long (Py2) or int (Py3). + + :param str attr: response string to be deserialized. + :rtype: long or int + :raises: ValueError if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + return _long_type(attr) + + @staticmethod + def deserialize_duration(attr): + """Deserialize ISO-8601 formatted string into TimeDelta object. + + :param str attr: response string to be deserialized. + :rtype: TimeDelta + :raises: DeserializationError if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = isodate.parse_duration(attr) + except (ValueError, OverflowError, AttributeError) as err: + msg = "Cannot deserialize duration object." + raise_with_traceback(DeserializationError, msg, err) + else: + return duration + + @staticmethod + def deserialize_date(attr): + """Deserialize ISO-8601 formatted string into Date object. + + :param str attr: response string to be deserialized. + :rtype: Date + :raises: DeserializationError if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + if re.search(r"[^\W\d_]", attr, re.I + re.U): + raise DeserializationError("Date must have only digits and -. Received: %s" % attr) + # This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception. + return isodate.parse_date(attr, defaultmonth=None, defaultday=None) + + @staticmethod + def deserialize_time(attr): + """Deserialize ISO-8601 formatted string into time object. + + :param str attr: response string to be deserialized. + :rtype: datetime.time + :raises: DeserializationError if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + if re.search(r"[^\W\d_]", attr, re.I + re.U): + raise DeserializationError("Date must have only digits and -. Received: %s" % attr) + return isodate.parse_time(attr) + + @staticmethod + def deserialize_rfc(attr): + """Deserialize RFC-1123 formatted string into Datetime object. + + :param str attr: response string to be deserialized. + :rtype: Datetime + :raises: DeserializationError if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + parsed_date = email.utils.parsedate_tz(attr) + date_obj = datetime.datetime( + *parsed_date[:6], tzinfo=_FixedOffset(datetime.timedelta(minutes=(parsed_date[9] or 0) / 60)) + ) + if not date_obj.tzinfo: + date_obj = date_obj.astimezone(tz=TZ_UTC) + except ValueError as err: + msg = "Cannot deserialize to rfc datetime object." + raise_with_traceback(DeserializationError, msg, err) + else: + return date_obj + + @staticmethod + def deserialize_iso(attr): + """Deserialize ISO-8601 formatted string into Datetime object. + + :param str attr: response string to be deserialized. + :rtype: Datetime + :raises: DeserializationError if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + attr = attr.upper() + match = Deserializer.valid_date.match(attr) + if not match: + raise ValueError("Invalid datetime string: " + attr) + + check_decimal = attr.split(".") + if len(check_decimal) > 1: + decimal_str = "" + for digit in check_decimal[1]: + if digit.isdigit(): + decimal_str += digit + else: + break + if len(decimal_str) > 6: + attr = attr.replace(decimal_str, decimal_str[0:6]) + + date_obj = isodate.parse_datetime(attr) + test_utc = date_obj.utctimetuple() + if test_utc.tm_year > 9999 or test_utc.tm_year < 1: + raise OverflowError("Hit max or min date") + except (ValueError, OverflowError, AttributeError) as err: + msg = "Cannot deserialize datetime object." + raise_with_traceback(DeserializationError, msg, err) + else: + return date_obj + + @staticmethod + def deserialize_unix(attr): + """Serialize Datetime object into IntTime format. + This is represented as seconds. + + :param int attr: Object to be serialized. + :rtype: Datetime + :raises: DeserializationError if format invalid + """ + if isinstance(attr, ET.Element): + attr = int(attr.text) + try: + date_obj = datetime.datetime.fromtimestamp(attr, TZ_UTC) + except ValueError as err: + msg = "Cannot deserialize to unix datetime object." + raise_with_traceback(DeserializationError, msg, err) + else: + return date_obj diff --git a/sdk/trafficmanager/azure-mgmt-trafficmanager/azure/mgmt/trafficmanager/_traffic_manager_management_client.py b/sdk/trafficmanager/azure-mgmt-trafficmanager/azure/mgmt/trafficmanager/_traffic_manager_management_client.py index d11587583989..8a1ecb006275 100644 --- a/sdk/trafficmanager/azure-mgmt-trafficmanager/azure/mgmt/trafficmanager/_traffic_manager_management_client.py +++ b/sdk/trafficmanager/azure-mgmt-trafficmanager/azure/mgmt/trafficmanager/_traffic_manager_management_client.py @@ -7,21 +7,28 @@ # -------------------------------------------------------------------------- from copy import deepcopy -from typing import Any, Optional, TYPE_CHECKING +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 from ._configuration import TrafficManagerManagementClientConfiguration -from .operations import EndpointsOperations, GeographicHierarchiesOperations, HeatMapOperations, ProfilesOperations, TrafficManagerUserMetricsKeysOperations +from ._serialization import Deserializer, Serializer +from .operations import ( + EndpointsOperations, + GeographicHierarchiesOperations, + HeatMapOperations, + ProfilesOperations, + TrafficManagerUserMetricsKeysOperations, +) if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials import TokenCredential -class TrafficManagerManagementClient: + +class TrafficManagerManagementClient: # pylint: disable=client-accepts-api-version-keyword """TrafficManagerManagementClient. :ivar endpoints: EndpointsOperations operations @@ -36,13 +43,15 @@ class TrafficManagerManagementClient: :ivar traffic_manager_user_metrics_keys: TrafficManagerUserMetricsKeysOperations operations :vartype traffic_manager_user_metrics_keys: azure.mgmt.trafficmanager.operations.TrafficManagerUserMetricsKeysOperations - :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: Gets subscription credentials which uniquely identify Microsoft Azure - subscription. The subscription ID forms part of the URI for every service call. + :param subscription_id: The ID of the target subscription. Required. :type subscription_id: str - :param base_url: Service URL. Default value is 'https://management.azure.com'. + :param base_url: Service URL. Default value is "https://management.azure.com". :type base_url: str + :keyword api_version: Api Version. Default value is "2022-04-01-preview". Note that overriding + this default value may result in unsupported behavior. + :paramtype api_version: str """ def __init__( @@ -52,7 +61,9 @@ def __init__( base_url: str = "https://management.azure.com", **kwargs: Any ) -> None: - self._config = TrafficManagerManagementClientConfiguration(credential=credential, subscription_id=subscription_id, **kwargs) + self._config = TrafficManagerManagementClientConfiguration( + 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)} @@ -61,16 +72,15 @@ def __init__( self._serialize.client_side_validation = False self.endpoints = EndpointsOperations(self._client, self._config, self._serialize, self._deserialize) self.profiles = ProfilesOperations(self._client, self._config, self._serialize, self._deserialize) - self.geographic_hierarchies = GeographicHierarchiesOperations(self._client, self._config, self._serialize, self._deserialize) + self.geographic_hierarchies = GeographicHierarchiesOperations( + self._client, self._config, self._serialize, self._deserialize + ) self.heat_map = HeatMapOperations(self._client, self._config, self._serialize, self._deserialize) - self.traffic_manager_user_metrics_keys = TrafficManagerUserMetricsKeysOperations(self._client, self._config, self._serialize, self._deserialize) - + self.traffic_manager_user_metrics_keys = TrafficManagerUserMetricsKeysOperations( + self._client, self._config, self._serialize, self._deserialize + ) - def _send_request( - self, - request, # type: HttpRequest - **kwargs: Any - ) -> HttpResponse: + def _send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: """Runs the network request through the client's chained policies. >>> from azure.core.rest import HttpRequest @@ -79,7 +89,7 @@ def _send_request( >>> response = client._send_request(request) - For more information on this code flow, see https://aka.ms/azsdk/python/protocol/quickstart + For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request :param request: The network request you want to make. Required. :type request: ~azure.core.rest.HttpRequest diff --git a/sdk/trafficmanager/azure-mgmt-trafficmanager/azure/mgmt/trafficmanager/_vendor.py b/sdk/trafficmanager/azure-mgmt-trafficmanager/azure/mgmt/trafficmanager/_vendor.py index 138f663c53a4..9aad73fc743e 100644 --- a/sdk/trafficmanager/azure-mgmt-trafficmanager/azure/mgmt/trafficmanager/_vendor.py +++ b/sdk/trafficmanager/azure-mgmt-trafficmanager/azure/mgmt/trafficmanager/_vendor.py @@ -7,6 +7,7 @@ from azure.core.pipeline.transport import HttpRequest + def _convert_request(request, files=None): data = request.content if not files else None request = HttpRequest(method=request.method, url=request.url, headers=request.headers, data=data) @@ -14,6 +15,7 @@ def _convert_request(request, files=None): request.set_formdata_body(files) return request + def _format_url_section(template, **kwargs): components = template.split("/") while components: @@ -21,7 +23,5 @@ def _format_url_section(template, **kwargs): return template.format(**kwargs) except KeyError as key: formatted_components = template.split("/") - components = [ - c for c in formatted_components if "{}".format(key.args[0]) not in c - ] + components = [c for c in formatted_components if "{}".format(key.args[0]) not in c] template = "/".join(components) diff --git a/sdk/trafficmanager/azure-mgmt-trafficmanager/azure/mgmt/trafficmanager/_version.py b/sdk/trafficmanager/azure-mgmt-trafficmanager/azure/mgmt/trafficmanager/_version.py index c47f66669f1b..e5754a47ce68 100644 --- a/sdk/trafficmanager/azure-mgmt-trafficmanager/azure/mgmt/trafficmanager/_version.py +++ b/sdk/trafficmanager/azure-mgmt-trafficmanager/azure/mgmt/trafficmanager/_version.py @@ -6,4 +6,4 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -VERSION = "1.0.0" +VERSION = "1.0.0b1" diff --git a/sdk/trafficmanager/azure-mgmt-trafficmanager/azure/mgmt/trafficmanager/aio/__init__.py b/sdk/trafficmanager/azure-mgmt-trafficmanager/azure/mgmt/trafficmanager/aio/__init__.py index b48878c326cf..a75ae436692e 100644 --- a/sdk/trafficmanager/azure-mgmt-trafficmanager/azure/mgmt/trafficmanager/aio/__init__.py +++ b/sdk/trafficmanager/azure-mgmt-trafficmanager/azure/mgmt/trafficmanager/aio/__init__.py @@ -7,9 +7,17 @@ # -------------------------------------------------------------------------- from ._traffic_manager_management_client import TrafficManagerManagementClient -__all__ = ['TrafficManagerManagementClient'] -# `._patch.py` is used for handwritten extensions to the generated code -# Example: https://github.com/Azure/azure-sdk-for-python/blob/main/doc/dev/customize_code/how-to-patch-sdk-code.md -from ._patch import patch_sdk -patch_sdk() +try: + from ._patch import __all__ as _patch_all + from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import +except ImportError: + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "TrafficManagerManagementClient", +] +__all__.extend([p for p in _patch_all if p not in __all__]) + +_patch_sdk() diff --git a/sdk/trafficmanager/azure-mgmt-trafficmanager/azure/mgmt/trafficmanager/aio/_configuration.py b/sdk/trafficmanager/azure-mgmt-trafficmanager/azure/mgmt/trafficmanager/aio/_configuration.py index 9a5b9ddb6ad8..757bc39d4518 100644 --- a/sdk/trafficmanager/azure-mgmt-trafficmanager/azure/mgmt/trafficmanager/aio/_configuration.py +++ b/sdk/trafficmanager/azure-mgmt-trafficmanager/azure/mgmt/trafficmanager/aio/_configuration.py @@ -6,6 +6,7 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +import sys from typing import Any, TYPE_CHECKING from azure.core.configuration import Configuration @@ -14,30 +15,35 @@ 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 TrafficManagerManagementClientConfiguration(Configuration): +class TrafficManagerManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes """Configuration for TrafficManagerManagementClient. 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: Gets subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. + :param subscription_id: The ID of the target subscription. Required. :type subscription_id: str + :keyword api_version: Api Version. Default value is "2022-04-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(TrafficManagerManagementClientConfiguration, self).__init__(**kwargs) + api_version = kwargs.pop("api_version", "2022-04-01-preview") # type: Literal["2022-04-01-preview"] + if credential is None: raise ValueError("Parameter 'credential' must not be None.") if subscription_id is None: @@ -45,23 +51,22 @@ def __init__( self.credential = credential self.subscription_id = subscription_id - self.api_version = "2018-08-01" - self.credential_scopes = kwargs.pop('credential_scopes', ['https://management.azure.com/.default']) - kwargs.setdefault('sdk_moniker', 'mgmt-trafficmanager/{}'.format(VERSION)) + self.api_version = api_version + self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "mgmt-trafficmanager/{}".format(VERSION)) self._configure(**kwargs) - def _configure( - self, - **kwargs: Any - ) -> None: - self.user_agent_policy = kwargs.get('user_agent_policy') or policies.UserAgentPolicy(**kwargs) - self.headers_policy = kwargs.get('headers_policy') or policies.HeadersPolicy(**kwargs) - self.proxy_policy = kwargs.get('proxy_policy') or policies.ProxyPolicy(**kwargs) - self.logging_policy = kwargs.get('logging_policy') or policies.NetworkTraceLoggingPolicy(**kwargs) - self.http_logging_policy = kwargs.get('http_logging_policy') or ARMHttpLoggingPolicy(**kwargs) - self.retry_policy = kwargs.get('retry_policy') or policies.AsyncRetryPolicy(**kwargs) - self.custom_hook_policy = kwargs.get('custom_hook_policy') or policies.CustomHookPolicy(**kwargs) - self.redirect_policy = kwargs.get('redirect_policy') or policies.AsyncRedirectPolicy(**kwargs) - self.authentication_policy = kwargs.get('authentication_policy') + def _configure(self, **kwargs: Any) -> None: + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.AsyncRetryPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.AsyncRedirectPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") if self.credential and not self.authentication_policy: - self.authentication_policy = AsyncARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs) + self.authentication_policy = AsyncARMChallengeAuthenticationPolicy( + self.credential, *self.credential_scopes, **kwargs + ) diff --git a/sdk/trafficmanager/azure-mgmt-trafficmanager/azure/mgmt/trafficmanager/aio/_patch.py b/sdk/trafficmanager/azure-mgmt-trafficmanager/azure/mgmt/trafficmanager/aio/_patch.py index 74e48ecd07cf..f99e77fef986 100644 --- a/sdk/trafficmanager/azure-mgmt-trafficmanager/azure/mgmt/trafficmanager/aio/_patch.py +++ b/sdk/trafficmanager/azure-mgmt-trafficmanager/azure/mgmt/trafficmanager/aio/_patch.py @@ -28,4 +28,4 @@ # This file is used for handwritten extensions to the generated code. Example: # https://github.com/Azure/azure-sdk-for-python/blob/main/doc/dev/customize_code/how-to-patch-sdk-code.md def patch_sdk(): - pass \ No newline at end of file + pass diff --git a/sdk/trafficmanager/azure-mgmt-trafficmanager/azure/mgmt/trafficmanager/aio/_traffic_manager_management_client.py b/sdk/trafficmanager/azure-mgmt-trafficmanager/azure/mgmt/trafficmanager/aio/_traffic_manager_management_client.py index 83514b3712fe..582cfd881336 100644 --- a/sdk/trafficmanager/azure-mgmt-trafficmanager/azure/mgmt/trafficmanager/aio/_traffic_manager_management_client.py +++ b/sdk/trafficmanager/azure-mgmt-trafficmanager/azure/mgmt/trafficmanager/aio/_traffic_manager_management_client.py @@ -7,21 +7,28 @@ # -------------------------------------------------------------------------- from copy import deepcopy -from typing import Any, Awaitable, Optional, TYPE_CHECKING +from typing import Any, Awaitable, TYPE_CHECKING from azure.core.rest import AsyncHttpResponse, HttpRequest from azure.mgmt.core import AsyncARMPipelineClient -from msrest import Deserializer, Serializer from .. import models +from .._serialization import Deserializer, Serializer from ._configuration import TrafficManagerManagementClientConfiguration -from .operations import EndpointsOperations, GeographicHierarchiesOperations, HeatMapOperations, ProfilesOperations, TrafficManagerUserMetricsKeysOperations +from .operations import ( + EndpointsOperations, + GeographicHierarchiesOperations, + HeatMapOperations, + ProfilesOperations, + TrafficManagerUserMetricsKeysOperations, +) if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential -class TrafficManagerManagementClient: + +class TrafficManagerManagementClient: # pylint: disable=client-accepts-api-version-keyword """TrafficManagerManagementClient. :ivar endpoints: EndpointsOperations operations @@ -36,13 +43,15 @@ class TrafficManagerManagementClient: :ivar traffic_manager_user_metrics_keys: TrafficManagerUserMetricsKeysOperations operations :vartype traffic_manager_user_metrics_keys: azure.mgmt.trafficmanager.aio.operations.TrafficManagerUserMetricsKeysOperations - :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: Gets subscription credentials which uniquely identify Microsoft Azure - subscription. The subscription ID forms part of the URI for every service call. + :param subscription_id: The ID of the target subscription. Required. :type subscription_id: str - :param base_url: Service URL. Default value is 'https://management.azure.com'. + :param base_url: Service URL. Default value is "https://management.azure.com". :type base_url: str + :keyword api_version: Api Version. Default value is "2022-04-01-preview". Note that overriding + this default value may result in unsupported behavior. + :paramtype api_version: str """ def __init__( @@ -52,7 +61,9 @@ def __init__( base_url: str = "https://management.azure.com", **kwargs: Any ) -> None: - self._config = TrafficManagerManagementClientConfiguration(credential=credential, subscription_id=subscription_id, **kwargs) + self._config = TrafficManagerManagementClientConfiguration( + 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)} @@ -61,16 +72,15 @@ def __init__( self._serialize.client_side_validation = False self.endpoints = EndpointsOperations(self._client, self._config, self._serialize, self._deserialize) self.profiles = ProfilesOperations(self._client, self._config, self._serialize, self._deserialize) - self.geographic_hierarchies = GeographicHierarchiesOperations(self._client, self._config, self._serialize, self._deserialize) + self.geographic_hierarchies = GeographicHierarchiesOperations( + self._client, self._config, self._serialize, self._deserialize + ) self.heat_map = HeatMapOperations(self._client, self._config, self._serialize, self._deserialize) - self.traffic_manager_user_metrics_keys = TrafficManagerUserMetricsKeysOperations(self._client, self._config, self._serialize, self._deserialize) - + self.traffic_manager_user_metrics_keys = TrafficManagerUserMetricsKeysOperations( + self._client, self._config, self._serialize, self._deserialize + ) - def _send_request( - self, - request: HttpRequest, - **kwargs: Any - ) -> Awaitable[AsyncHttpResponse]: + def _send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]: """Runs the network request through the client's chained policies. >>> from azure.core.rest import HttpRequest @@ -79,7 +89,7 @@ def _send_request( >>> response = await client._send_request(request) - For more information on this code flow, see https://aka.ms/azsdk/python/protocol/quickstart + For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request :param request: The network request you want to make. Required. :type request: ~azure.core.rest.HttpRequest diff --git a/sdk/trafficmanager/azure-mgmt-trafficmanager/azure/mgmt/trafficmanager/aio/operations/__init__.py b/sdk/trafficmanager/azure-mgmt-trafficmanager/azure/mgmt/trafficmanager/aio/operations/__init__.py index adda3e0be5d0..d48dcfb68274 100644 --- a/sdk/trafficmanager/azure-mgmt-trafficmanager/azure/mgmt/trafficmanager/aio/operations/__init__.py +++ b/sdk/trafficmanager/azure-mgmt-trafficmanager/azure/mgmt/trafficmanager/aio/operations/__init__.py @@ -12,10 +12,16 @@ from ._heat_map_operations import HeatMapOperations from ._traffic_manager_user_metrics_keys_operations import TrafficManagerUserMetricsKeysOperations +from ._patch import __all__ as _patch_all +from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import +from ._patch import patch_sdk as _patch_sdk + __all__ = [ - 'EndpointsOperations', - 'ProfilesOperations', - 'GeographicHierarchiesOperations', - 'HeatMapOperations', - 'TrafficManagerUserMetricsKeysOperations', + "EndpointsOperations", + "ProfilesOperations", + "GeographicHierarchiesOperations", + "HeatMapOperations", + "TrafficManagerUserMetricsKeysOperations", ] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/sdk/trafficmanager/azure-mgmt-trafficmanager/azure/mgmt/trafficmanager/aio/operations/_endpoints_operations.py b/sdk/trafficmanager/azure-mgmt-trafficmanager/azure/mgmt/trafficmanager/aio/operations/_endpoints_operations.py index da69d640a928..b66ebcd3448f 100644 --- a/sdk/trafficmanager/azure-mgmt-trafficmanager/azure/mgmt/trafficmanager/aio/operations/_endpoints_operations.py +++ b/sdk/trafficmanager/azure-mgmt-trafficmanager/azure/mgmt/trafficmanager/aio/operations/_endpoints_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,82 +6,189 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -import functools -from typing import Any, Callable, Dict, Generic, Optional, TypeVar, Union -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 from azure.core.rest import HttpRequest from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models from ..._vendor import _convert_request -from ...operations._endpoints_operations import build_create_or_update_request, build_delete_request, build_get_request, build_update_request -T = TypeVar('T') +from ...operations._endpoints_operations import ( + build_create_or_update_request, + build_delete_request, + build_get_request, + build_update_request, +) + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class EndpointsOperations: - """EndpointsOperations 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 EndpointsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.trafficmanager.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.trafficmanager.aio.TrafficManagerManagementClient`'s + :attr:`endpoints` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - @distributed_trace_async + @overload async def update( self, resource_group_name: str, profile_name: str, - endpoint_type: Union[str, "_models.EndpointType"], + endpoint_type: Union[str, _models.EndpointType], endpoint_name: str, - parameters: "_models.Endpoint", + parameters: _models.Endpoint, + *, + content_type: str = "application/json", **kwargs: Any - ) -> "_models.Endpoint": + ) -> _models.Endpoint: """Update a Traffic Manager endpoint. - :param resource_group_name: The name of the resource group containing the Traffic Manager - endpoint to be updated. + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param profile_name: The name of the Traffic Manager profile. + :param profile_name: The name of the Traffic Manager profile. Required. :type profile_name: str - :param endpoint_type: The type of the Traffic Manager endpoint to be updated. + :param endpoint_type: The type of the Traffic Manager endpoint to be updated. Known values are: + "AzureEndpoints", "ExternalEndpoints", and "NestedEndpoints". Required. :type endpoint_type: str or ~azure.mgmt.trafficmanager.models.EndpointType - :param endpoint_name: The name of the Traffic Manager endpoint to be updated. + :param endpoint_name: The name of the Traffic Manager endpoint to be updated. Required. :type endpoint_name: str :param parameters: The Traffic Manager endpoint parameters supplied to the Update operation. + Required. :type parameters: ~azure.mgmt.trafficmanager.models.Endpoint + :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: Endpoint or the result of cls(response) + :rtype: ~azure.mgmt.trafficmanager.models.Endpoint + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def update( + self, + resource_group_name: str, + profile_name: str, + endpoint_type: Union[str, _models.EndpointType], + endpoint_name: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Endpoint: + """Update a Traffic Manager endpoint. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param profile_name: The name of the Traffic Manager profile. Required. + :type profile_name: str + :param endpoint_type: The type of the Traffic Manager endpoint to be updated. Known values are: + "AzureEndpoints", "ExternalEndpoints", and "NestedEndpoints". Required. + :type endpoint_type: str or ~azure.mgmt.trafficmanager.models.EndpointType + :param endpoint_name: The name of the Traffic Manager endpoint to be updated. Required. + :type endpoint_name: str + :param parameters: The Traffic Manager endpoint parameters supplied to the Update operation. + Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: Endpoint, or the result of cls(response) + :return: Endpoint or the result of cls(response) :rtype: ~azure.mgmt.trafficmanager.models.Endpoint - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def update( + self, + resource_group_name: str, + profile_name: str, + endpoint_type: Union[str, _models.EndpointType], + endpoint_name: str, + parameters: Union[_models.Endpoint, IO], + **kwargs: Any + ) -> _models.Endpoint: + """Update a Traffic Manager endpoint. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param profile_name: The name of the Traffic Manager profile. Required. + :type profile_name: str + :param endpoint_type: The type of the Traffic Manager endpoint to be updated. Known values are: + "AzureEndpoints", "ExternalEndpoints", and "NestedEndpoints". Required. + :type endpoint_type: str or ~azure.mgmt.trafficmanager.models.EndpointType + :param endpoint_name: The name of the Traffic Manager endpoint to be updated. Required. + :type endpoint_name: str + :param parameters: The Traffic Manager endpoint parameters supplied to the Update operation. Is + either a model type or a IO type. Required. + :type parameters: ~azure.mgmt.trafficmanager.models.Endpoint 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: Endpoint or the result of cls(response) + :rtype: ~azure.mgmt.trafficmanager.models.Endpoint + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Endpoint"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - _json = self._serialize.body(parameters, 'Endpoint') + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-04-01-preview"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.Endpoint] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "Endpoint") request = build_update_request( resource_group_name=resource_group_name, @@ -88,128 +196,243 @@ async def update( endpoint_type=endpoint_type, endpoint_name=endpoint_name, subscription_id=self._config.subscription_id, + api_version=api_version, content_type=content_type, json=_json, - template_url=self.update.metadata['url'], + content=_content, + template_url=self.update.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('Endpoint', pipeline_response) + deserialized = self._deserialize("Endpoint", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/trafficmanagerprofiles/{profileName}/{endpointType}/{endpointName}'} # type: ignore - + update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/trafficmanagerprofiles/{profileName}/{endpointType}/{endpointName}"} # type: ignore @distributed_trace_async async def get( self, resource_group_name: str, profile_name: str, - endpoint_type: Union[str, "_models.EndpointType"], + endpoint_type: Union[str, _models.EndpointType], endpoint_name: str, **kwargs: Any - ) -> "_models.Endpoint": + ) -> _models.Endpoint: """Gets a Traffic Manager endpoint. - :param resource_group_name: The name of the resource group containing the Traffic Manager - endpoint. + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param profile_name: The name of the Traffic Manager profile. + :param profile_name: The name of the Traffic Manager profile. Required. :type profile_name: str - :param endpoint_type: The type of the Traffic Manager endpoint. + :param endpoint_type: The type of the Traffic Manager endpoint. Known values are: + "AzureEndpoints", "ExternalEndpoints", and "NestedEndpoints". Required. :type endpoint_type: str or ~azure.mgmt.trafficmanager.models.EndpointType - :param endpoint_name: The name of the Traffic Manager endpoint. + :param endpoint_name: The name of the Traffic Manager endpoint. Required. :type endpoint_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: Endpoint, or the result of cls(response) + :return: Endpoint or the result of cls(response) :rtype: ~azure.mgmt.trafficmanager.models.Endpoint - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Endpoint"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-04-01-preview"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.Endpoint] - request = build_get_request( resource_group_name=resource_group_name, profile_name=profile_name, endpoint_type=endpoint_type, endpoint_name=endpoint_name, subscription_id=self._config.subscription_id, - template_url=self.get.metadata['url'], + 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) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - 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('Endpoint', pipeline_response) + deserialized = self._deserialize("Endpoint", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/trafficmanagerprofiles/{profileName}/{endpointType}/{endpointName}'} # type: ignore + get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/trafficmanagerprofiles/{profileName}/{endpointType}/{endpointName}"} # type: ignore + @overload + async def create_or_update( + self, + resource_group_name: str, + profile_name: str, + endpoint_type: Union[str, _models.EndpointType], + endpoint_name: str, + parameters: _models.Endpoint, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Endpoint: + """Create or update a Traffic Manager endpoint. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param profile_name: The name of the Traffic Manager profile. Required. + :type profile_name: str + :param endpoint_type: The type of the Traffic Manager endpoint to be created or updated. Known + values are: "AzureEndpoints", "ExternalEndpoints", and "NestedEndpoints". Required. + :type endpoint_type: str or ~azure.mgmt.trafficmanager.models.EndpointType + :param endpoint_name: The name of the Traffic Manager endpoint to be created or updated. + Required. + :type endpoint_name: str + :param parameters: The Traffic Manager endpoint parameters supplied to the CreateOrUpdate + operation. Required. + :type parameters: ~azure.mgmt.trafficmanager.models.Endpoint + :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: Endpoint or the result of cls(response) + :rtype: ~azure.mgmt.trafficmanager.models.Endpoint + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_or_update( + self, + resource_group_name: str, + profile_name: str, + endpoint_type: Union[str, _models.EndpointType], + endpoint_name: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Endpoint: + """Create or update a Traffic Manager endpoint. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param profile_name: The name of the Traffic Manager profile. Required. + :type profile_name: str + :param endpoint_type: The type of the Traffic Manager endpoint to be created or updated. Known + values are: "AzureEndpoints", "ExternalEndpoints", and "NestedEndpoints". Required. + :type endpoint_type: str or ~azure.mgmt.trafficmanager.models.EndpointType + :param endpoint_name: The name of the Traffic Manager endpoint to be created or updated. + Required. + :type endpoint_name: str + :param parameters: The Traffic Manager endpoint parameters supplied to the CreateOrUpdate + operation. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: Endpoint or the result of cls(response) + :rtype: ~azure.mgmt.trafficmanager.models.Endpoint + :raises ~azure.core.exceptions.HttpResponseError: + """ @distributed_trace_async async def create_or_update( self, resource_group_name: str, profile_name: str, - endpoint_type: Union[str, "_models.EndpointType"], + endpoint_type: Union[str, _models.EndpointType], endpoint_name: str, - parameters: "_models.Endpoint", + parameters: Union[_models.Endpoint, IO], **kwargs: Any - ) -> "_models.Endpoint": + ) -> _models.Endpoint: """Create or update a Traffic Manager endpoint. - :param resource_group_name: The name of the resource group containing the Traffic Manager - endpoint to be created or updated. + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param profile_name: The name of the Traffic Manager profile. + :param profile_name: The name of the Traffic Manager profile. Required. :type profile_name: str - :param endpoint_type: The type of the Traffic Manager endpoint to be created or updated. + :param endpoint_type: The type of the Traffic Manager endpoint to be created or updated. Known + values are: "AzureEndpoints", "ExternalEndpoints", and "NestedEndpoints". Required. :type endpoint_type: str or ~azure.mgmt.trafficmanager.models.EndpointType :param endpoint_name: The name of the Traffic Manager endpoint to be created or updated. + Required. :type endpoint_name: str :param parameters: The Traffic Manager endpoint parameters supplied to the CreateOrUpdate - operation. - :type parameters: ~azure.mgmt.trafficmanager.models.Endpoint + operation. Is either a model type or a IO type. Required. + :type parameters: ~azure.mgmt.trafficmanager.models.Endpoint 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: Endpoint, or the result of cls(response) + :return: Endpoint or the result of cls(response) :rtype: ~azure.mgmt.trafficmanager.models.Endpoint - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Endpoint"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-04-01-preview"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.Endpoint] - _json = self._serialize.body(parameters, 'Endpoint') + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "Endpoint") request = build_create_or_update_request( resource_group_name=resource_group_name, @@ -217,14 +440,21 @@ async def create_or_update( endpoint_type=endpoint_type, endpoint_name=endpoint_name, subscription_id=self._config.subscription_id, + api_version=api_version, content_type=content_type, json=_json, - template_url=self.create_or_update.metadata['url'], + 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) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 201]: @@ -232,63 +462,78 @@ async def create_or_update( raise HttpResponseError(response=response, error_format=ARMErrorFormat) if response.status_code == 200: - deserialized = self._deserialize('Endpoint', pipeline_response) + deserialized = self._deserialize("Endpoint", pipeline_response) if response.status_code == 201: - deserialized = self._deserialize('Endpoint', pipeline_response) + deserialized = self._deserialize("Endpoint", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/trafficmanagerprofiles/{profileName}/{endpointType}/{endpointName}'} # type: ignore - + create_or_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/trafficmanagerprofiles/{profileName}/{endpointType}/{endpointName}"} # type: ignore @distributed_trace_async async def delete( self, resource_group_name: str, profile_name: str, - endpoint_type: Union[str, "_models.EndpointType"], + endpoint_type: Union[str, _models.EndpointType], endpoint_name: str, **kwargs: Any - ) -> Optional["_models.DeleteOperationResult"]: + ) -> Optional[_models.DeleteOperationResult]: """Deletes a Traffic Manager endpoint. - :param resource_group_name: The name of the resource group containing the Traffic Manager - endpoint to be deleted. + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param profile_name: The name of the Traffic Manager profile. + :param profile_name: The name of the Traffic Manager profile. Required. :type profile_name: str - :param endpoint_type: The type of the Traffic Manager endpoint to be deleted. + :param endpoint_type: The type of the Traffic Manager endpoint to be deleted. Known values are: + "AzureEndpoints", "ExternalEndpoints", and "NestedEndpoints". Required. :type endpoint_type: str or ~azure.mgmt.trafficmanager.models.EndpointType - :param endpoint_name: The name of the Traffic Manager endpoint to be deleted. + :param endpoint_name: The name of the Traffic Manager endpoint to be deleted. Required. :type endpoint_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: DeleteOperationResult, or the result of cls(response) + :return: DeleteOperationResult or None or the result of cls(response) :rtype: ~azure.mgmt.trafficmanager.models.DeleteOperationResult or None - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.DeleteOperationResult"]] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-04-01-preview"] + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.DeleteOperationResult]] - request = build_delete_request( resource_group_name=resource_group_name, profile_name=profile_name, endpoint_type=endpoint_type, endpoint_name=endpoint_name, subscription_id=self._config.subscription_id, - template_url=self.delete.metadata['url'], + 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) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 204]: @@ -297,12 +542,11 @@ async def delete( deserialized = None if response.status_code == 200: - deserialized = self._deserialize('DeleteOperationResult', pipeline_response) + deserialized = self._deserialize("DeleteOperationResult", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/trafficmanagerprofiles/{profileName}/{endpointType}/{endpointName}'} # type: ignore - + delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/trafficmanagerprofiles/{profileName}/{endpointType}/{endpointName}"} # type: ignore diff --git a/sdk/trafficmanager/azure-mgmt-trafficmanager/azure/mgmt/trafficmanager/aio/operations/_geographic_hierarchies_operations.py b/sdk/trafficmanager/azure-mgmt-trafficmanager/azure/mgmt/trafficmanager/aio/operations/_geographic_hierarchies_operations.py index abaaff11be56..de2506c5b6f6 100644 --- a/sdk/trafficmanager/azure-mgmt-trafficmanager/azure/mgmt/trafficmanager/aio/operations/_geographic_hierarchies_operations.py +++ b/sdk/trafficmanager/azure-mgmt-trafficmanager/azure/mgmt/trafficmanager/aio/operations/_geographic_hierarchies_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,83 +6,104 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -import functools -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, Optional, TypeVar + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.rest import HttpRequest from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models from ..._vendor import _convert_request from ...operations._geographic_hierarchies_operations import build_get_default_request -T = TypeVar('T') + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class GeographicHierarchiesOperations: - """GeographicHierarchiesOperations 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 GeographicHierarchiesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.trafficmanager.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.trafficmanager.aio.TrafficManagerManagementClient`'s + :attr:`geographic_hierarchies` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace_async - async def get_default( - self, - **kwargs: Any - ) -> "_models.TrafficManagerGeographicHierarchy": + async def get_default(self, **kwargs: Any) -> _models.TrafficManagerGeographicHierarchy: """Gets the default Geographic Hierarchy used by the Geographic traffic routing method. :keyword callable cls: A custom type or function that will be passed the direct response - :return: TrafficManagerGeographicHierarchy, or the result of cls(response) + :return: TrafficManagerGeographicHierarchy or the result of cls(response) :rtype: ~azure.mgmt.trafficmanager.models.TrafficManagerGeographicHierarchy - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.TrafficManagerGeographicHierarchy"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-04-01-preview"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.TrafficManagerGeographicHierarchy] - request = build_get_default_request( - template_url=self.get_default.metadata['url'], + api_version=api_version, + template_url=self.get_default.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('TrafficManagerGeographicHierarchy', pipeline_response) + deserialized = self._deserialize("TrafficManagerGeographicHierarchy", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get_default.metadata = {'url': '/providers/Microsoft.Network/trafficManagerGeographicHierarchies/default'} # type: ignore - + get_default.metadata = {"url": "/providers/Microsoft.Network/trafficManagerGeographicHierarchies/default"} # type: ignore diff --git a/sdk/trafficmanager/azure-mgmt-trafficmanager/azure/mgmt/trafficmanager/aio/operations/_heat_map_operations.py b/sdk/trafficmanager/azure-mgmt-trafficmanager/azure/mgmt/trafficmanager/aio/operations/_heat_map_operations.py index 8d12f3c52707..3e0c5c447236 100644 --- a/sdk/trafficmanager/azure-mgmt-trafficmanager/azure/mgmt/trafficmanager/aio/operations/_heat_map_operations.py +++ b/sdk/trafficmanager/azure-mgmt-trafficmanager/azure/mgmt/trafficmanager/aio/operations/_heat_map_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,44 +6,54 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -import functools -from typing import Any, Callable, Dict, Generic, List, Optional, TypeVar -import warnings - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +import sys +from typing import Any, Callable, Dict, List, Optional, TypeVar + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.rest import HttpRequest from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models from ..._vendor import _convert_request from ...operations._heat_map_operations import build_get_request -T = TypeVar('T') + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class HeatMapOperations: - """HeatMapOperations 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 HeatMapOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.trafficmanager.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.trafficmanager.aio.TrafficManagerManagementClient`'s + :attr:`heat_map` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace_async async def get( @@ -52,55 +63,75 @@ async def get( top_left: Optional[List[float]] = None, bot_right: Optional[List[float]] = None, **kwargs: Any - ) -> "_models.HeatMapModel": + ) -> _models.HeatMapModel: """Gets latest heatmap for Traffic Manager profile. - :param resource_group_name: The name of the resource group containing the Traffic Manager - endpoint. + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param profile_name: The name of the Traffic Manager profile. + :param profile_name: The name of the Traffic Manager profile. Required. :type profile_name: str :param top_left: The top left latitude,longitude pair of the rectangular viewport to query for. + Default value is None. :type top_left: list[float] :param bot_right: The bottom right latitude,longitude pair of the rectangular viewport to query - for. + for. Default value is None. :type bot_right: list[float] + :keyword heat_map_type: The type of HeatMap for the Traffic Manager profile. Default value is + "default". Note that overriding this default value may result in unsupported behavior. + :paramtype heat_map_type: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: HeatMapModel, or the result of cls(response) + :return: HeatMapModel or the result of cls(response) :rtype: ~azure.mgmt.trafficmanager.models.HeatMapModel - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.HeatMapModel"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + heat_map_type = kwargs.pop("heat_map_type", "default") # type: Literal["default"] + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-04-01-preview"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.HeatMapModel] - request = build_get_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, profile_name=profile_name, + subscription_id=self._config.subscription_id, top_left=top_left, bot_right=bot_right, - template_url=self.get.metadata['url'], + heat_map_type=heat_map_type, + 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) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - 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('HeatMapModel', pipeline_response) + deserialized = self._deserialize("HeatMapModel", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/trafficmanagerprofiles/{profileName}/heatMaps/{heatMapType}'} # type: ignore - + get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/trafficmanagerprofiles/{profileName}/heatMaps/{heatMapType}"} # type: ignore diff --git a/sdk/trafficmanager/azure-mgmt-trafficmanager/azure/mgmt/trafficmanager/aio/operations/_patch.py b/sdk/trafficmanager/azure-mgmt-trafficmanager/azure/mgmt/trafficmanager/aio/operations/_patch.py new file mode 100644 index 000000000000..f7dd32510333 --- /dev/null +++ b/sdk/trafficmanager/azure-mgmt-trafficmanager/azure/mgmt/trafficmanager/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/trafficmanager/azure-mgmt-trafficmanager/azure/mgmt/trafficmanager/aio/operations/_profiles_operations.py b/sdk/trafficmanager/azure-mgmt-trafficmanager/azure/mgmt/trafficmanager/aio/operations/_profiles_operations.py index 931fab5c8dec..18b0a5287f77 100644 --- a/sdk/trafficmanager/azure-mgmt-trafficmanager/azure/mgmt/trafficmanager/aio/operations/_profiles_operations.py +++ b/sdk/trafficmanager/azure-mgmt-trafficmanager/azure/mgmt/trafficmanager/aio/operations/_profiles_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,141 +6,239 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -import functools -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 from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models from ..._vendor import _convert_request -from ...operations._profiles_operations import build_check_traffic_manager_relative_dns_name_availability_request, build_create_or_update_request, build_delete_request, build_get_request, build_list_by_resource_group_request, build_list_by_subscription_request, build_update_request -T = TypeVar('T') +from ...operations._profiles_operations import ( + build_check_traffic_manager_relative_dns_name_availability_request, + build_create_or_update_request, + build_delete_request, + build_get_request, + build_list_by_resource_group_request, + build_list_by_subscription_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 ProfilesOperations: - """ProfilesOperations 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 ProfilesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.trafficmanager.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.trafficmanager.aio.TrafficManagerManagementClient`'s + :attr:`profiles` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - @distributed_trace_async + @overload async def check_traffic_manager_relative_dns_name_availability( self, - parameters: "_models.CheckTrafficManagerRelativeDnsNameAvailabilityParameters", + parameters: _models.CheckTrafficManagerRelativeDnsNameAvailabilityParameters, + *, + content_type: str = "application/json", **kwargs: Any - ) -> "_models.TrafficManagerNameAvailability": + ) -> _models.TrafficManagerNameAvailability: """Checks the availability of a Traffic Manager Relative DNS name. :param parameters: The Traffic Manager name parameters supplied to the - CheckTrafficManagerNameAvailability operation. + CheckTrafficManagerNameAvailability operation. Required. :type parameters: ~azure.mgmt.trafficmanager.models.CheckTrafficManagerRelativeDnsNameAvailabilityParameters + :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: TrafficManagerNameAvailability or the result of cls(response) + :rtype: ~azure.mgmt.trafficmanager.models.TrafficManagerNameAvailability + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def check_traffic_manager_relative_dns_name_availability( + self, parameters: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.TrafficManagerNameAvailability: + """Checks the availability of a Traffic Manager Relative DNS name. + + :param parameters: The Traffic Manager name parameters supplied to the + CheckTrafficManagerNameAvailability operation. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: TrafficManagerNameAvailability or the result of cls(response) + :rtype: ~azure.mgmt.trafficmanager.models.TrafficManagerNameAvailability + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def check_traffic_manager_relative_dns_name_availability( + self, parameters: Union[_models.CheckTrafficManagerRelativeDnsNameAvailabilityParameters, IO], **kwargs: Any + ) -> _models.TrafficManagerNameAvailability: + """Checks the availability of a Traffic Manager Relative DNS name. + + :param parameters: The Traffic Manager name parameters supplied to the + CheckTrafficManagerNameAvailability operation. Is either a model type or a IO type. Required. + :type parameters: + ~azure.mgmt.trafficmanager.models.CheckTrafficManagerRelativeDnsNameAvailabilityParameters 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: TrafficManagerNameAvailability, or the result of cls(response) + :return: TrafficManagerNameAvailability or the result of cls(response) :rtype: ~azure.mgmt.trafficmanager.models.TrafficManagerNameAvailability - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.TrafficManagerNameAvailability"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - _json = self._serialize.body(parameters, 'CheckTrafficManagerRelativeDnsNameAvailabilityParameters') + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-04-01-preview"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.TrafficManagerNameAvailability] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "CheckTrafficManagerRelativeDnsNameAvailabilityParameters") request = build_check_traffic_manager_relative_dns_name_availability_request( + api_version=api_version, content_type=content_type, json=_json, - template_url=self.check_traffic_manager_relative_dns_name_availability.metadata['url'], + content=_content, + template_url=self.check_traffic_manager_relative_dns_name_availability.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('TrafficManagerNameAvailability', pipeline_response) + deserialized = self._deserialize("TrafficManagerNameAvailability", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - check_traffic_manager_relative_dns_name_availability.metadata = {'url': '/providers/Microsoft.Network/checkTrafficManagerNameAvailability'} # type: ignore - + check_traffic_manager_relative_dns_name_availability.metadata = {"url": "/providers/Microsoft.Network/checkTrafficManagerNameAvailability"} # type: ignore @distributed_trace - def list_by_resource_group( - self, - resource_group_name: str, - **kwargs: Any - ) -> AsyncIterable["_models.ProfileListResult"]: + def list_by_resource_group(self, resource_group_name: str, **kwargs: Any) -> AsyncIterable["_models.Profile"]: """Lists all Traffic Manager profiles within a resource group. - :param resource_group_name: The name of the resource group containing the Traffic Manager - profiles to be listed. + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either ProfileListResult or the result of cls(response) - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.trafficmanager.models.ProfileListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either Profile or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.trafficmanager.models.Profile] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.ProfileListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-04-01-preview"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.ProfileListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_by_resource_group_request( resource_group_name=resource_group_name, subscription_id=self._config.subscription_id, - template_url=self.list_by_resource_group.metadata['url'], + 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) + request.url = self._client.format_url(request.url) # type: ignore else: - - request = build_list_by_resource_group_request( - resource_group_name=resource_group_name, - subscription_id=self._config.subscription_id, - template_url=next_link, + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request @@ -153,7 +252,9 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: @@ -162,48 +263,63 @@ async def get_next(next_link=None): return pipeline_response + return AsyncItemPaged(get_next, extract_data) - return AsyncItemPaged( - get_next, extract_data - ) - list_by_resource_group.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/trafficmanagerprofiles'} # type: ignore + list_by_resource_group.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/trafficmanagerprofiles"} # type: ignore @distributed_trace - def list_by_subscription( - self, - **kwargs: Any - ) -> AsyncIterable["_models.ProfileListResult"]: + def list_by_subscription(self, **kwargs: Any) -> AsyncIterable["_models.Profile"]: """Lists all Traffic Manager profiles within a subscription. :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either ProfileListResult or the result of cls(response) - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.trafficmanager.models.ProfileListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either Profile or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.trafficmanager.models.Profile] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.ProfileListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-04-01-preview"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.ProfileListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_by_subscription_request( subscription_id=self._config.subscription_id, - template_url=self.list_by_subscription.metadata['url'], + api_version=api_version, + template_url=self.list_by_subscription.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore else: - - request = build_list_by_subscription_request( - subscription_id=self._config.subscription_id, - template_url=next_link, + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request @@ -217,7 +333,9 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: @@ -226,109 +344,195 @@ async def get_next(next_link=None): return pipeline_response + return AsyncItemPaged(get_next, extract_data) - return AsyncItemPaged( - get_next, extract_data - ) - list_by_subscription.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Network/trafficmanagerprofiles'} # type: ignore + list_by_subscription.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Network/trafficmanagerprofiles"} # type: ignore @distributed_trace_async - async def get( - self, - resource_group_name: str, - profile_name: str, - **kwargs: Any - ) -> "_models.Profile": + async def get(self, resource_group_name: str, profile_name: str, **kwargs: Any) -> _models.Profile: """Gets a Traffic Manager profile. - :param resource_group_name: The name of the resource group containing the Traffic Manager - profile. + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param profile_name: The name of the Traffic Manager profile. + :param profile_name: The name of the Traffic Manager profile. Required. :type profile_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: Profile, or the result of cls(response) + :return: Profile or the result of cls(response) :rtype: ~azure.mgmt.trafficmanager.models.Profile - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Profile"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-04-01-preview"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.Profile] - request = build_get_request( resource_group_name=resource_group_name, profile_name=profile_name, subscription_id=self._config.subscription_id, - template_url=self.get.metadata['url'], + 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) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - 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('Profile', pipeline_response) + deserialized = self._deserialize("Profile", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/trafficmanagerprofiles/{profileName}'} # type: ignore + get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/trafficmanagerprofiles/{profileName}"} # type: ignore - - @distributed_trace_async + @overload async def create_or_update( self, resource_group_name: str, profile_name: str, - parameters: "_models.Profile", + parameters: _models.Profile, + *, + content_type: str = "application/json", **kwargs: Any - ) -> "_models.Profile": + ) -> _models.Profile: """Create or update a Traffic Manager profile. - :param resource_group_name: The name of the resource group containing the Traffic Manager - profile. + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param profile_name: The name of the Traffic Manager profile. + :param profile_name: The name of the Traffic Manager profile. Required. :type profile_name: str :param parameters: The Traffic Manager profile parameters supplied to the CreateOrUpdate - operation. + operation. Required. :type parameters: ~azure.mgmt.trafficmanager.models.Profile + :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: Profile, or the result of cls(response) + :return: Profile or the result of cls(response) :rtype: ~azure.mgmt.trafficmanager.models.Profile - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_or_update( + self, + resource_group_name: str, + profile_name: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Profile: + """Create or update a Traffic Manager profile. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param profile_name: The name of the Traffic Manager profile. Required. + :type profile_name: str + :param parameters: The Traffic Manager profile parameters supplied to the CreateOrUpdate + operation. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: Profile or the result of cls(response) + :rtype: ~azure.mgmt.trafficmanager.models.Profile + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create_or_update( + self, resource_group_name: str, profile_name: str, parameters: Union[_models.Profile, IO], **kwargs: Any + ) -> _models.Profile: + """Create or update a Traffic Manager profile. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param profile_name: The name of the Traffic Manager profile. Required. + :type profile_name: str + :param parameters: The Traffic Manager profile parameters supplied to the CreateOrUpdate + operation. Is either a model type or a IO type. Required. + :type parameters: ~azure.mgmt.trafficmanager.models.Profile 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: Profile or the result of cls(response) + :rtype: ~azure.mgmt.trafficmanager.models.Profile + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Profile"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - _json = self._serialize.body(parameters, 'Profile') + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-04-01-preview"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.Profile] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "Profile") request = build_create_or_update_request( resource_group_name=resource_group_name, profile_name=profile_name, subscription_id=self._config.subscription_id, + api_version=api_version, content_type=content_type, json=_json, - template_url=self.create_or_update.metadata['url'], + 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) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 201]: @@ -336,55 +540,66 @@ async def create_or_update( raise HttpResponseError(response=response, error_format=ARMErrorFormat) if response.status_code == 200: - deserialized = self._deserialize('Profile', pipeline_response) + deserialized = self._deserialize("Profile", pipeline_response) if response.status_code == 201: - deserialized = self._deserialize('Profile', pipeline_response) + deserialized = self._deserialize("Profile", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/trafficmanagerprofiles/{profileName}'} # type: ignore - + create_or_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/trafficmanagerprofiles/{profileName}"} # type: ignore @distributed_trace_async async def delete( - self, - resource_group_name: str, - profile_name: str, - **kwargs: Any - ) -> Optional["_models.DeleteOperationResult"]: + self, resource_group_name: str, profile_name: str, **kwargs: Any + ) -> Optional[_models.DeleteOperationResult]: """Deletes a Traffic Manager profile. - :param resource_group_name: The name of the resource group containing the Traffic Manager - profile to be deleted. + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param profile_name: The name of the Traffic Manager profile to be deleted. + :param profile_name: The name of the Traffic Manager profile to be deleted. Required. :type profile_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: DeleteOperationResult, or the result of cls(response) + :return: DeleteOperationResult or None or the result of cls(response) :rtype: ~azure.mgmt.trafficmanager.models.DeleteOperationResult or None - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.DeleteOperationResult"]] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-04-01-preview"] + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.DeleteOperationResult]] - request = build_delete_request( resource_group_name=resource_group_name, profile_name=profile_name, subscription_id=self._config.subscription_id, - template_url=self.delete.metadata['url'], + 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) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 204]: @@ -393,72 +608,150 @@ async def delete( deserialized = None if response.status_code == 200: - deserialized = self._deserialize('DeleteOperationResult', pipeline_response) + deserialized = self._deserialize("DeleteOperationResult", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/trafficmanagerprofiles/{profileName}'} # type: ignore - + delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/trafficmanagerprofiles/{profileName}"} # type: ignore - @distributed_trace_async + @overload async def update( self, resource_group_name: str, profile_name: str, - parameters: "_models.Profile", + parameters: _models.Profile, + *, + content_type: str = "application/json", **kwargs: Any - ) -> "_models.Profile": + ) -> _models.Profile: """Update a Traffic Manager profile. - :param resource_group_name: The name of the resource group containing the Traffic Manager - profile. + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param profile_name: The name of the Traffic Manager profile. + :param profile_name: The name of the Traffic Manager profile. Required. :type profile_name: str :param parameters: The Traffic Manager profile parameters supplied to the Update operation. + Required. :type parameters: ~azure.mgmt.trafficmanager.models.Profile + :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: Profile, or the result of cls(response) + :return: Profile or the result of cls(response) :rtype: ~azure.mgmt.trafficmanager.models.Profile - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def update( + self, + resource_group_name: str, + profile_name: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Profile: + """Update a Traffic Manager profile. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param profile_name: The name of the Traffic Manager profile. Required. + :type profile_name: str + :param parameters: The Traffic Manager profile parameters supplied to the Update operation. + Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: Profile or the result of cls(response) + :rtype: ~azure.mgmt.trafficmanager.models.Profile + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def update( + self, resource_group_name: str, profile_name: str, parameters: Union[_models.Profile, IO], **kwargs: Any + ) -> _models.Profile: + """Update a Traffic Manager profile. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param profile_name: The name of the Traffic Manager profile. Required. + :type profile_name: str + :param parameters: The Traffic Manager profile parameters supplied to the Update operation. Is + either a model type or a IO type. Required. + :type parameters: ~azure.mgmt.trafficmanager.models.Profile 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: Profile or the result of cls(response) + :rtype: ~azure.mgmt.trafficmanager.models.Profile + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Profile"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-04-01-preview"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.Profile] - _json = self._serialize.body(parameters, 'Profile') + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "Profile") request = build_update_request( resource_group_name=resource_group_name, profile_name=profile_name, subscription_id=self._config.subscription_id, + api_version=api_version, content_type=content_type, json=_json, - template_url=self.update.metadata['url'], + content=_content, + template_url=self.update.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('Profile', pipeline_response) + deserialized = self._deserialize("Profile", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/trafficmanagerprofiles/{profileName}'} # type: ignore - + update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/trafficmanagerprofiles/{profileName}"} # type: ignore diff --git a/sdk/trafficmanager/azure-mgmt-trafficmanager/azure/mgmt/trafficmanager/aio/operations/_traffic_manager_user_metrics_keys_operations.py b/sdk/trafficmanager/azure-mgmt-trafficmanager/azure/mgmt/trafficmanager/aio/operations/_traffic_manager_user_metrics_keys_operations.py index d1fa783ec420..0ea2c5f69e91 100644 --- a/sdk/trafficmanager/azure-mgmt-trafficmanager/azure/mgmt/trafficmanager/aio/operations/_traffic_manager_user_metrics_keys_operations.py +++ b/sdk/trafficmanager/azure-mgmt-trafficmanager/azure/mgmt/trafficmanager/aio/operations/_traffic_manager_user_metrics_keys_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,170 +6,217 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -import functools -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, Optional, TypeVar + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.rest import HttpRequest from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models from ..._vendor import _convert_request -from ...operations._traffic_manager_user_metrics_keys_operations import build_create_or_update_request, build_delete_request, build_get_request -T = TypeVar('T') +from ...operations._traffic_manager_user_metrics_keys_operations import ( + build_create_or_update_request, + build_delete_request, + build_get_request, +) + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class TrafficManagerUserMetricsKeysOperations: - """TrafficManagerUserMetricsKeysOperations 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 TrafficManagerUserMetricsKeysOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.trafficmanager.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.trafficmanager.aio.TrafficManagerManagementClient`'s + :attr:`traffic_manager_user_metrics_keys` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace_async - async def get( - self, - **kwargs: Any - ) -> "_models.UserMetricsModel": + async def get(self, **kwargs: Any) -> _models.UserMetricsModel: """Get the subscription-level key used for Real User Metrics collection. :keyword callable cls: A custom type or function that will be passed the direct response - :return: UserMetricsModel, or the result of cls(response) + :return: UserMetricsModel or the result of cls(response) :rtype: ~azure.mgmt.trafficmanager.models.UserMetricsModel - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.UserMetricsModel"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-04-01-preview"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.UserMetricsModel] - request = build_get_request( subscription_id=self._config.subscription_id, - template_url=self.get.metadata['url'], + 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) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - 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('UserMetricsModel', pipeline_response) + deserialized = self._deserialize("UserMetricsModel", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Network/trafficManagerUserMetricsKeys/default'} # type: ignore - + get.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Network/trafficManagerUserMetricsKeys/default"} # type: ignore @distributed_trace_async - async def create_or_update( - self, - **kwargs: Any - ) -> "_models.UserMetricsModel": + async def create_or_update(self, **kwargs: Any) -> _models.UserMetricsModel: """Create or update a subscription-level key used for Real User Metrics collection. :keyword callable cls: A custom type or function that will be passed the direct response - :return: UserMetricsModel, or the result of cls(response) + :return: UserMetricsModel or the result of cls(response) :rtype: ~azure.mgmt.trafficmanager.models.UserMetricsModel - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.UserMetricsModel"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-04-01-preview"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.UserMetricsModel] - request = build_create_or_update_request( subscription_id=self._config.subscription_id, - template_url=self.create_or_update.metadata['url'], + api_version=api_version, + template_url=self.create_or_update.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [201]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('UserMetricsModel', pipeline_response) + deserialized = self._deserialize("UserMetricsModel", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Network/trafficManagerUserMetricsKeys/default'} # type: ignore - + create_or_update.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Network/trafficManagerUserMetricsKeys/default"} # type: ignore @distributed_trace_async - async def delete( - self, - **kwargs: Any - ) -> "_models.DeleteOperationResult": + async def delete(self, **kwargs: Any) -> _models.DeleteOperationResult: """Delete a subscription-level key used for Real User Metrics collection. :keyword callable cls: A custom type or function that will be passed the direct response - :return: DeleteOperationResult, or the result of cls(response) + :return: DeleteOperationResult or the result of cls(response) :rtype: ~azure.mgmt.trafficmanager.models.DeleteOperationResult - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.DeleteOperationResult"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-04-01-preview"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.DeleteOperationResult] - request = build_delete_request( subscription_id=self._config.subscription_id, - template_url=self.delete.metadata['url'], + 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) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - 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('DeleteOperationResult', pipeline_response) + deserialized = self._deserialize("DeleteOperationResult", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - delete.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Network/trafficManagerUserMetricsKeys/default'} # type: ignore - + delete.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Network/trafficManagerUserMetricsKeys/default"} # type: ignore diff --git a/sdk/trafficmanager/azure-mgmt-trafficmanager/azure/mgmt/trafficmanager/models/__init__.py b/sdk/trafficmanager/azure-mgmt-trafficmanager/azure/mgmt/trafficmanager/models/__init__.py index 74c8478fffd5..4f914a4b9f8a 100644 --- a/sdk/trafficmanager/azure-mgmt-trafficmanager/azure/mgmt/trafficmanager/models/__init__.py +++ b/sdk/trafficmanager/azure-mgmt-trafficmanager/azure/mgmt/trafficmanager/models/__init__.py @@ -30,50 +30,54 @@ from ._models_py3 import TrafficManagerNameAvailability from ._models_py3 import UserMetricsModel - -from ._traffic_manager_management_client_enums import ( - AllowedEndpointRecordType, - EndpointMonitorStatus, - EndpointStatus, - EndpointType, - MonitorProtocol, - ProfileMonitorStatus, - ProfileStatus, - TrafficRoutingMethod, - TrafficViewEnrollmentStatus, -) +from ._traffic_manager_management_client_enums import AllowedEndpointRecordType +from ._traffic_manager_management_client_enums import AlwaysServe +from ._traffic_manager_management_client_enums import EndpointMonitorStatus +from ._traffic_manager_management_client_enums import EndpointStatus +from ._traffic_manager_management_client_enums import EndpointType +from ._traffic_manager_management_client_enums import MonitorProtocol +from ._traffic_manager_management_client_enums import ProfileMonitorStatus +from ._traffic_manager_management_client_enums import ProfileStatus +from ._traffic_manager_management_client_enums import TrafficRoutingMethod +from ._traffic_manager_management_client_enums import TrafficViewEnrollmentStatus +from ._patch import __all__ as _patch_all +from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import +from ._patch import patch_sdk as _patch_sdk __all__ = [ - 'CheckTrafficManagerRelativeDnsNameAvailabilityParameters', - 'CloudErrorBody', - 'DeleteOperationResult', - 'DnsConfig', - 'Endpoint', - 'EndpointPropertiesCustomHeadersItem', - 'EndpointPropertiesSubnetsItem', - 'HeatMapEndpoint', - 'HeatMapModel', - 'MonitorConfig', - 'MonitorConfigCustomHeadersItem', - 'MonitorConfigExpectedStatusCodeRangesItem', - 'Profile', - 'ProfileListResult', - 'ProxyResource', - 'QueryExperience', - 'Region', - 'Resource', - 'TrackedResource', - 'TrafficFlow', - 'TrafficManagerGeographicHierarchy', - 'TrafficManagerNameAvailability', - 'UserMetricsModel', - 'AllowedEndpointRecordType', - 'EndpointMonitorStatus', - 'EndpointStatus', - 'EndpointType', - 'MonitorProtocol', - 'ProfileMonitorStatus', - 'ProfileStatus', - 'TrafficRoutingMethod', - 'TrafficViewEnrollmentStatus', + "CheckTrafficManagerRelativeDnsNameAvailabilityParameters", + "CloudErrorBody", + "DeleteOperationResult", + "DnsConfig", + "Endpoint", + "EndpointPropertiesCustomHeadersItem", + "EndpointPropertiesSubnetsItem", + "HeatMapEndpoint", + "HeatMapModel", + "MonitorConfig", + "MonitorConfigCustomHeadersItem", + "MonitorConfigExpectedStatusCodeRangesItem", + "Profile", + "ProfileListResult", + "ProxyResource", + "QueryExperience", + "Region", + "Resource", + "TrackedResource", + "TrafficFlow", + "TrafficManagerGeographicHierarchy", + "TrafficManagerNameAvailability", + "UserMetricsModel", + "AllowedEndpointRecordType", + "AlwaysServe", + "EndpointMonitorStatus", + "EndpointStatus", + "EndpointType", + "MonitorProtocol", + "ProfileMonitorStatus", + "ProfileStatus", + "TrafficRoutingMethod", + "TrafficViewEnrollmentStatus", ] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/sdk/trafficmanager/azure-mgmt-trafficmanager/azure/mgmt/trafficmanager/models/_models_py3.py b/sdk/trafficmanager/azure-mgmt-trafficmanager/azure/mgmt/trafficmanager/models/_models_py3.py index 4238f37a1335..9453e1379d23 100644 --- a/sdk/trafficmanager/azure-mgmt-trafficmanager/azure/mgmt/trafficmanager/models/_models_py3.py +++ b/sdk/trafficmanager/azure-mgmt-trafficmanager/azure/mgmt/trafficmanager/models/_models_py3.py @@ -1,4 +1,5 @@ # coding=utf-8 +# pylint: disable=too-many-lines # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. @@ -7,14 +8,16 @@ # -------------------------------------------------------------------------- import datetime -from typing import Dict, List, Optional, Union +from typing import Dict, List, Optional, TYPE_CHECKING, Union -import msrest.serialization +from .. import _serialization -from ._traffic_manager_management_client_enums import * +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from .. import models as _models -class CheckTrafficManagerRelativeDnsNameAvailabilityParameters(msrest.serialization.Model): +class CheckTrafficManagerRelativeDnsNameAvailabilityParameters(_serialization.Model): """Parameters supplied to check Traffic Manager name operation. :ivar name: The name of the resource. @@ -24,29 +27,23 @@ class CheckTrafficManagerRelativeDnsNameAvailabilityParameters(msrest.serializat """ _attribute_map = { - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, } - def __init__( - self, - *, - name: Optional[str] = None, - type: Optional[str] = None, - **kwargs - ): + def __init__(self, *, name: Optional[str] = None, type: Optional[str] = None, **kwargs): """ :keyword name: The name of the resource. :paramtype name: str :keyword type: The type of the resource. :paramtype type: str """ - super(CheckTrafficManagerRelativeDnsNameAvailabilityParameters, self).__init__(**kwargs) + super().__init__(**kwargs) self.name = name self.type = type -class CloudErrorBody(msrest.serialization.Model): +class CloudErrorBody(_serialization.Model): """The content of an error returned by the Azure Resource Manager. :ivar code: Error code. @@ -60,10 +57,10 @@ class CloudErrorBody(msrest.serialization.Model): """ _attribute_map = { - 'code': {'key': 'code', 'type': 'str'}, - 'message': {'key': 'message', 'type': 'str'}, - 'target': {'key': 'target', 'type': 'str'}, - 'details': {'key': 'details', 'type': '[CloudErrorBody]'}, + "code": {"key": "code", "type": "str"}, + "message": {"key": "message", "type": "str"}, + "target": {"key": "target", "type": "str"}, + "details": {"key": "details", "type": "[CloudErrorBody]"}, } def __init__( @@ -72,7 +69,7 @@ def __init__( code: Optional[str] = None, message: Optional[str] = None, target: Optional[str] = None, - details: Optional[List["CloudErrorBody"]] = None, + details: Optional[List["_models.CloudErrorBody"]] = None, **kwargs ): """ @@ -85,14 +82,14 @@ def __init__( :keyword details: Error details. :paramtype details: list[~azure.mgmt.trafficmanager.models.CloudErrorBody] """ - super(CloudErrorBody, self).__init__(**kwargs) + super().__init__(**kwargs) self.code = code self.message = message self.target = target self.details = details -class DeleteOperationResult(msrest.serialization.Model): +class DeleteOperationResult(_serialization.Model): """The result of the request or operation. Variables are only populated by the server, and will be ignored when sending a request. @@ -102,24 +99,20 @@ class DeleteOperationResult(msrest.serialization.Model): """ _validation = { - 'operation_result': {'readonly': True}, + "operation_result": {"readonly": True}, } _attribute_map = { - 'operation_result': {'key': 'boolean', 'type': 'bool'}, + "operation_result": {"key": "boolean", "type": "bool"}, } - def __init__( - self, - **kwargs - ): - """ - """ - super(DeleteOperationResult, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.operation_result = None -class DnsConfig(msrest.serialization.Model): +class DnsConfig(_serialization.Model): """Class containing DNS settings in a Traffic Manager profile. Variables are only populated by the server, and will be ignored when sending a request. @@ -134,26 +127,20 @@ class DnsConfig(msrest.serialization.Model): :vartype fqdn: str :ivar ttl: The DNS Time-To-Live (TTL), in seconds. This informs the local DNS resolvers and DNS clients how long to cache DNS responses provided by this Traffic Manager profile. - :vartype ttl: long + :vartype ttl: int """ _validation = { - 'fqdn': {'readonly': True}, + "fqdn": {"readonly": True}, } _attribute_map = { - 'relative_name': {'key': 'relativeName', 'type': 'str'}, - 'fqdn': {'key': 'fqdn', 'type': 'str'}, - 'ttl': {'key': 'ttl', 'type': 'long'}, + "relative_name": {"key": "relativeName", "type": "str"}, + "fqdn": {"key": "fqdn", "type": "str"}, + "ttl": {"key": "ttl", "type": "int"}, } - def __init__( - self, - *, - relative_name: Optional[str] = None, - ttl: Optional[int] = None, - **kwargs - ): + def __init__(self, *, relative_name: Optional[str] = None, ttl: Optional[int] = None, **kwargs): """ :keyword relative_name: The relative DNS name provided by this Traffic Manager profile. This value is combined with the DNS domain name used by Azure Traffic Manager to form the @@ -161,15 +148,15 @@ def __init__( :paramtype relative_name: str :keyword ttl: The DNS Time-To-Live (TTL), in seconds. This informs the local DNS resolvers and DNS clients how long to cache DNS responses provided by this Traffic Manager profile. - :paramtype ttl: long + :paramtype ttl: int """ - super(DnsConfig, self).__init__(**kwargs) + super().__init__(**kwargs) self.relative_name = relative_name self.fqdn = None self.ttl = ttl -class Resource(msrest.serialization.Model): +class Resource(_serialization.Model): """The core properties of ARM resources. :ivar id: Fully qualified resource Id for the resource. Ex - @@ -182,15 +169,15 @@ class Resource(msrest.serialization.Model): """ _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, *, - id: Optional[str] = None, + id: Optional[str] = None, # pylint: disable=redefined-builtin name: Optional[str] = None, type: Optional[str] = None, **kwargs @@ -204,7 +191,7 @@ def __init__( :keyword type: The type of the resource. Ex- Microsoft.Network/trafficManagerProfiles. :paramtype type: str """ - super(Resource, self).__init__(**kwargs) + super().__init__(**kwargs) self.id = id self.name = name self.type = type @@ -223,15 +210,15 @@ class ProxyResource(Resource): """ _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, *, - id: Optional[str] = None, + id: Optional[str] = None, # pylint: disable=redefined-builtin name: Optional[str] = None, type: Optional[str] = None, **kwargs @@ -245,10 +232,10 @@ def __init__( :keyword type: The type of the resource. Ex- Microsoft.Network/trafficManagerProfiles. :paramtype type: str """ - super(ProxyResource, self).__init__(id=id, name=name, type=type, **kwargs) + super().__init__(id=id, name=name, type=type, **kwargs) -class Endpoint(ProxyResource): +class Endpoint(ProxyResource): # pylint: disable=too-many-instance-attributes """Class representing a Traffic Manager endpoint. :ivar id: Fully qualified resource Id for the resource. Ex - @@ -265,36 +252,36 @@ class Endpoint(ProxyResource): returns this value in DNS responses to direct traffic to this endpoint. :vartype target: str :ivar endpoint_status: The status of the endpoint. If the endpoint is Enabled, it is probed for - endpoint health and is included in the traffic routing method. Possible values include: - "Enabled", "Disabled". + endpoint health and is included in the traffic routing method. Known values are: "Enabled" and + "Disabled". :vartype endpoint_status: str or ~azure.mgmt.trafficmanager.models.EndpointStatus :ivar weight: The weight of this endpoint when using the 'Weighted' traffic routing method. Possible values are from 1 to 1000. - :vartype weight: long + :vartype weight: int :ivar priority: The priority of this endpoint when using the 'Priority' traffic routing method. Possible values are from 1 to 1000, lower values represent higher priority. This is an optional parameter. If specified, it must be specified on all endpoints, and no two endpoints can share the same priority value. - :vartype priority: long + :vartype priority: int :ivar endpoint_location: Specifies the location of the external or nested endpoints when using the 'Performance' traffic routing method. :vartype endpoint_location: str - :ivar endpoint_monitor_status: The monitoring status of the endpoint. Possible values include: - "CheckingEndpoint", "Online", "Degraded", "Disabled", "Inactive", "Stopped". + :ivar endpoint_monitor_status: The monitoring status of the endpoint. Known values are: + "CheckingEndpoint", "Online", "Degraded", "Disabled", "Inactive", and "Stopped". :vartype endpoint_monitor_status: str or ~azure.mgmt.trafficmanager.models.EndpointMonitorStatus :ivar min_child_endpoints: The minimum number of endpoints that must be available in the child profile in order for the parent profile to be considered available. Only applicable to endpoint of type 'NestedEndpoints'. - :vartype min_child_endpoints: long + :vartype min_child_endpoints: int :ivar min_child_endpoints_i_pv4: The minimum number of IPv4 (DNS record type A) endpoints that must be available in the child profile in order for the parent profile to be considered available. Only applicable to endpoint of type 'NestedEndpoints'. - :vartype min_child_endpoints_i_pv4: long + :vartype min_child_endpoints_i_pv4: int :ivar min_child_endpoints_i_pv6: The minimum number of IPv6 (DNS record type AAAA) endpoints that must be available in the child profile in order for the parent profile to be considered available. Only applicable to endpoint of type 'NestedEndpoints'. - :vartype min_child_endpoints_i_pv6: long + :vartype min_child_endpoints_i_pv6: int :ivar geo_mapping: The list of countries/regions mapped to this endpoint when using the 'Geographic' traffic routing method. Please consult Traffic Manager Geographic documentation for a full list of accepted values. @@ -306,46 +293,52 @@ class Endpoint(ProxyResource): :ivar custom_headers: List of custom headers. :vartype custom_headers: list[~azure.mgmt.trafficmanager.models.EndpointPropertiesCustomHeadersItem] + :ivar always_serve: If Always Serve is enabled, probing for endpoint health will be disabled + and endpoints will be included in the traffic routing method. Known values are: "Enabled" and + "Disabled". + :vartype always_serve: str or ~azure.mgmt.trafficmanager.models.AlwaysServe """ _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'target_resource_id': {'key': 'properties.targetResourceId', 'type': 'str'}, - 'target': {'key': 'properties.target', 'type': 'str'}, - 'endpoint_status': {'key': 'properties.endpointStatus', 'type': 'str'}, - 'weight': {'key': 'properties.weight', 'type': 'long'}, - 'priority': {'key': 'properties.priority', 'type': 'long'}, - 'endpoint_location': {'key': 'properties.endpointLocation', 'type': 'str'}, - 'endpoint_monitor_status': {'key': 'properties.endpointMonitorStatus', 'type': 'str'}, - 'min_child_endpoints': {'key': 'properties.minChildEndpoints', 'type': 'long'}, - 'min_child_endpoints_i_pv4': {'key': 'properties.minChildEndpointsIPv4', 'type': 'long'}, - 'min_child_endpoints_i_pv6': {'key': 'properties.minChildEndpointsIPv6', 'type': 'long'}, - 'geo_mapping': {'key': 'properties.geoMapping', 'type': '[str]'}, - 'subnets': {'key': 'properties.subnets', 'type': '[EndpointPropertiesSubnetsItem]'}, - 'custom_headers': {'key': 'properties.customHeaders', 'type': '[EndpointPropertiesCustomHeadersItem]'}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "target_resource_id": {"key": "properties.targetResourceId", "type": "str"}, + "target": {"key": "properties.target", "type": "str"}, + "endpoint_status": {"key": "properties.endpointStatus", "type": "str"}, + "weight": {"key": "properties.weight", "type": "int"}, + "priority": {"key": "properties.priority", "type": "int"}, + "endpoint_location": {"key": "properties.endpointLocation", "type": "str"}, + "endpoint_monitor_status": {"key": "properties.endpointMonitorStatus", "type": "str"}, + "min_child_endpoints": {"key": "properties.minChildEndpoints", "type": "int"}, + "min_child_endpoints_i_pv4": {"key": "properties.minChildEndpointsIPv4", "type": "int"}, + "min_child_endpoints_i_pv6": {"key": "properties.minChildEndpointsIPv6", "type": "int"}, + "geo_mapping": {"key": "properties.geoMapping", "type": "[str]"}, + "subnets": {"key": "properties.subnets", "type": "[EndpointPropertiesSubnetsItem]"}, + "custom_headers": {"key": "properties.customHeaders", "type": "[EndpointPropertiesCustomHeadersItem]"}, + "always_serve": {"key": "properties.alwaysServe", "type": "str"}, } def __init__( self, *, - id: Optional[str] = None, + id: Optional[str] = None, # pylint: disable=redefined-builtin name: Optional[str] = None, type: Optional[str] = None, target_resource_id: Optional[str] = None, target: Optional[str] = None, - endpoint_status: Optional[Union[str, "EndpointStatus"]] = None, + endpoint_status: Optional[Union[str, "_models.EndpointStatus"]] = None, weight: Optional[int] = None, priority: Optional[int] = None, endpoint_location: Optional[str] = None, - endpoint_monitor_status: Optional[Union[str, "EndpointMonitorStatus"]] = None, + endpoint_monitor_status: Optional[Union[str, "_models.EndpointMonitorStatus"]] = None, min_child_endpoints: Optional[int] = None, min_child_endpoints_i_pv4: Optional[int] = None, min_child_endpoints_i_pv6: Optional[int] = None, geo_mapping: Optional[List[str]] = None, - subnets: Optional[List["EndpointPropertiesSubnetsItem"]] = None, - custom_headers: Optional[List["EndpointPropertiesCustomHeadersItem"]] = None, + subnets: Optional[List["_models.EndpointPropertiesSubnetsItem"]] = None, + custom_headers: Optional[List["_models.EndpointPropertiesCustomHeadersItem"]] = None, + always_serve: Optional[Union[str, "_models.AlwaysServe"]] = None, **kwargs ): """ @@ -363,36 +356,36 @@ def __init__( returns this value in DNS responses to direct traffic to this endpoint. :paramtype target: str :keyword endpoint_status: The status of the endpoint. If the endpoint is Enabled, it is probed - for endpoint health and is included in the traffic routing method. Possible values include: - "Enabled", "Disabled". + for endpoint health and is included in the traffic routing method. Known values are: "Enabled" + and "Disabled". :paramtype endpoint_status: str or ~azure.mgmt.trafficmanager.models.EndpointStatus :keyword weight: The weight of this endpoint when using the 'Weighted' traffic routing method. Possible values are from 1 to 1000. - :paramtype weight: long + :paramtype weight: int :keyword priority: The priority of this endpoint when using the 'Priority' traffic routing method. Possible values are from 1 to 1000, lower values represent higher priority. This is an optional parameter. If specified, it must be specified on all endpoints, and no two endpoints can share the same priority value. - :paramtype priority: long + :paramtype priority: int :keyword endpoint_location: Specifies the location of the external or nested endpoints when using the 'Performance' traffic routing method. :paramtype endpoint_location: str - :keyword endpoint_monitor_status: The monitoring status of the endpoint. Possible values - include: "CheckingEndpoint", "Online", "Degraded", "Disabled", "Inactive", "Stopped". + :keyword endpoint_monitor_status: The monitoring status of the endpoint. Known values are: + "CheckingEndpoint", "Online", "Degraded", "Disabled", "Inactive", and "Stopped". :paramtype endpoint_monitor_status: str or ~azure.mgmt.trafficmanager.models.EndpointMonitorStatus :keyword min_child_endpoints: The minimum number of endpoints that must be available in the child profile in order for the parent profile to be considered available. Only applicable to endpoint of type 'NestedEndpoints'. - :paramtype min_child_endpoints: long + :paramtype min_child_endpoints: int :keyword min_child_endpoints_i_pv4: The minimum number of IPv4 (DNS record type A) endpoints that must be available in the child profile in order for the parent profile to be considered available. Only applicable to endpoint of type 'NestedEndpoints'. - :paramtype min_child_endpoints_i_pv4: long + :paramtype min_child_endpoints_i_pv4: int :keyword min_child_endpoints_i_pv6: The minimum number of IPv6 (DNS record type AAAA) endpoints that must be available in the child profile in order for the parent profile to be considered available. Only applicable to endpoint of type 'NestedEndpoints'. - :paramtype min_child_endpoints_i_pv6: long + :paramtype min_child_endpoints_i_pv6: int :keyword geo_mapping: The list of countries/regions mapped to this endpoint when using the 'Geographic' traffic routing method. Please consult Traffic Manager Geographic documentation for a full list of accepted values. @@ -404,8 +397,12 @@ def __init__( :keyword custom_headers: List of custom headers. :paramtype custom_headers: list[~azure.mgmt.trafficmanager.models.EndpointPropertiesCustomHeadersItem] + :keyword always_serve: If Always Serve is enabled, probing for endpoint health will be disabled + and endpoints will be included in the traffic routing method. Known values are: "Enabled" and + "Disabled". + :paramtype always_serve: str or ~azure.mgmt.trafficmanager.models.AlwaysServe """ - super(Endpoint, self).__init__(id=id, name=name, type=type, **kwargs) + super().__init__(id=id, name=name, type=type, **kwargs) self.target_resource_id = target_resource_id self.target = target self.endpoint_status = endpoint_status @@ -419,9 +416,10 @@ def __init__( self.geo_mapping = geo_mapping self.subnets = subnets self.custom_headers = custom_headers + self.always_serve = always_serve -class EndpointPropertiesCustomHeadersItem(msrest.serialization.Model): +class EndpointPropertiesCustomHeadersItem(_serialization.Model): """Custom header name and value. :ivar name: Header name. @@ -431,29 +429,23 @@ class EndpointPropertiesCustomHeadersItem(msrest.serialization.Model): """ _attribute_map = { - 'name': {'key': 'name', 'type': 'str'}, - 'value': {'key': 'value', 'type': 'str'}, + "name": {"key": "name", "type": "str"}, + "value": {"key": "value", "type": "str"}, } - def __init__( - self, - *, - name: Optional[str] = None, - value: Optional[str] = None, - **kwargs - ): + def __init__(self, *, name: Optional[str] = None, value: Optional[str] = None, **kwargs): """ :keyword name: Header name. :paramtype name: str :keyword value: Header value. :paramtype value: str """ - super(EndpointPropertiesCustomHeadersItem, self).__init__(**kwargs) + super().__init__(**kwargs) self.name = name self.value = value -class EndpointPropertiesSubnetsItem(msrest.serialization.Model): +class EndpointPropertiesSubnetsItem(_serialization.Model): """Subnet first address, scope, and/or last address. :ivar first: First address in the subnet. @@ -465,18 +457,13 @@ class EndpointPropertiesSubnetsItem(msrest.serialization.Model): """ _attribute_map = { - 'first': {'key': 'first', 'type': 'str'}, - 'last': {'key': 'last', 'type': 'str'}, - 'scope': {'key': 'scope', 'type': 'int'}, + "first": {"key": "first", "type": "str"}, + "last": {"key": "last", "type": "str"}, + "scope": {"key": "scope", "type": "int"}, } def __init__( - self, - *, - first: Optional[str] = None, - last: Optional[str] = None, - scope: Optional[int] = None, - **kwargs + self, *, first: Optional[str] = None, last: Optional[str] = None, scope: Optional[int] = None, **kwargs ): """ :keyword first: First address in the subnet. @@ -486,13 +473,13 @@ def __init__( :keyword scope: Block size (number of leading bits in the subnet mask). :paramtype scope: int """ - super(EndpointPropertiesSubnetsItem, self).__init__(**kwargs) + super().__init__(**kwargs) self.first = first self.last = last self.scope = scope -class HeatMapEndpoint(msrest.serialization.Model): +class HeatMapEndpoint(_serialization.Model): """Class which is a sparse representation of a Traffic Manager endpoint. :ivar resource_id: The ARM Resource ID of this Traffic Manager endpoint. @@ -502,24 +489,18 @@ class HeatMapEndpoint(msrest.serialization.Model): """ _attribute_map = { - 'resource_id': {'key': 'resourceId', 'type': 'str'}, - 'endpoint_id': {'key': 'endpointId', 'type': 'int'}, + "resource_id": {"key": "resourceId", "type": "str"}, + "endpoint_id": {"key": "endpointId", "type": "int"}, } - def __init__( - self, - *, - resource_id: Optional[str] = None, - endpoint_id: Optional[int] = None, - **kwargs - ): + def __init__(self, *, resource_id: Optional[str] = None, endpoint_id: Optional[int] = None, **kwargs): """ :keyword resource_id: The ARM Resource ID of this Traffic Manager endpoint. :paramtype resource_id: str :keyword endpoint_id: A number uniquely identifying this endpoint in query experiences. :paramtype endpoint_id: int """ - super(HeatMapEndpoint, self).__init__(**kwargs) + super().__init__(**kwargs) self.resource_id = resource_id self.endpoint_id = endpoint_id @@ -545,25 +526,25 @@ class HeatMapModel(ProxyResource): """ _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'start_time': {'key': 'properties.startTime', 'type': 'iso-8601'}, - 'end_time': {'key': 'properties.endTime', 'type': 'iso-8601'}, - 'endpoints': {'key': 'properties.endpoints', 'type': '[HeatMapEndpoint]'}, - 'traffic_flows': {'key': 'properties.trafficFlows', 'type': '[TrafficFlow]'}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "start_time": {"key": "properties.startTime", "type": "iso-8601"}, + "end_time": {"key": "properties.endTime", "type": "iso-8601"}, + "endpoints": {"key": "properties.endpoints", "type": "[HeatMapEndpoint]"}, + "traffic_flows": {"key": "properties.trafficFlows", "type": "[TrafficFlow]"}, } def __init__( self, *, - id: Optional[str] = None, + id: Optional[str] = None, # pylint: disable=redefined-builtin name: Optional[str] = None, type: Optional[str] = None, start_time: Optional[datetime.datetime] = None, end_time: Optional[datetime.datetime] = None, - endpoints: Optional[List["HeatMapEndpoint"]] = None, - traffic_flows: Optional[List["TrafficFlow"]] = None, + endpoints: Optional[List["_models.HeatMapEndpoint"]] = None, + traffic_flows: Optional[List["_models.TrafficFlow"]] = None, **kwargs ): """ @@ -583,37 +564,37 @@ def __init__( :keyword traffic_flows: The traffic flows produced in this HeatMap calculation. :paramtype traffic_flows: list[~azure.mgmt.trafficmanager.models.TrafficFlow] """ - super(HeatMapModel, self).__init__(id=id, name=name, type=type, **kwargs) + super().__init__(id=id, name=name, type=type, **kwargs) self.start_time = start_time self.end_time = end_time self.endpoints = endpoints self.traffic_flows = traffic_flows -class MonitorConfig(msrest.serialization.Model): +class MonitorConfig(_serialization.Model): """Class containing endpoint monitoring settings in a Traffic Manager profile. :ivar profile_monitor_status: The profile-level monitoring status of the Traffic Manager - profile. Possible values include: "CheckingEndpoints", "Online", "Degraded", "Disabled", + profile. Known values are: "CheckingEndpoints", "Online", "Degraded", "Disabled", and "Inactive". :vartype profile_monitor_status: str or ~azure.mgmt.trafficmanager.models.ProfileMonitorStatus - :ivar protocol: The protocol (HTTP, HTTPS or TCP) used to probe for endpoint health. Possible - values include: "HTTP", "HTTPS", "TCP". + :ivar protocol: The protocol (HTTP, HTTPS or TCP) used to probe for endpoint health. Known + values are: "HTTP", "HTTPS", and "TCP". :vartype protocol: str or ~azure.mgmt.trafficmanager.models.MonitorProtocol :ivar port: The TCP port used to probe for endpoint health. - :vartype port: long + :vartype port: int :ivar path: The path relative to the endpoint domain name used to probe for endpoint health. :vartype path: str :ivar interval_in_seconds: The monitor interval for endpoints in this profile. This is the interval at which Traffic Manager will check the health of each endpoint in this profile. - :vartype interval_in_seconds: long + :vartype interval_in_seconds: int :ivar timeout_in_seconds: The monitor timeout for endpoints in this profile. This is the time that Traffic Manager allows endpoints in this profile to response to the health check. - :vartype timeout_in_seconds: long + :vartype timeout_in_seconds: int :ivar tolerated_number_of_failures: The number of consecutive failed health check that Traffic Manager tolerates before declaring an endpoint in this profile Degraded after the next failed health check. - :vartype tolerated_number_of_failures: long + :vartype tolerated_number_of_failures: int :ivar custom_headers: List of custom headers. :vartype custom_headers: list[~azure.mgmt.trafficmanager.models.MonitorConfigCustomHeadersItem] :ivar expected_status_code_ranges: List of expected status code ranges. @@ -622,54 +603,57 @@ class MonitorConfig(msrest.serialization.Model): """ _attribute_map = { - 'profile_monitor_status': {'key': 'profileMonitorStatus', 'type': 'str'}, - 'protocol': {'key': 'protocol', 'type': 'str'}, - 'port': {'key': 'port', 'type': 'long'}, - 'path': {'key': 'path', 'type': 'str'}, - 'interval_in_seconds': {'key': 'intervalInSeconds', 'type': 'long'}, - 'timeout_in_seconds': {'key': 'timeoutInSeconds', 'type': 'long'}, - 'tolerated_number_of_failures': {'key': 'toleratedNumberOfFailures', 'type': 'long'}, - 'custom_headers': {'key': 'customHeaders', 'type': '[MonitorConfigCustomHeadersItem]'}, - 'expected_status_code_ranges': {'key': 'expectedStatusCodeRanges', 'type': '[MonitorConfigExpectedStatusCodeRangesItem]'}, + "profile_monitor_status": {"key": "profileMonitorStatus", "type": "str"}, + "protocol": {"key": "protocol", "type": "str"}, + "port": {"key": "port", "type": "int"}, + "path": {"key": "path", "type": "str"}, + "interval_in_seconds": {"key": "intervalInSeconds", "type": "int"}, + "timeout_in_seconds": {"key": "timeoutInSeconds", "type": "int"}, + "tolerated_number_of_failures": {"key": "toleratedNumberOfFailures", "type": "int"}, + "custom_headers": {"key": "customHeaders", "type": "[MonitorConfigCustomHeadersItem]"}, + "expected_status_code_ranges": { + "key": "expectedStatusCodeRanges", + "type": "[MonitorConfigExpectedStatusCodeRangesItem]", + }, } def __init__( self, *, - profile_monitor_status: Optional[Union[str, "ProfileMonitorStatus"]] = None, - protocol: Optional[Union[str, "MonitorProtocol"]] = None, + profile_monitor_status: Optional[Union[str, "_models.ProfileMonitorStatus"]] = None, + protocol: Optional[Union[str, "_models.MonitorProtocol"]] = None, port: Optional[int] = None, path: Optional[str] = None, interval_in_seconds: Optional[int] = None, timeout_in_seconds: Optional[int] = None, tolerated_number_of_failures: Optional[int] = None, - custom_headers: Optional[List["MonitorConfigCustomHeadersItem"]] = None, - expected_status_code_ranges: Optional[List["MonitorConfigExpectedStatusCodeRangesItem"]] = None, + custom_headers: Optional[List["_models.MonitorConfigCustomHeadersItem"]] = None, + expected_status_code_ranges: Optional[List["_models.MonitorConfigExpectedStatusCodeRangesItem"]] = None, **kwargs ): """ :keyword profile_monitor_status: The profile-level monitoring status of the Traffic Manager - profile. Possible values include: "CheckingEndpoints", "Online", "Degraded", "Disabled", + profile. Known values are: "CheckingEndpoints", "Online", "Degraded", "Disabled", and "Inactive". :paramtype profile_monitor_status: str or ~azure.mgmt.trafficmanager.models.ProfileMonitorStatus - :keyword protocol: The protocol (HTTP, HTTPS or TCP) used to probe for endpoint health. - Possible values include: "HTTP", "HTTPS", "TCP". + :keyword protocol: The protocol (HTTP, HTTPS or TCP) used to probe for endpoint health. Known + values are: "HTTP", "HTTPS", and "TCP". :paramtype protocol: str or ~azure.mgmt.trafficmanager.models.MonitorProtocol :keyword port: The TCP port used to probe for endpoint health. - :paramtype port: long + :paramtype port: int :keyword path: The path relative to the endpoint domain name used to probe for endpoint health. :paramtype path: str :keyword interval_in_seconds: The monitor interval for endpoints in this profile. This is the interval at which Traffic Manager will check the health of each endpoint in this profile. - :paramtype interval_in_seconds: long + :paramtype interval_in_seconds: int :keyword timeout_in_seconds: The monitor timeout for endpoints in this profile. This is the time that Traffic Manager allows endpoints in this profile to response to the health check. - :paramtype timeout_in_seconds: long + :paramtype timeout_in_seconds: int :keyword tolerated_number_of_failures: The number of consecutive failed health check that Traffic Manager tolerates before declaring an endpoint in this profile Degraded after the next failed health check. - :paramtype tolerated_number_of_failures: long + :paramtype tolerated_number_of_failures: int :keyword custom_headers: List of custom headers. :paramtype custom_headers: list[~azure.mgmt.trafficmanager.models.MonitorConfigCustomHeadersItem] @@ -677,7 +661,7 @@ def __init__( :paramtype expected_status_code_ranges: list[~azure.mgmt.trafficmanager.models.MonitorConfigExpectedStatusCodeRangesItem] """ - super(MonitorConfig, self).__init__(**kwargs) + super().__init__(**kwargs) self.profile_monitor_status = profile_monitor_status self.protocol = protocol self.port = port @@ -689,7 +673,7 @@ def __init__( self.expected_status_code_ranges = expected_status_code_ranges -class MonitorConfigCustomHeadersItem(msrest.serialization.Model): +class MonitorConfigCustomHeadersItem(_serialization.Model): """Custom header name and value. :ivar name: Header name. @@ -699,29 +683,23 @@ class MonitorConfigCustomHeadersItem(msrest.serialization.Model): """ _attribute_map = { - 'name': {'key': 'name', 'type': 'str'}, - 'value': {'key': 'value', 'type': 'str'}, + "name": {"key": "name", "type": "str"}, + "value": {"key": "value", "type": "str"}, } - def __init__( - self, - *, - name: Optional[str] = None, - value: Optional[str] = None, - **kwargs - ): + def __init__(self, *, name: Optional[str] = None, value: Optional[str] = None, **kwargs): """ :keyword name: Header name. :paramtype name: str :keyword value: Header value. :paramtype value: str """ - super(MonitorConfigCustomHeadersItem, self).__init__(**kwargs) + super().__init__(**kwargs) self.name = name self.value = value -class MonitorConfigExpectedStatusCodeRangesItem(msrest.serialization.Model): +class MonitorConfigExpectedStatusCodeRangesItem(_serialization.Model): """Min and max value of a status code range. :ivar min: Min status code. @@ -731,15 +709,15 @@ class MonitorConfigExpectedStatusCodeRangesItem(msrest.serialization.Model): """ _attribute_map = { - 'min': {'key': 'min', 'type': 'int'}, - 'max': {'key': 'max', 'type': 'int'}, + "min": {"key": "min", "type": "int"}, + "max": {"key": "max", "type": "int"}, } def __init__( self, *, - min: Optional[int] = None, - max: Optional[int] = None, + min: Optional[int] = None, # pylint: disable=redefined-builtin + max: Optional[int] = None, # pylint: disable=redefined-builtin **kwargs ): """ @@ -748,7 +726,7 @@ def __init__( :keyword max: Max status code. :paramtype max: int """ - super(MonitorConfigExpectedStatusCodeRangesItem, self).__init__(**kwargs) + super().__init__(**kwargs) self.min = min self.max = max @@ -763,24 +741,24 @@ class TrackedResource(Resource): :vartype name: str :ivar type: The type of the resource. Ex- Microsoft.Network/trafficManagerProfiles. :vartype type: str - :ivar tags: A set of tags. Resource tags. + :ivar tags: Resource tags. :vartype tags: dict[str, str] :ivar location: The Azure Region where the resource lives. :vartype location: str """ _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, *, - id: Optional[str] = None, + id: Optional[str] = None, # pylint: disable=redefined-builtin name: Optional[str] = None, type: Optional[str] = None, tags: Optional[Dict[str, str]] = None, @@ -795,17 +773,17 @@ def __init__( :paramtype name: str :keyword type: The type of the resource. Ex- Microsoft.Network/trafficManagerProfiles. :paramtype type: str - :keyword tags: A set of tags. Resource tags. + :keyword tags: Resource tags. :paramtype tags: dict[str, str] :keyword location: The Azure Region where the resource lives. :paramtype location: str """ - super(TrackedResource, self).__init__(id=id, name=name, type=type, **kwargs) + super().__init__(id=id, name=name, type=type, **kwargs) self.tags = tags self.location = location -class Profile(TrackedResource): +class Profile(TrackedResource): # pylint: disable=too-many-instance-attributes """Class representing a Traffic Manager profile. :ivar id: Fully qualified resource Id for the resource. Ex - @@ -815,16 +793,15 @@ class Profile(TrackedResource): :vartype name: str :ivar type: The type of the resource. Ex- Microsoft.Network/trafficManagerProfiles. :vartype type: str - :ivar tags: A set of tags. Resource tags. + :ivar tags: Resource tags. :vartype tags: dict[str, str] :ivar location: The Azure Region where the resource lives. :vartype location: str - :ivar profile_status: The status of the Traffic Manager profile. Possible values include: - "Enabled", "Disabled". + :ivar profile_status: The status of the Traffic Manager profile. Known values are: "Enabled" + and "Disabled". :vartype profile_status: str or ~azure.mgmt.trafficmanager.models.ProfileStatus - :ivar traffic_routing_method: The traffic routing method of the Traffic Manager profile. - Possible values include: "Performance", "Priority", "Weighted", "Geographic", "MultiValue", - "Subnet". + :ivar traffic_routing_method: The traffic routing method of the Traffic Manager profile. Known + values are: "Performance", "Priority", "Weighted", "Geographic", "MultiValue", and "Subnet". :vartype traffic_routing_method: str or ~azure.mgmt.trafficmanager.models.TrafficRoutingMethod :ivar dns_config: The DNS settings of the Traffic Manager profile. :vartype dns_config: ~azure.mgmt.trafficmanager.models.DnsConfig @@ -834,48 +811,47 @@ class Profile(TrackedResource): :vartype endpoints: list[~azure.mgmt.trafficmanager.models.Endpoint] :ivar traffic_view_enrollment_status: Indicates whether Traffic View is 'Enabled' or 'Disabled' for the Traffic Manager profile. Null, indicates 'Disabled'. Enabling this feature will - increase the cost of the Traffic Manage profile. Possible values include: "Enabled", - "Disabled". + increase the cost of the Traffic Manage profile. Known values are: "Enabled" and "Disabled". :vartype traffic_view_enrollment_status: str or ~azure.mgmt.trafficmanager.models.TrafficViewEnrollmentStatus :ivar allowed_endpoint_record_types: The list of allowed endpoint record types. :vartype allowed_endpoint_record_types: list[str or ~azure.mgmt.trafficmanager.models.AllowedEndpointRecordType] :ivar max_return: Maximum number of endpoints to be returned for MultiValue routing type. - :vartype max_return: long + :vartype max_return: int """ _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'}, - 'profile_status': {'key': 'properties.profileStatus', 'type': 'str'}, - 'traffic_routing_method': {'key': 'properties.trafficRoutingMethod', 'type': 'str'}, - 'dns_config': {'key': 'properties.dnsConfig', 'type': 'DnsConfig'}, - 'monitor_config': {'key': 'properties.monitorConfig', 'type': 'MonitorConfig'}, - 'endpoints': {'key': 'properties.endpoints', 'type': '[Endpoint]'}, - 'traffic_view_enrollment_status': {'key': 'properties.trafficViewEnrollmentStatus', 'type': 'str'}, - 'allowed_endpoint_record_types': {'key': 'properties.allowedEndpointRecordTypes', 'type': '[str]'}, - 'max_return': {'key': 'properties.maxReturn', 'type': 'long'}, + "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"}, + "profile_status": {"key": "properties.profileStatus", "type": "str"}, + "traffic_routing_method": {"key": "properties.trafficRoutingMethod", "type": "str"}, + "dns_config": {"key": "properties.dnsConfig", "type": "DnsConfig"}, + "monitor_config": {"key": "properties.monitorConfig", "type": "MonitorConfig"}, + "endpoints": {"key": "properties.endpoints", "type": "[Endpoint]"}, + "traffic_view_enrollment_status": {"key": "properties.trafficViewEnrollmentStatus", "type": "str"}, + "allowed_endpoint_record_types": {"key": "properties.allowedEndpointRecordTypes", "type": "[str]"}, + "max_return": {"key": "properties.maxReturn", "type": "int"}, } def __init__( self, *, - id: Optional[str] = None, + id: Optional[str] = None, # pylint: disable=redefined-builtin name: Optional[str] = None, type: Optional[str] = None, tags: Optional[Dict[str, str]] = None, location: Optional[str] = None, - profile_status: Optional[Union[str, "ProfileStatus"]] = None, - traffic_routing_method: Optional[Union[str, "TrafficRoutingMethod"]] = None, - dns_config: Optional["DnsConfig"] = None, - monitor_config: Optional["MonitorConfig"] = None, - endpoints: Optional[List["Endpoint"]] = None, - traffic_view_enrollment_status: Optional[Union[str, "TrafficViewEnrollmentStatus"]] = None, - allowed_endpoint_record_types: Optional[List[Union[str, "AllowedEndpointRecordType"]]] = None, + profile_status: Optional[Union[str, "_models.ProfileStatus"]] = None, + traffic_routing_method: Optional[Union[str, "_models.TrafficRoutingMethod"]] = None, + dns_config: Optional["_models.DnsConfig"] = None, + monitor_config: Optional["_models.MonitorConfig"] = None, + endpoints: Optional[List["_models.Endpoint"]] = None, + traffic_view_enrollment_status: Optional[Union[str, "_models.TrafficViewEnrollmentStatus"]] = None, + allowed_endpoint_record_types: Optional[List[Union[str, "_models.AllowedEndpointRecordType"]]] = None, max_return: Optional[int] = None, **kwargs ): @@ -887,15 +863,15 @@ def __init__( :paramtype name: str :keyword type: The type of the resource. Ex- Microsoft.Network/trafficManagerProfiles. :paramtype type: str - :keyword tags: A set of tags. Resource tags. + :keyword tags: Resource tags. :paramtype tags: dict[str, str] :keyword location: The Azure Region where the resource lives. :paramtype location: str - :keyword profile_status: The status of the Traffic Manager profile. Possible values include: - "Enabled", "Disabled". + :keyword profile_status: The status of the Traffic Manager profile. Known values are: "Enabled" + and "Disabled". :paramtype profile_status: str or ~azure.mgmt.trafficmanager.models.ProfileStatus :keyword traffic_routing_method: The traffic routing method of the Traffic Manager profile. - Possible values include: "Performance", "Priority", "Weighted", "Geographic", "MultiValue", + Known values are: "Performance", "Priority", "Weighted", "Geographic", "MultiValue", and "Subnet". :paramtype traffic_routing_method: str or ~azure.mgmt.trafficmanager.models.TrafficRoutingMethod @@ -907,7 +883,7 @@ def __init__( :paramtype endpoints: list[~azure.mgmt.trafficmanager.models.Endpoint] :keyword traffic_view_enrollment_status: Indicates whether Traffic View is 'Enabled' or 'Disabled' for the Traffic Manager profile. Null, indicates 'Disabled'. Enabling this feature - will increase the cost of the Traffic Manage profile. Possible values include: "Enabled", + will increase the cost of the Traffic Manage profile. Known values are: "Enabled" and "Disabled". :paramtype traffic_view_enrollment_status: str or ~azure.mgmt.trafficmanager.models.TrafficViewEnrollmentStatus @@ -915,9 +891,9 @@ def __init__( :paramtype allowed_endpoint_record_types: list[str or ~azure.mgmt.trafficmanager.models.AllowedEndpointRecordType] :keyword max_return: Maximum number of endpoints to be returned for MultiValue routing type. - :paramtype max_return: long + :paramtype max_return: int """ - super(Profile, self).__init__(id=id, name=name, type=type, tags=tags, location=location, **kwargs) + super().__init__(id=id, name=name, type=type, tags=tags, location=location, **kwargs) self.profile_status = profile_status self.traffic_routing_method = traffic_routing_method self.dns_config = dns_config @@ -928,7 +904,7 @@ def __init__( self.max_return = max_return -class ProfileListResult(msrest.serialization.Model): +class ProfileListResult(_serialization.Model): """The list Traffic Manager profiles operation response. :ivar value: Gets the list of Traffic manager profiles. @@ -936,72 +912,60 @@ class ProfileListResult(msrest.serialization.Model): """ _attribute_map = { - 'value': {'key': 'value', 'type': '[Profile]'}, + "value": {"key": "value", "type": "[Profile]"}, } - def __init__( - self, - *, - value: Optional[List["Profile"]] = None, - **kwargs - ): + def __init__(self, *, value: Optional[List["_models.Profile"]] = None, **kwargs): """ :keyword value: Gets the list of Traffic manager profiles. :paramtype value: list[~azure.mgmt.trafficmanager.models.Profile] """ - super(ProfileListResult, self).__init__(**kwargs) + super().__init__(**kwargs) self.value = value -class QueryExperience(msrest.serialization.Model): +class QueryExperience(_serialization.Model): """Class representing a Traffic Manager HeatMap query experience properties. All required parameters must be populated in order to send to Azure. - :ivar endpoint_id: Required. The id of the endpoint from the 'endpoints' array which these - queries were routed to. + :ivar endpoint_id: The id of the endpoint from the 'endpoints' array which these queries were + routed to. Required. :vartype endpoint_id: int - :ivar query_count: Required. The number of queries originating from this location. + :ivar query_count: The number of queries originating from this location. Required. :vartype query_count: int :ivar latency: The latency experienced by queries originating from this location. :vartype latency: float """ _validation = { - 'endpoint_id': {'required': True}, - 'query_count': {'required': True}, + "endpoint_id": {"required": True}, + "query_count": {"required": True}, } _attribute_map = { - 'endpoint_id': {'key': 'endpointId', 'type': 'int'}, - 'query_count': {'key': 'queryCount', 'type': 'int'}, - 'latency': {'key': 'latency', 'type': 'float'}, + "endpoint_id": {"key": "endpointId", "type": "int"}, + "query_count": {"key": "queryCount", "type": "int"}, + "latency": {"key": "latency", "type": "float"}, } - def __init__( - self, - *, - endpoint_id: int, - query_count: int, - latency: Optional[float] = None, - **kwargs - ): + def __init__(self, *, endpoint_id: int, query_count: int, latency: Optional[float] = None, **kwargs): """ - :keyword endpoint_id: Required. The id of the endpoint from the 'endpoints' array which these - queries were routed to. + :keyword endpoint_id: The id of the endpoint from the 'endpoints' array which these queries + were routed to. Required. :paramtype endpoint_id: int - :keyword query_count: Required. The number of queries originating from this location. + :keyword query_count: The number of queries originating from this location. Required. :paramtype query_count: int :keyword latency: The latency experienced by queries originating from this location. :paramtype latency: float """ - super(QueryExperience, self).__init__(**kwargs) + super().__init__(**kwargs) self.endpoint_id = endpoint_id self.query_count = query_count self.latency = latency -class Region(msrest.serialization.Model): +class Region(_serialization.Model): """Class representing a region in the Geographic hierarchy used with the Geographic traffic routing method. :ivar code: The code of the region. @@ -1013,9 +977,9 @@ class Region(msrest.serialization.Model): """ _attribute_map = { - 'code': {'key': 'code', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'regions': {'key': 'regions', 'type': '[Region]'}, + "code": {"key": "code", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "regions": {"key": "regions", "type": "[Region]"}, } def __init__( @@ -1023,7 +987,7 @@ def __init__( *, code: Optional[str] = None, name: Optional[str] = None, - regions: Optional[List["Region"]] = None, + regions: Optional[List["_models.Region"]] = None, **kwargs ): """ @@ -1034,13 +998,13 @@ def __init__( :keyword regions: The list of Regions grouped under this Region in the Geographic Hierarchy. :paramtype regions: list[~azure.mgmt.trafficmanager.models.Region] """ - super(Region, self).__init__(**kwargs) + super().__init__(**kwargs) self.code = code self.name = name self.regions = regions -class TrafficFlow(msrest.serialization.Model): +class TrafficFlow(_serialization.Model): """Class representing a Traffic Manager HeatMap traffic flow properties. :ivar source_ip: The IP address that this query experience originated from. @@ -1054,10 +1018,10 @@ class TrafficFlow(msrest.serialization.Model): """ _attribute_map = { - 'source_ip': {'key': 'sourceIp', 'type': 'str'}, - 'latitude': {'key': 'latitude', 'type': 'float'}, - 'longitude': {'key': 'longitude', 'type': 'float'}, - 'query_experiences': {'key': 'queryExperiences', 'type': '[QueryExperience]'}, + "source_ip": {"key": "sourceIp", "type": "str"}, + "latitude": {"key": "latitude", "type": "float"}, + "longitude": {"key": "longitude", "type": "float"}, + "query_experiences": {"key": "queryExperiences", "type": "[QueryExperience]"}, } def __init__( @@ -1066,7 +1030,7 @@ def __init__( source_ip: Optional[str] = None, latitude: Optional[float] = None, longitude: Optional[float] = None, - query_experiences: Optional[List["QueryExperience"]] = None, + query_experiences: Optional[List["_models.QueryExperience"]] = None, **kwargs ): """ @@ -1079,7 +1043,7 @@ def __init__( :keyword query_experiences: The query experiences produced in this HeatMap calculation. :paramtype query_experiences: list[~azure.mgmt.trafficmanager.models.QueryExperience] """ - super(TrafficFlow, self).__init__(**kwargs) + super().__init__(**kwargs) self.source_ip = source_ip self.latitude = latitude self.longitude = longitude @@ -1102,19 +1066,19 @@ class TrafficManagerGeographicHierarchy(ProxyResource): """ _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'geographic_hierarchy': {'key': 'properties.geographicHierarchy', 'type': 'Region'}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "geographic_hierarchy": {"key": "properties.geographicHierarchy", "type": "Region"}, } def __init__( self, *, - id: Optional[str] = None, + id: Optional[str] = None, # pylint: disable=redefined-builtin name: Optional[str] = None, type: Optional[str] = None, - geographic_hierarchy: Optional["Region"] = None, + geographic_hierarchy: Optional["_models.Region"] = None, **kwargs ): """ @@ -1129,11 +1093,11 @@ def __init__( the hierarchy can be retrieved. :paramtype geographic_hierarchy: ~azure.mgmt.trafficmanager.models.Region """ - super(TrafficManagerGeographicHierarchy, self).__init__(id=id, name=name, type=type, **kwargs) + super().__init__(id=id, name=name, type=type, **kwargs) self.geographic_hierarchy = geographic_hierarchy -class TrafficManagerNameAvailability(msrest.serialization.Model): +class TrafficManagerNameAvailability(_serialization.Model): """Class representing a Traffic Manager Name Availability response. :ivar name: The relative name. @@ -1150,11 +1114,11 @@ class TrafficManagerNameAvailability(msrest.serialization.Model): """ _attribute_map = { - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'name_available': {'key': 'nameAvailable', 'type': 'bool'}, - 'reason': {'key': 'reason', 'type': 'str'}, - 'message': {'key': 'message', 'type': 'str'}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "name_available": {"key": "nameAvailable", "type": "bool"}, + "reason": {"key": "reason", "type": "str"}, + "message": {"key": "message", "type": "str"}, } def __init__( @@ -1180,7 +1144,7 @@ def __init__( applicable. :paramtype message: str """ - super(TrafficManagerNameAvailability, self).__init__(**kwargs) + super().__init__(**kwargs) self.name = name self.type = type self.name_available = name_available @@ -1203,16 +1167,16 @@ class UserMetricsModel(ProxyResource): """ _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'key': {'key': 'properties.key', 'type': 'str'}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "key": {"key": "properties.key", "type": "str"}, } def __init__( self, *, - id: Optional[str] = None, + id: Optional[str] = None, # pylint: disable=redefined-builtin name: Optional[str] = None, type: Optional[str] = None, key: Optional[str] = None, @@ -1229,5 +1193,5 @@ def __init__( :keyword key: The key returned by the User Metrics operation. :paramtype key: str """ - super(UserMetricsModel, self).__init__(id=id, name=name, type=type, **kwargs) + super().__init__(id=id, name=name, type=type, **kwargs) self.key = key diff --git a/sdk/trafficmanager/azure-mgmt-trafficmanager/azure/mgmt/trafficmanager/models/_patch.py b/sdk/trafficmanager/azure-mgmt-trafficmanager/azure/mgmt/trafficmanager/models/_patch.py new file mode 100644 index 000000000000..f7dd32510333 --- /dev/null +++ b/sdk/trafficmanager/azure-mgmt-trafficmanager/azure/mgmt/trafficmanager/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/trafficmanager/azure-mgmt-trafficmanager/azure/mgmt/trafficmanager/models/_traffic_manager_management_client_enums.py b/sdk/trafficmanager/azure-mgmt-trafficmanager/azure/mgmt/trafficmanager/models/_traffic_manager_management_client_enums.py index fc36d75babe2..8cba84e01237 100644 --- a/sdk/trafficmanager/azure-mgmt-trafficmanager/azure/mgmt/trafficmanager/models/_traffic_manager_management_client_enums.py +++ b/sdk/trafficmanager/azure-mgmt-trafficmanager/azure/mgmt/trafficmanager/models/_traffic_manager_management_client_enums.py @@ -7,23 +7,30 @@ # -------------------------------------------------------------------------- from enum import Enum -from six import with_metaclass from azure.core import CaseInsensitiveEnumMeta -class AllowedEndpointRecordType(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): - """The allowed type DNS record types for this profile. - """ +class AllowedEndpointRecordType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The allowed type DNS record types for this profile.""" DOMAIN_NAME = "DomainName" I_PV4_ADDRESS = "IPv4Address" I_PV6_ADDRESS = "IPv6Address" ANY = "Any" -class EndpointMonitorStatus(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): - """The monitoring status of the endpoint. + +class AlwaysServe(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """If Always Serve is enabled, probing for endpoint health will be disabled and endpoints will be + included in the traffic routing method. """ + ENABLED = "Enabled" + DISABLED = "Disabled" + + +class EndpointMonitorStatus(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The monitoring status of the endpoint.""" + CHECKING_ENDPOINT = "CheckingEndpoint" ONLINE = "Online" DEGRADED = "Degraded" @@ -31,7 +38,8 @@ class EndpointMonitorStatus(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): INACTIVE = "Inactive" STOPPED = "Stopped" -class EndpointStatus(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): + +class EndpointStatus(str, Enum, metaclass=CaseInsensitiveEnumMeta): """The status of the endpoint. If the endpoint is Enabled, it is probed for endpoint health and is included in the traffic routing method. """ @@ -39,23 +47,25 @@ class EndpointStatus(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): ENABLED = "Enabled" DISABLED = "Disabled" -class EndpointType(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): + +class EndpointType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """EndpointType.""" AZURE_ENDPOINTS = "AzureEndpoints" EXTERNAL_ENDPOINTS = "ExternalEndpoints" NESTED_ENDPOINTS = "NestedEndpoints" -class MonitorProtocol(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): - """The protocol (HTTP, HTTPS or TCP) used to probe for endpoint health. - """ + +class MonitorProtocol(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The protocol (HTTP, HTTPS or TCP) used to probe for endpoint health.""" HTTP = "HTTP" HTTPS = "HTTPS" TCP = "TCP" -class ProfileMonitorStatus(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): - """The profile-level monitoring status of the Traffic Manager profile. - """ + +class ProfileMonitorStatus(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The profile-level monitoring status of the Traffic Manager profile.""" CHECKING_ENDPOINTS = "CheckingEndpoints" ONLINE = "Online" @@ -63,16 +73,16 @@ class ProfileMonitorStatus(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): DISABLED = "Disabled" INACTIVE = "Inactive" -class ProfileStatus(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): - """The status of the Traffic Manager profile. - """ + +class ProfileStatus(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The status of the Traffic Manager profile.""" ENABLED = "Enabled" DISABLED = "Disabled" -class TrafficRoutingMethod(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): - """The traffic routing method of the Traffic Manager profile. - """ + +class TrafficRoutingMethod(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The traffic routing method of the Traffic Manager profile.""" PERFORMANCE = "Performance" PRIORITY = "Priority" @@ -81,7 +91,8 @@ class TrafficRoutingMethod(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): MULTI_VALUE = "MultiValue" SUBNET = "Subnet" -class TrafficViewEnrollmentStatus(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): + +class TrafficViewEnrollmentStatus(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Indicates whether Traffic View is 'Enabled' or 'Disabled' for the Traffic Manager profile. Null, indicates 'Disabled'. Enabling this feature will increase the cost of the Traffic Manage profile. diff --git a/sdk/trafficmanager/azure-mgmt-trafficmanager/azure/mgmt/trafficmanager/operations/__init__.py b/sdk/trafficmanager/azure-mgmt-trafficmanager/azure/mgmt/trafficmanager/operations/__init__.py index adda3e0be5d0..d48dcfb68274 100644 --- a/sdk/trafficmanager/azure-mgmt-trafficmanager/azure/mgmt/trafficmanager/operations/__init__.py +++ b/sdk/trafficmanager/azure-mgmt-trafficmanager/azure/mgmt/trafficmanager/operations/__init__.py @@ -12,10 +12,16 @@ from ._heat_map_operations import HeatMapOperations from ._traffic_manager_user_metrics_keys_operations import TrafficManagerUserMetricsKeysOperations +from ._patch import __all__ as _patch_all +from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import +from ._patch import patch_sdk as _patch_sdk + __all__ = [ - 'EndpointsOperations', - 'ProfilesOperations', - 'GeographicHierarchiesOperations', - 'HeatMapOperations', - 'TrafficManagerUserMetricsKeysOperations', + "EndpointsOperations", + "ProfilesOperations", + "GeographicHierarchiesOperations", + "HeatMapOperations", + "TrafficManagerUserMetricsKeysOperations", ] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/sdk/trafficmanager/azure-mgmt-trafficmanager/azure/mgmt/trafficmanager/operations/_endpoints_operations.py b/sdk/trafficmanager/azure-mgmt-trafficmanager/azure/mgmt/trafficmanager/operations/_endpoints_operations.py index 8e726f2f39dc..e0168f0e3d46 100644 --- a/sdk/trafficmanager/azure-mgmt-trafficmanager/azure/mgmt/trafficmanager/operations/_endpoints_operations.py +++ b/sdk/trafficmanager/azure-mgmt-trafficmanager/azure/mgmt/trafficmanager/operations/_endpoints_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,259 +6,361 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -import functools -from typing import Any, Callable, Dict, Generic, Optional, TypeVar, Union -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 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 msrest import Serializer from .. import models as _models +from .._serialization import Serializer from .._vendor import _convert_request, _format_url_section -T = TypeVar('T') -JSONType = Any + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False + def build_update_request( resource_group_name: str, profile_name: str, - endpoint_type: Union[str, "_models.EndpointType"], + endpoint_type: Union[str, _models.EndpointType], endpoint_name: str, subscription_id: str, - *, - json: JSONType = None, - content: Any = None, **kwargs: Any ) -> HttpRequest: - content_type = kwargs.pop('content_type', None) # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", "2022-04-01-preview") + ) # type: Literal["2022-04-01-preview"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") - api_version = "2018-08-01" - accept = "application/json" # Construct URL - url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/trafficmanagerprofiles/{profileName}/{endpointType}/{endpointName}') + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/trafficmanagerprofiles/{profileName}/{endpointType}/{endpointName}", + ) # pylint: disable=line-too-long path_format_arguments = { - "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str'), - "profileName": _SERIALIZER.url("profile_name", profile_name, 'str'), - "endpointType": _SERIALIZER.url("endpoint_type", endpoint_type, 'str'), - "endpointName": _SERIALIZER.url("endpoint_name", endpoint_name, 'str'), - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "profileName": _SERIALIZER.url("profile_name", profile_name, "str"), + "endpointType": _SERIALIZER.url("endpoint_type", endpoint_type, "str"), + "endpointName": _SERIALIZER.url("endpoint_name", endpoint_name, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - url = _format_url_section(url, **path_format_arguments) + _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] if content_type is not None: - header_parameters['Content-Type'] = _SERIALIZER.header("content_type", content_type, 'str') - header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest( - method="PATCH", - url=url, - params=query_parameters, - headers=header_parameters, - json=json, - content=content, - **kwargs - ) + return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs) def build_get_request( resource_group_name: str, profile_name: str, - endpoint_type: Union[str, "_models.EndpointType"], + endpoint_type: Union[str, _models.EndpointType], endpoint_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: - api_version = "2018-08-01" - accept = "application/json" + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", "2022-04-01-preview") + ) # type: Literal["2022-04-01-preview"] + accept = _headers.pop("Accept", "application/json") + # Construct URL - url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/trafficmanagerprofiles/{profileName}/{endpointType}/{endpointName}') + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/trafficmanagerprofiles/{profileName}/{endpointType}/{endpointName}", + ) # pylint: disable=line-too-long path_format_arguments = { - "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str'), - "profileName": _SERIALIZER.url("profile_name", profile_name, 'str'), - "endpointType": _SERIALIZER.url("endpoint_type", endpoint_type, 'str'), - "endpointName": _SERIALIZER.url("endpoint_name", endpoint_name, 'str'), - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "profileName": _SERIALIZER.url("profile_name", profile_name, "str"), + "endpointType": _SERIALIZER.url("endpoint_type", endpoint_type, "str"), + "endpointName": _SERIALIZER.url("endpoint_name", endpoint_name, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - url = _format_url_section(url, **path_format_arguments) + _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] - header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest( - method="GET", - url=url, - params=query_parameters, - headers=header_parameters, - **kwargs - ) + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_create_or_update_request( resource_group_name: str, profile_name: str, - endpoint_type: Union[str, "_models.EndpointType"], + endpoint_type: Union[str, _models.EndpointType], endpoint_name: str, subscription_id: str, - *, - json: JSONType = None, - content: Any = None, **kwargs: Any ) -> HttpRequest: - content_type = kwargs.pop('content_type', None) # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", "2022-04-01-preview") + ) # type: Literal["2022-04-01-preview"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") - api_version = "2018-08-01" - accept = "application/json" # Construct URL - url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/trafficmanagerprofiles/{profileName}/{endpointType}/{endpointName}') + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/trafficmanagerprofiles/{profileName}/{endpointType}/{endpointName}", + ) # pylint: disable=line-too-long path_format_arguments = { - "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str'), - "profileName": _SERIALIZER.url("profile_name", profile_name, 'str'), - "endpointType": _SERIALIZER.url("endpoint_type", endpoint_type, 'str'), - "endpointName": _SERIALIZER.url("endpoint_name", endpoint_name, 'str'), - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "profileName": _SERIALIZER.url("profile_name", profile_name, "str"), + "endpointType": _SERIALIZER.url("endpoint_type", endpoint_type, "str"), + "endpointName": _SERIALIZER.url("endpoint_name", endpoint_name, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - url = _format_url_section(url, **path_format_arguments) + _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] if content_type is not None: - header_parameters['Content-Type'] = _SERIALIZER.header("content_type", content_type, 'str') - header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest( - method="PUT", - url=url, - params=query_parameters, - headers=header_parameters, - json=json, - content=content, - **kwargs - ) + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) def build_delete_request( resource_group_name: str, profile_name: str, - endpoint_type: Union[str, "_models.EndpointType"], + endpoint_type: Union[str, _models.EndpointType], endpoint_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: - api_version = "2018-08-01" - accept = "application/json" + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", "2022-04-01-preview") + ) # type: Literal["2022-04-01-preview"] + accept = _headers.pop("Accept", "application/json") + # Construct URL - url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/trafficmanagerprofiles/{profileName}/{endpointType}/{endpointName}') + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/trafficmanagerprofiles/{profileName}/{endpointType}/{endpointName}", + ) # pylint: disable=line-too-long path_format_arguments = { - "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str'), - "profileName": _SERIALIZER.url("profile_name", profile_name, 'str'), - "endpointType": _SERIALIZER.url("endpoint_type", endpoint_type, 'str'), - "endpointName": _SERIALIZER.url("endpoint_name", endpoint_name, 'str'), - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "profileName": _SERIALIZER.url("profile_name", profile_name, "str"), + "endpointType": _SERIALIZER.url("endpoint_type", endpoint_type, "str"), + "endpointName": _SERIALIZER.url("endpoint_name", endpoint_name, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - url = _format_url_section(url, **path_format_arguments) + _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] - header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') - - return HttpRequest( - method="DELETE", - url=url, - params=query_parameters, - headers=header_parameters, - **kwargs - ) - -class EndpointsOperations(object): - """EndpointsOperations operations. - - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. - - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.trafficmanager.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +class EndpointsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.trafficmanager.TrafficManagerManagementClient`'s + :attr:`endpoints` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer): - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - @distributed_trace + @overload def update( self, resource_group_name: str, profile_name: str, - endpoint_type: Union[str, "_models.EndpointType"], + endpoint_type: Union[str, _models.EndpointType], endpoint_name: str, - parameters: "_models.Endpoint", + parameters: _models.Endpoint, + *, + content_type: str = "application/json", **kwargs: Any - ) -> "_models.Endpoint": + ) -> _models.Endpoint: """Update a Traffic Manager endpoint. - :param resource_group_name: The name of the resource group containing the Traffic Manager - endpoint to be updated. + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param profile_name: The name of the Traffic Manager profile. + :param profile_name: The name of the Traffic Manager profile. Required. :type profile_name: str - :param endpoint_type: The type of the Traffic Manager endpoint to be updated. + :param endpoint_type: The type of the Traffic Manager endpoint to be updated. Known values are: + "AzureEndpoints", "ExternalEndpoints", and "NestedEndpoints". Required. :type endpoint_type: str or ~azure.mgmt.trafficmanager.models.EndpointType - :param endpoint_name: The name of the Traffic Manager endpoint to be updated. + :param endpoint_name: The name of the Traffic Manager endpoint to be updated. Required. :type endpoint_name: str :param parameters: The Traffic Manager endpoint parameters supplied to the Update operation. + Required. :type parameters: ~azure.mgmt.trafficmanager.models.Endpoint + :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: Endpoint or the result of cls(response) + :rtype: ~azure.mgmt.trafficmanager.models.Endpoint + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def update( + self, + resource_group_name: str, + profile_name: str, + endpoint_type: Union[str, _models.EndpointType], + endpoint_name: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Endpoint: + """Update a Traffic Manager endpoint. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param profile_name: The name of the Traffic Manager profile. Required. + :type profile_name: str + :param endpoint_type: The type of the Traffic Manager endpoint to be updated. Known values are: + "AzureEndpoints", "ExternalEndpoints", and "NestedEndpoints". Required. + :type endpoint_type: str or ~azure.mgmt.trafficmanager.models.EndpointType + :param endpoint_name: The name of the Traffic Manager endpoint to be updated. Required. + :type endpoint_name: str + :param parameters: The Traffic Manager endpoint parameters supplied to the Update operation. + Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: Endpoint or the result of cls(response) + :rtype: ~azure.mgmt.trafficmanager.models.Endpoint + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def update( + self, + resource_group_name: str, + profile_name: str, + endpoint_type: Union[str, _models.EndpointType], + endpoint_name: str, + parameters: Union[_models.Endpoint, IO], + **kwargs: Any + ) -> _models.Endpoint: + """Update a Traffic Manager endpoint. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param profile_name: The name of the Traffic Manager profile. Required. + :type profile_name: str + :param endpoint_type: The type of the Traffic Manager endpoint to be updated. Known values are: + "AzureEndpoints", "ExternalEndpoints", and "NestedEndpoints". Required. + :type endpoint_type: str or ~azure.mgmt.trafficmanager.models.EndpointType + :param endpoint_name: The name of the Traffic Manager endpoint to be updated. Required. + :type endpoint_name: str + :param parameters: The Traffic Manager endpoint parameters supplied to the Update operation. Is + either a model type or a IO type. Required. + :type parameters: ~azure.mgmt.trafficmanager.models.Endpoint 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: Endpoint, or the result of cls(response) + :return: Endpoint or the result of cls(response) :rtype: ~azure.mgmt.trafficmanager.models.Endpoint - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Endpoint"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - _json = self._serialize.body(parameters, 'Endpoint') + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-04-01-preview"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.Endpoint] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "Endpoint") request = build_update_request( resource_group_name=resource_group_name, @@ -265,128 +368,243 @@ def update( endpoint_type=endpoint_type, endpoint_name=endpoint_name, subscription_id=self._config.subscription_id, + api_version=api_version, content_type=content_type, json=_json, - template_url=self.update.metadata['url'], + content=_content, + template_url=self.update.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('Endpoint', pipeline_response) + deserialized = self._deserialize("Endpoint", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/trafficmanagerprofiles/{profileName}/{endpointType}/{endpointName}'} # type: ignore - + update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/trafficmanagerprofiles/{profileName}/{endpointType}/{endpointName}"} # type: ignore @distributed_trace def get( self, resource_group_name: str, profile_name: str, - endpoint_type: Union[str, "_models.EndpointType"], + endpoint_type: Union[str, _models.EndpointType], endpoint_name: str, **kwargs: Any - ) -> "_models.Endpoint": + ) -> _models.Endpoint: """Gets a Traffic Manager endpoint. - :param resource_group_name: The name of the resource group containing the Traffic Manager - endpoint. + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param profile_name: The name of the Traffic Manager profile. + :param profile_name: The name of the Traffic Manager profile. Required. :type profile_name: str - :param endpoint_type: The type of the Traffic Manager endpoint. + :param endpoint_type: The type of the Traffic Manager endpoint. Known values are: + "AzureEndpoints", "ExternalEndpoints", and "NestedEndpoints". Required. :type endpoint_type: str or ~azure.mgmt.trafficmanager.models.EndpointType - :param endpoint_name: The name of the Traffic Manager endpoint. + :param endpoint_name: The name of the Traffic Manager endpoint. Required. :type endpoint_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: Endpoint, or the result of cls(response) + :return: Endpoint or the result of cls(response) :rtype: ~azure.mgmt.trafficmanager.models.Endpoint - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Endpoint"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-04-01-preview"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.Endpoint] - request = build_get_request( resource_group_name=resource_group_name, profile_name=profile_name, endpoint_type=endpoint_type, endpoint_name=endpoint_name, subscription_id=self._config.subscription_id, - template_url=self.get.metadata['url'], + 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) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - 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('Endpoint', pipeline_response) + deserialized = self._deserialize("Endpoint", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/trafficmanagerprofiles/{profileName}/{endpointType}/{endpointName}'} # type: ignore + get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/trafficmanagerprofiles/{profileName}/{endpointType}/{endpointName}"} # type: ignore + + @overload + def create_or_update( + self, + resource_group_name: str, + profile_name: str, + endpoint_type: Union[str, _models.EndpointType], + endpoint_name: str, + parameters: _models.Endpoint, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Endpoint: + """Create or update a Traffic Manager endpoint. + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param profile_name: The name of the Traffic Manager profile. Required. + :type profile_name: str + :param endpoint_type: The type of the Traffic Manager endpoint to be created or updated. Known + values are: "AzureEndpoints", "ExternalEndpoints", and "NestedEndpoints". Required. + :type endpoint_type: str or ~azure.mgmt.trafficmanager.models.EndpointType + :param endpoint_name: The name of the Traffic Manager endpoint to be created or updated. + Required. + :type endpoint_name: str + :param parameters: The Traffic Manager endpoint parameters supplied to the CreateOrUpdate + operation. Required. + :type parameters: ~azure.mgmt.trafficmanager.models.Endpoint + :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: Endpoint or the result of cls(response) + :rtype: ~azure.mgmt.trafficmanager.models.Endpoint + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_or_update( + self, + resource_group_name: str, + profile_name: str, + endpoint_type: Union[str, _models.EndpointType], + endpoint_name: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Endpoint: + """Create or update a Traffic Manager endpoint. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param profile_name: The name of the Traffic Manager profile. Required. + :type profile_name: str + :param endpoint_type: The type of the Traffic Manager endpoint to be created or updated. Known + values are: "AzureEndpoints", "ExternalEndpoints", and "NestedEndpoints". Required. + :type endpoint_type: str or ~azure.mgmt.trafficmanager.models.EndpointType + :param endpoint_name: The name of the Traffic Manager endpoint to be created or updated. + Required. + :type endpoint_name: str + :param parameters: The Traffic Manager endpoint parameters supplied to the CreateOrUpdate + operation. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: Endpoint or the result of cls(response) + :rtype: ~azure.mgmt.trafficmanager.models.Endpoint + :raises ~azure.core.exceptions.HttpResponseError: + """ @distributed_trace def create_or_update( self, resource_group_name: str, profile_name: str, - endpoint_type: Union[str, "_models.EndpointType"], + endpoint_type: Union[str, _models.EndpointType], endpoint_name: str, - parameters: "_models.Endpoint", + parameters: Union[_models.Endpoint, IO], **kwargs: Any - ) -> "_models.Endpoint": + ) -> _models.Endpoint: """Create or update a Traffic Manager endpoint. - :param resource_group_name: The name of the resource group containing the Traffic Manager - endpoint to be created or updated. + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param profile_name: The name of the Traffic Manager profile. + :param profile_name: The name of the Traffic Manager profile. Required. :type profile_name: str - :param endpoint_type: The type of the Traffic Manager endpoint to be created or updated. + :param endpoint_type: The type of the Traffic Manager endpoint to be created or updated. Known + values are: "AzureEndpoints", "ExternalEndpoints", and "NestedEndpoints". Required. :type endpoint_type: str or ~azure.mgmt.trafficmanager.models.EndpointType :param endpoint_name: The name of the Traffic Manager endpoint to be created or updated. + Required. :type endpoint_name: str :param parameters: The Traffic Manager endpoint parameters supplied to the CreateOrUpdate - operation. - :type parameters: ~azure.mgmt.trafficmanager.models.Endpoint + operation. Is either a model type or a IO type. Required. + :type parameters: ~azure.mgmt.trafficmanager.models.Endpoint 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: Endpoint, or the result of cls(response) + :return: Endpoint or the result of cls(response) :rtype: ~azure.mgmt.trafficmanager.models.Endpoint - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Endpoint"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - _json = self._serialize.body(parameters, 'Endpoint') + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-04-01-preview"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.Endpoint] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "Endpoint") request = build_create_or_update_request( resource_group_name=resource_group_name, @@ -394,14 +612,21 @@ def create_or_update( endpoint_type=endpoint_type, endpoint_name=endpoint_name, subscription_id=self._config.subscription_id, + api_version=api_version, content_type=content_type, json=_json, - template_url=self.create_or_update.metadata['url'], + 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) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 201]: @@ -409,63 +634,78 @@ def create_or_update( raise HttpResponseError(response=response, error_format=ARMErrorFormat) if response.status_code == 200: - deserialized = self._deserialize('Endpoint', pipeline_response) + deserialized = self._deserialize("Endpoint", pipeline_response) if response.status_code == 201: - deserialized = self._deserialize('Endpoint', pipeline_response) + deserialized = self._deserialize("Endpoint", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/trafficmanagerprofiles/{profileName}/{endpointType}/{endpointName}'} # type: ignore - + create_or_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/trafficmanagerprofiles/{profileName}/{endpointType}/{endpointName}"} # type: ignore @distributed_trace def delete( self, resource_group_name: str, profile_name: str, - endpoint_type: Union[str, "_models.EndpointType"], + endpoint_type: Union[str, _models.EndpointType], endpoint_name: str, **kwargs: Any - ) -> Optional["_models.DeleteOperationResult"]: + ) -> Optional[_models.DeleteOperationResult]: """Deletes a Traffic Manager endpoint. - :param resource_group_name: The name of the resource group containing the Traffic Manager - endpoint to be deleted. + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param profile_name: The name of the Traffic Manager profile. + :param profile_name: The name of the Traffic Manager profile. Required. :type profile_name: str - :param endpoint_type: The type of the Traffic Manager endpoint to be deleted. + :param endpoint_type: The type of the Traffic Manager endpoint to be deleted. Known values are: + "AzureEndpoints", "ExternalEndpoints", and "NestedEndpoints". Required. :type endpoint_type: str or ~azure.mgmt.trafficmanager.models.EndpointType - :param endpoint_name: The name of the Traffic Manager endpoint to be deleted. + :param endpoint_name: The name of the Traffic Manager endpoint to be deleted. Required. :type endpoint_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: DeleteOperationResult, or the result of cls(response) + :return: DeleteOperationResult or None or the result of cls(response) :rtype: ~azure.mgmt.trafficmanager.models.DeleteOperationResult or None - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.DeleteOperationResult"]] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-04-01-preview"] + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.DeleteOperationResult]] - request = build_delete_request( resource_group_name=resource_group_name, profile_name=profile_name, endpoint_type=endpoint_type, endpoint_name=endpoint_name, subscription_id=self._config.subscription_id, - template_url=self.delete.metadata['url'], + 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) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 204]: @@ -474,12 +714,11 @@ def delete( deserialized = None if response.status_code == 200: - deserialized = self._deserialize('DeleteOperationResult', pipeline_response) + deserialized = self._deserialize("DeleteOperationResult", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/trafficmanagerprofiles/{profileName}/{endpointType}/{endpointName}'} # type: ignore - + delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/trafficmanagerprofiles/{profileName}/{endpointType}/{endpointName}"} # type: ignore diff --git a/sdk/trafficmanager/azure-mgmt-trafficmanager/azure/mgmt/trafficmanager/operations/_geographic_hierarchies_operations.py b/sdk/trafficmanager/azure-mgmt-trafficmanager/azure/mgmt/trafficmanager/operations/_geographic_hierarchies_operations.py index 67526c316c4c..39cffc8017d3 100644 --- a/sdk/trafficmanager/azure-mgmt-trafficmanager/azure/mgmt/trafficmanager/operations/_geographic_hierarchies_operations.py +++ b/sdk/trafficmanager/azure-mgmt-trafficmanager/azure/mgmt/trafficmanager/operations/_geographic_hierarchies_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,110 +6,128 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -import functools -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, Optional, TypeVar + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat -from msrest import Serializer from .. import models as _models +from .._serialization import Serializer from .._vendor import _convert_request -T = TypeVar('T') + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False -def build_get_default_request( - **kwargs: Any -) -> HttpRequest: - api_version = "2018-08-01" - accept = "application/json" + +def build_get_default_request(**kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", "2022-04-01-preview") + ) # type: Literal["2022-04-01-preview"] + accept = _headers.pop("Accept", "application/json") + # Construct URL - url = kwargs.pop("template_url", '/providers/Microsoft.Network/trafficManagerGeographicHierarchies/default') + _url = kwargs.pop("template_url", "/providers/Microsoft.Network/trafficManagerGeographicHierarchies/default") # Construct parameters - query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] - header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') - - return HttpRequest( - method="GET", - url=url, - params=query_parameters, - headers=header_parameters, - **kwargs - ) - -class GeographicHierarchiesOperations(object): - """GeographicHierarchiesOperations operations. - - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. - - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.trafficmanager.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class GeographicHierarchiesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.trafficmanager.TrafficManagerManagementClient`'s + :attr:`geographic_hierarchies` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer): - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace - def get_default( - self, - **kwargs: Any - ) -> "_models.TrafficManagerGeographicHierarchy": + def get_default(self, **kwargs: Any) -> _models.TrafficManagerGeographicHierarchy: """Gets the default Geographic Hierarchy used by the Geographic traffic routing method. :keyword callable cls: A custom type or function that will be passed the direct response - :return: TrafficManagerGeographicHierarchy, or the result of cls(response) + :return: TrafficManagerGeographicHierarchy or the result of cls(response) :rtype: ~azure.mgmt.trafficmanager.models.TrafficManagerGeographicHierarchy - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.TrafficManagerGeographicHierarchy"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-04-01-preview"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.TrafficManagerGeographicHierarchy] - request = build_get_default_request( - template_url=self.get_default.metadata['url'], + api_version=api_version, + template_url=self.get_default.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('TrafficManagerGeographicHierarchy', pipeline_response) + deserialized = self._deserialize("TrafficManagerGeographicHierarchy", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get_default.metadata = {'url': '/providers/Microsoft.Network/trafficManagerGeographicHierarchies/default'} # type: ignore - + get_default.metadata = {"url": "/providers/Microsoft.Network/trafficManagerGeographicHierarchies/default"} # type: ignore diff --git a/sdk/trafficmanager/azure-mgmt-trafficmanager/azure/mgmt/trafficmanager/operations/_heat_map_operations.py b/sdk/trafficmanager/azure-mgmt-trafficmanager/azure/mgmt/trafficmanager/operations/_heat_map_operations.py index 85da607d77b0..30d8fb0a53e2 100644 --- a/sdk/trafficmanager/azure-mgmt-trafficmanager/azure/mgmt/trafficmanager/operations/_heat_map_operations.py +++ b/sdk/trafficmanager/azure-mgmt-trafficmanager/azure/mgmt/trafficmanager/operations/_heat_map_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,90 +6,104 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -import functools -from typing import Any, Callable, Dict, Generic, List, Optional, TypeVar -import warnings - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +import sys +from typing import Any, Callable, Dict, List, Optional, TypeVar + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat -from msrest import Serializer from .. import models as _models +from .._serialization import Serializer from .._vendor import _convert_request, _format_url_section -T = TypeVar('T') + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False + def build_get_request( - subscription_id: str, resource_group_name: str, profile_name: str, + subscription_id: str, *, top_left: Optional[List[float]] = None, bot_right: Optional[List[float]] = None, **kwargs: Any ) -> HttpRequest: - heat_map_type = "default" - api_version = "2018-08-01" - accept = "application/json" + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + heat_map_type = kwargs.pop("heat_map_type", "default") # type: Literal["default"] + api_version = kwargs.pop( + "api_version", _params.pop("api-version", "2022-04-01-preview") + ) # type: Literal["2022-04-01-preview"] + accept = _headers.pop("Accept", "application/json") + # Construct URL - url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/trafficmanagerprofiles/{profileName}/heatMaps/{heatMapType}') + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/trafficmanagerprofiles/{profileName}/heatMaps/{heatMapType}", + ) # pylint: disable=line-too-long path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'), - "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str'), - "profileName": _SERIALIZER.url("profile_name", profile_name, 'str'), - "heatMapType": _SERIALIZER.url("heat_map_type", heat_map_type, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "profileName": _SERIALIZER.url("profile_name", profile_name, "str"), + "heatMapType": _SERIALIZER.url("heat_map_type", heat_map_type, "str"), } - url = _format_url_section(url, **path_format_arguments) + _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] if top_left is not None: - query_parameters['topLeft'] = _SERIALIZER.query("top_left", top_left, '[float]', div=',') + _params["topLeft"] = _SERIALIZER.query("top_left", top_left, "[float]", div=",") if bot_right is not None: - query_parameters['botRight'] = _SERIALIZER.query("bot_right", bot_right, '[float]', div=',') - query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["botRight"] = _SERIALIZER.query("bot_right", bot_right, "[float]", div=",") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] - header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') - - return HttpRequest( - method="GET", - url=url, - params=query_parameters, - headers=header_parameters, - **kwargs - ) - -class HeatMapOperations(object): - """HeatMapOperations operations. - - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. - - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.trafficmanager.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class HeatMapOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.trafficmanager.TrafficManagerManagementClient`'s + :attr:`heat_map` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer): - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace def get( @@ -98,55 +113,75 @@ def get( top_left: Optional[List[float]] = None, bot_right: Optional[List[float]] = None, **kwargs: Any - ) -> "_models.HeatMapModel": + ) -> _models.HeatMapModel: """Gets latest heatmap for Traffic Manager profile. - :param resource_group_name: The name of the resource group containing the Traffic Manager - endpoint. + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param profile_name: The name of the Traffic Manager profile. + :param profile_name: The name of the Traffic Manager profile. Required. :type profile_name: str :param top_left: The top left latitude,longitude pair of the rectangular viewport to query for. + Default value is None. :type top_left: list[float] :param bot_right: The bottom right latitude,longitude pair of the rectangular viewport to query - for. + for. Default value is None. :type bot_right: list[float] + :keyword heat_map_type: The type of HeatMap for the Traffic Manager profile. Default value is + "default". Note that overriding this default value may result in unsupported behavior. + :paramtype heat_map_type: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: HeatMapModel, or the result of cls(response) + :return: HeatMapModel or the result of cls(response) :rtype: ~azure.mgmt.trafficmanager.models.HeatMapModel - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.HeatMapModel"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + heat_map_type = kwargs.pop("heat_map_type", "default") # type: Literal["default"] + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-04-01-preview"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.HeatMapModel] - request = build_get_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, profile_name=profile_name, + subscription_id=self._config.subscription_id, top_left=top_left, bot_right=bot_right, - template_url=self.get.metadata['url'], + heat_map_type=heat_map_type, + 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) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - 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('HeatMapModel', pipeline_response) + deserialized = self._deserialize("HeatMapModel", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/trafficmanagerprofiles/{profileName}/heatMaps/{heatMapType}'} # type: ignore - + get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/trafficmanagerprofiles/{profileName}/heatMaps/{heatMapType}"} # type: ignore diff --git a/sdk/trafficmanager/azure-mgmt-trafficmanager/azure/mgmt/trafficmanager/operations/_patch.py b/sdk/trafficmanager/azure-mgmt-trafficmanager/azure/mgmt/trafficmanager/operations/_patch.py new file mode 100644 index 000000000000..f7dd32510333 --- /dev/null +++ b/sdk/trafficmanager/azure-mgmt-trafficmanager/azure/mgmt/trafficmanager/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/trafficmanager/azure-mgmt-trafficmanager/azure/mgmt/trafficmanager/operations/_profiles_operations.py b/sdk/trafficmanager/azure-mgmt-trafficmanager/azure/mgmt/trafficmanager/operations/_profiles_operations.py index fa3345f13872..ff798e8ac49f 100644 --- a/sdk/trafficmanager/azure-mgmt-trafficmanager/azure/mgmt/trafficmanager/operations/_profiles_operations.py +++ b/sdk/trafficmanager/azure-mgmt-trafficmanager/azure/mgmt/trafficmanager/operations/_profiles_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,398 +6,461 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -import functools -from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar, Union -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 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 msrest import Serializer from .. import models as _models +from .._serialization import Serializer from .._vendor import _convert_request, _format_url_section -T = TypeVar('T') -JSONType = Any + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False -def build_check_traffic_manager_relative_dns_name_availability_request( - *, - json: JSONType = None, - content: Any = None, - **kwargs: Any -) -> HttpRequest: - content_type = kwargs.pop('content_type', None) # type: Optional[str] - api_version = "2018-08-01" - accept = "application/json" +def build_check_traffic_manager_relative_dns_name_availability_request(**kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", "2022-04-01-preview") + ) # type: Literal["2022-04-01-preview"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") + # Construct URL - url = kwargs.pop("template_url", '/providers/Microsoft.Network/checkTrafficManagerNameAvailability') + _url = kwargs.pop("template_url", "/providers/Microsoft.Network/checkTrafficManagerNameAvailability") # Construct parameters - query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] if content_type is not None: - header_parameters['Content-Type'] = _SERIALIZER.header("content_type", content_type, 'str') - header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') - - return HttpRequest( - method="POST", - url=url, - params=query_parameters, - headers=header_parameters, - json=json, - content=content, - **kwargs - ) + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_by_resource_group_request(resource_group_name: str, subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", "2022-04-01-preview") + ) # type: Literal["2022-04-01-preview"] + accept = _headers.pop("Accept", "application/json") -def build_list_by_resource_group_request( - resource_group_name: str, - subscription_id: str, - **kwargs: Any -) -> HttpRequest: - api_version = "2018-08-01" - accept = "application/json" # Construct URL - url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/trafficmanagerprofiles') + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/trafficmanagerprofiles", + ) # pylint: disable=line-too-long path_format_arguments = { - "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str'), - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - url = _format_url_section(url, **path_format_arguments) + _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] - header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') - - return HttpRequest( - method="GET", - url=url, - params=query_parameters, - headers=header_parameters, - **kwargs - ) + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_by_subscription_request(subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", "2022-04-01-preview") + ) # type: Literal["2022-04-01-preview"] + accept = _headers.pop("Accept", "application/json") -def build_list_by_subscription_request( - subscription_id: str, - **kwargs: Any -) -> HttpRequest: - api_version = "2018-08-01" - accept = "application/json" # Construct URL - url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/providers/Microsoft.Network/trafficmanagerprofiles') + _url = kwargs.pop( + "template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Network/trafficmanagerprofiles" + ) path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - url = _format_url_section(url, **path_format_arguments) + _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] - header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') - - return HttpRequest( - method="GET", - url=url, - params=query_parameters, - headers=header_parameters, - **kwargs - ) + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_request(resource_group_name: str, profile_name: str, subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", "2022-04-01-preview") + ) # type: Literal["2022-04-01-preview"] + accept = _headers.pop("Accept", "application/json") -def build_get_request( - resource_group_name: str, - profile_name: str, - subscription_id: str, - **kwargs: Any -) -> HttpRequest: - api_version = "2018-08-01" - accept = "application/json" # Construct URL - url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/trafficmanagerprofiles/{profileName}') + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/trafficmanagerprofiles/{profileName}", + ) # pylint: disable=line-too-long path_format_arguments = { - "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str'), - "profileName": _SERIALIZER.url("profile_name", profile_name, 'str'), - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "profileName": _SERIALIZER.url("profile_name", profile_name, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - url = _format_url_section(url, **path_format_arguments) + _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] - header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') - - return HttpRequest( - method="GET", - url=url, - params=query_parameters, - headers=header_parameters, - **kwargs - ) + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_create_or_update_request( - resource_group_name: str, - profile_name: str, - subscription_id: str, - *, - json: JSONType = None, - content: Any = None, - **kwargs: Any + resource_group_name: str, profile_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: - content_type = kwargs.pop('content_type', None) # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", "2022-04-01-preview") + ) # type: Literal["2022-04-01-preview"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") - api_version = "2018-08-01" - accept = "application/json" # Construct URL - url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/trafficmanagerprofiles/{profileName}') + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/trafficmanagerprofiles/{profileName}", + ) # pylint: disable=line-too-long path_format_arguments = { - "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str'), - "profileName": _SERIALIZER.url("profile_name", profile_name, 'str'), - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "profileName": _SERIALIZER.url("profile_name", profile_name, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - url = _format_url_section(url, **path_format_arguments) + _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] if content_type is not None: - header_parameters['Content-Type'] = _SERIALIZER.header("content_type", content_type, 'str') - header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') - - return HttpRequest( - method="PUT", - url=url, - params=query_parameters, - headers=header_parameters, - json=json, - content=content, - **kwargs - ) + _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, - profile_name: str, - subscription_id: str, - **kwargs: Any + resource_group_name: str, profile_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: - api_version = "2018-08-01" - accept = "application/json" + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", "2022-04-01-preview") + ) # type: Literal["2022-04-01-preview"] + accept = _headers.pop("Accept", "application/json") + # Construct URL - url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/trafficmanagerprofiles/{profileName}') + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/trafficmanagerprofiles/{profileName}", + ) # pylint: disable=line-too-long path_format_arguments = { - "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str'), - "profileName": _SERIALIZER.url("profile_name", profile_name, 'str'), - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "profileName": _SERIALIZER.url("profile_name", profile_name, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - url = _format_url_section(url, **path_format_arguments) + _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] - header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') - - return HttpRequest( - method="DELETE", - url=url, - params=query_parameters, - headers=header_parameters, - **kwargs - ) + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) def build_update_request( - resource_group_name: str, - profile_name: str, - subscription_id: str, - *, - json: JSONType = None, - content: Any = None, - **kwargs: Any + resource_group_name: str, profile_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: - content_type = kwargs.pop('content_type', None) # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", "2022-04-01-preview") + ) # type: Literal["2022-04-01-preview"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") - api_version = "2018-08-01" - accept = "application/json" # Construct URL - url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/trafficmanagerprofiles/{profileName}') + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/trafficmanagerprofiles/{profileName}", + ) # pylint: disable=line-too-long path_format_arguments = { - "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str'), - "profileName": _SERIALIZER.url("profile_name", profile_name, 'str'), - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "profileName": _SERIALIZER.url("profile_name", profile_name, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - url = _format_url_section(url, **path_format_arguments) + _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] if content_type is not None: - header_parameters['Content-Type'] = _SERIALIZER.header("content_type", content_type, 'str') - header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') - - return HttpRequest( - method="PATCH", - url=url, - params=query_parameters, - headers=header_parameters, - json=json, - content=content, - **kwargs - ) + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") -class ProfilesOperations(object): - """ProfilesOperations operations. + return HttpRequest(method="PATCH", 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.trafficmanager.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 ProfilesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.trafficmanager.TrafficManagerManagementClient`'s + :attr:`profiles` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer): - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - @distributed_trace + @overload def check_traffic_manager_relative_dns_name_availability( self, - parameters: "_models.CheckTrafficManagerRelativeDnsNameAvailabilityParameters", + parameters: _models.CheckTrafficManagerRelativeDnsNameAvailabilityParameters, + *, + content_type: str = "application/json", **kwargs: Any - ) -> "_models.TrafficManagerNameAvailability": + ) -> _models.TrafficManagerNameAvailability: """Checks the availability of a Traffic Manager Relative DNS name. :param parameters: The Traffic Manager name parameters supplied to the - CheckTrafficManagerNameAvailability operation. + CheckTrafficManagerNameAvailability operation. Required. :type parameters: ~azure.mgmt.trafficmanager.models.CheckTrafficManagerRelativeDnsNameAvailabilityParameters + :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: TrafficManagerNameAvailability or the result of cls(response) + :rtype: ~azure.mgmt.trafficmanager.models.TrafficManagerNameAvailability + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def check_traffic_manager_relative_dns_name_availability( + self, parameters: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.TrafficManagerNameAvailability: + """Checks the availability of a Traffic Manager Relative DNS name. + + :param parameters: The Traffic Manager name parameters supplied to the + CheckTrafficManagerNameAvailability operation. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: TrafficManagerNameAvailability or the result of cls(response) + :rtype: ~azure.mgmt.trafficmanager.models.TrafficManagerNameAvailability + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def check_traffic_manager_relative_dns_name_availability( + self, parameters: Union[_models.CheckTrafficManagerRelativeDnsNameAvailabilityParameters, IO], **kwargs: Any + ) -> _models.TrafficManagerNameAvailability: + """Checks the availability of a Traffic Manager Relative DNS name. + + :param parameters: The Traffic Manager name parameters supplied to the + CheckTrafficManagerNameAvailability operation. Is either a model type or a IO type. Required. + :type parameters: + ~azure.mgmt.trafficmanager.models.CheckTrafficManagerRelativeDnsNameAvailabilityParameters 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: TrafficManagerNameAvailability, or the result of cls(response) + :return: TrafficManagerNameAvailability or the result of cls(response) :rtype: ~azure.mgmt.trafficmanager.models.TrafficManagerNameAvailability - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.TrafficManagerNameAvailability"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-04-01-preview"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.TrafficManagerNameAvailability] - _json = self._serialize.body(parameters, 'CheckTrafficManagerRelativeDnsNameAvailabilityParameters') + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "CheckTrafficManagerRelativeDnsNameAvailabilityParameters") request = build_check_traffic_manager_relative_dns_name_availability_request( + api_version=api_version, content_type=content_type, json=_json, - template_url=self.check_traffic_manager_relative_dns_name_availability.metadata['url'], + content=_content, + template_url=self.check_traffic_manager_relative_dns_name_availability.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('TrafficManagerNameAvailability', pipeline_response) + deserialized = self._deserialize("TrafficManagerNameAvailability", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - check_traffic_manager_relative_dns_name_availability.metadata = {'url': '/providers/Microsoft.Network/checkTrafficManagerNameAvailability'} # type: ignore - + check_traffic_manager_relative_dns_name_availability.metadata = {"url": "/providers/Microsoft.Network/checkTrafficManagerNameAvailability"} # type: ignore @distributed_trace - def list_by_resource_group( - self, - resource_group_name: str, - **kwargs: Any - ) -> Iterable["_models.ProfileListResult"]: + def list_by_resource_group(self, resource_group_name: str, **kwargs: Any) -> Iterable["_models.Profile"]: """Lists all Traffic Manager profiles within a resource group. - :param resource_group_name: The name of the resource group containing the Traffic Manager - profiles to be listed. + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either ProfileListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.trafficmanager.models.ProfileListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either Profile or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.trafficmanager.models.Profile] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.ProfileListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-04-01-preview"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.ProfileListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_by_resource_group_request( resource_group_name=resource_group_name, subscription_id=self._config.subscription_id, - template_url=self.list_by_resource_group.metadata['url'], + 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) + request.url = self._client.format_url(request.url) # type: ignore else: - - request = build_list_by_resource_group_request( - resource_group_name=resource_group_name, - subscription_id=self._config.subscription_id, - template_url=next_link, + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request @@ -410,7 +474,9 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: @@ -419,47 +485,63 @@ def get_next(next_link=None): return pipeline_response + return ItemPaged(get_next, extract_data) - return ItemPaged( - get_next, extract_data - ) - list_by_resource_group.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/trafficmanagerprofiles'} # type: ignore + list_by_resource_group.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/trafficmanagerprofiles"} # type: ignore @distributed_trace - def list_by_subscription( - self, - **kwargs: Any - ) -> Iterable["_models.ProfileListResult"]: + def list_by_subscription(self, **kwargs: Any) -> Iterable["_models.Profile"]: """Lists all Traffic Manager profiles within a subscription. :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either ProfileListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.trafficmanager.models.ProfileListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either Profile or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.trafficmanager.models.Profile] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.ProfileListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-04-01-preview"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.ProfileListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_by_subscription_request( subscription_id=self._config.subscription_id, - template_url=self.list_by_subscription.metadata['url'], + api_version=api_version, + template_url=self.list_by_subscription.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore else: - - request = build_list_by_subscription_request( - subscription_id=self._config.subscription_id, - template_url=next_link, + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request @@ -473,7 +555,9 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: @@ -482,109 +566,195 @@ def get_next(next_link=None): return pipeline_response + return ItemPaged(get_next, extract_data) - return ItemPaged( - get_next, extract_data - ) - list_by_subscription.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Network/trafficmanagerprofiles'} # type: ignore + list_by_subscription.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Network/trafficmanagerprofiles"} # type: ignore @distributed_trace - def get( - self, - resource_group_name: str, - profile_name: str, - **kwargs: Any - ) -> "_models.Profile": + def get(self, resource_group_name: str, profile_name: str, **kwargs: Any) -> _models.Profile: """Gets a Traffic Manager profile. - :param resource_group_name: The name of the resource group containing the Traffic Manager - profile. + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param profile_name: The name of the Traffic Manager profile. + :param profile_name: The name of the Traffic Manager profile. Required. :type profile_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: Profile, or the result of cls(response) + :return: Profile or the result of cls(response) :rtype: ~azure.mgmt.trafficmanager.models.Profile - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Profile"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-04-01-preview"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.Profile] - request = build_get_request( resource_group_name=resource_group_name, profile_name=profile_name, subscription_id=self._config.subscription_id, - template_url=self.get.metadata['url'], + 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) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - 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('Profile', pipeline_response) + deserialized = self._deserialize("Profile", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/trafficmanagerprofiles/{profileName}'} # type: ignore - + get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/trafficmanagerprofiles/{profileName}"} # type: ignore - @distributed_trace + @overload def create_or_update( self, resource_group_name: str, profile_name: str, - parameters: "_models.Profile", + parameters: _models.Profile, + *, + content_type: str = "application/json", **kwargs: Any - ) -> "_models.Profile": + ) -> _models.Profile: """Create or update a Traffic Manager profile. - :param resource_group_name: The name of the resource group containing the Traffic Manager - profile. + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param profile_name: The name of the Traffic Manager profile. + :param profile_name: The name of the Traffic Manager profile. Required. :type profile_name: str :param parameters: The Traffic Manager profile parameters supplied to the CreateOrUpdate - operation. + operation. Required. :type parameters: ~azure.mgmt.trafficmanager.models.Profile + :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: Profile, or the result of cls(response) + :return: Profile or the result of cls(response) :rtype: ~azure.mgmt.trafficmanager.models.Profile - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_or_update( + self, + resource_group_name: str, + profile_name: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Profile: + """Create or update a Traffic Manager profile. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param profile_name: The name of the Traffic Manager profile. Required. + :type profile_name: str + :param parameters: The Traffic Manager profile parameters supplied to the CreateOrUpdate + operation. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: Profile or the result of cls(response) + :rtype: ~azure.mgmt.trafficmanager.models.Profile + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create_or_update( + self, resource_group_name: str, profile_name: str, parameters: Union[_models.Profile, IO], **kwargs: Any + ) -> _models.Profile: + """Create or update a Traffic Manager profile. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param profile_name: The name of the Traffic Manager profile. Required. + :type profile_name: str + :param parameters: The Traffic Manager profile parameters supplied to the CreateOrUpdate + operation. Is either a model type or a IO type. Required. + :type parameters: ~azure.mgmt.trafficmanager.models.Profile 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: Profile or the result of cls(response) + :rtype: ~azure.mgmt.trafficmanager.models.Profile + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Profile"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-04-01-preview"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.Profile] - _json = self._serialize.body(parameters, 'Profile') + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "Profile") request = build_create_or_update_request( resource_group_name=resource_group_name, profile_name=profile_name, subscription_id=self._config.subscription_id, + api_version=api_version, content_type=content_type, json=_json, - template_url=self.create_or_update.metadata['url'], + 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) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 201]: @@ -592,55 +762,66 @@ def create_or_update( raise HttpResponseError(response=response, error_format=ARMErrorFormat) if response.status_code == 200: - deserialized = self._deserialize('Profile', pipeline_response) + deserialized = self._deserialize("Profile", pipeline_response) if response.status_code == 201: - deserialized = self._deserialize('Profile', pipeline_response) + deserialized = self._deserialize("Profile", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/trafficmanagerprofiles/{profileName}'} # type: ignore - + create_or_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/trafficmanagerprofiles/{profileName}"} # type: ignore @distributed_trace def delete( - self, - resource_group_name: str, - profile_name: str, - **kwargs: Any - ) -> Optional["_models.DeleteOperationResult"]: + self, resource_group_name: str, profile_name: str, **kwargs: Any + ) -> Optional[_models.DeleteOperationResult]: """Deletes a Traffic Manager profile. - :param resource_group_name: The name of the resource group containing the Traffic Manager - profile to be deleted. + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param profile_name: The name of the Traffic Manager profile to be deleted. + :param profile_name: The name of the Traffic Manager profile to be deleted. Required. :type profile_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: DeleteOperationResult, or the result of cls(response) + :return: DeleteOperationResult or None or the result of cls(response) :rtype: ~azure.mgmt.trafficmanager.models.DeleteOperationResult or None - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.DeleteOperationResult"]] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-04-01-preview"] + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.DeleteOperationResult]] - request = build_delete_request( resource_group_name=resource_group_name, profile_name=profile_name, subscription_id=self._config.subscription_id, - template_url=self.delete.metadata['url'], + 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) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 204]: @@ -649,72 +830,150 @@ def delete( deserialized = None if response.status_code == 200: - deserialized = self._deserialize('DeleteOperationResult', pipeline_response) + deserialized = self._deserialize("DeleteOperationResult", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/trafficmanagerprofiles/{profileName}'} # type: ignore - + delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/trafficmanagerprofiles/{profileName}"} # type: ignore - @distributed_trace + @overload def update( self, resource_group_name: str, profile_name: str, - parameters: "_models.Profile", + parameters: _models.Profile, + *, + content_type: str = "application/json", **kwargs: Any - ) -> "_models.Profile": + ) -> _models.Profile: """Update a Traffic Manager profile. - :param resource_group_name: The name of the resource group containing the Traffic Manager - profile. + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param profile_name: The name of the Traffic Manager profile. + :param profile_name: The name of the Traffic Manager profile. Required. :type profile_name: str :param parameters: The Traffic Manager profile parameters supplied to the Update operation. + Required. :type parameters: ~azure.mgmt.trafficmanager.models.Profile + :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: Profile, or the result of cls(response) + :return: Profile or the result of cls(response) :rtype: ~azure.mgmt.trafficmanager.models.Profile - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def update( + self, + resource_group_name: str, + profile_name: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Profile: + """Update a Traffic Manager profile. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param profile_name: The name of the Traffic Manager profile. Required. + :type profile_name: str + :param parameters: The Traffic Manager profile parameters supplied to the Update operation. + Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: Profile or the result of cls(response) + :rtype: ~azure.mgmt.trafficmanager.models.Profile + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def update( + self, resource_group_name: str, profile_name: str, parameters: Union[_models.Profile, IO], **kwargs: Any + ) -> _models.Profile: + """Update a Traffic Manager profile. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param profile_name: The name of the Traffic Manager profile. Required. + :type profile_name: str + :param parameters: The Traffic Manager profile parameters supplied to the Update operation. Is + either a model type or a IO type. Required. + :type parameters: ~azure.mgmt.trafficmanager.models.Profile 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: Profile or the result of cls(response) + :rtype: ~azure.mgmt.trafficmanager.models.Profile + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Profile"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - _json = self._serialize.body(parameters, 'Profile') + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-04-01-preview"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.Profile] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "Profile") request = build_update_request( resource_group_name=resource_group_name, profile_name=profile_name, subscription_id=self._config.subscription_id, + api_version=api_version, content_type=content_type, json=_json, - template_url=self.update.metadata['url'], + content=_content, + template_url=self.update.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('Profile', pipeline_response) + deserialized = self._deserialize("Profile", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/trafficmanagerprofiles/{profileName}'} # type: ignore - + update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/trafficmanagerprofiles/{profileName}"} # type: ignore diff --git a/sdk/trafficmanager/azure-mgmt-trafficmanager/azure/mgmt/trafficmanager/operations/_traffic_manager_user_metrics_keys_operations.py b/sdk/trafficmanager/azure-mgmt-trafficmanager/azure/mgmt/trafficmanager/operations/_traffic_manager_user_metrics_keys_operations.py index 4d176c695b48..9df36e9a002d 100644 --- a/sdk/trafficmanager/azure-mgmt-trafficmanager/azure/mgmt/trafficmanager/operations/_traffic_manager_user_metrics_keys_operations.py +++ b/sdk/trafficmanager/azure-mgmt-trafficmanager/azure/mgmt/trafficmanager/operations/_traffic_manager_user_metrics_keys_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,265 +6,303 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -import functools -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, Optional, TypeVar + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat -from msrest import Serializer from .. import models as _models +from .._serialization import Serializer from .._vendor import _convert_request, _format_url_section -T = TypeVar('T') + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False -def build_get_request( - subscription_id: str, - **kwargs: Any -) -> HttpRequest: - api_version = "2018-08-01" - accept = "application/json" + +def build_get_request(subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", "2022-04-01-preview") + ) # type: Literal["2022-04-01-preview"] + accept = _headers.pop("Accept", "application/json") + # Construct URL - url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/providers/Microsoft.Network/trafficManagerUserMetricsKeys/default') + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Network/trafficManagerUserMetricsKeys/default", + ) # pylint: disable=line-too-long path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - url = _format_url_section(url, **path_format_arguments) + _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] - header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') - - return HttpRequest( - method="GET", - url=url, - params=query_parameters, - headers=header_parameters, - **kwargs - ) - - -def build_create_or_update_request( - subscription_id: str, - **kwargs: Any -) -> HttpRequest: - api_version = "2018-08-01" - accept = "application/json" + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_create_or_update_request(subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", "2022-04-01-preview") + ) # type: Literal["2022-04-01-preview"] + accept = _headers.pop("Accept", "application/json") + # Construct URL - url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/providers/Microsoft.Network/trafficManagerUserMetricsKeys/default') + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Network/trafficManagerUserMetricsKeys/default", + ) # pylint: disable=line-too-long path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - url = _format_url_section(url, **path_format_arguments) + _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] - header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') - - return HttpRequest( - method="PUT", - url=url, - params=query_parameters, - headers=header_parameters, - **kwargs - ) - - -def build_delete_request( - subscription_id: str, - **kwargs: Any -) -> HttpRequest: - api_version = "2018-08-01" - accept = "application/json" + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_delete_request(subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", "2022-04-01-preview") + ) # type: Literal["2022-04-01-preview"] + accept = _headers.pop("Accept", "application/json") + # Construct URL - url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/providers/Microsoft.Network/trafficManagerUserMetricsKeys/default') + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Network/trafficManagerUserMetricsKeys/default", + ) # pylint: disable=line-too-long path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - url = _format_url_section(url, **path_format_arguments) + _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] - header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') - - return HttpRequest( - method="DELETE", - url=url, - params=query_parameters, - headers=header_parameters, - **kwargs - ) - -class TrafficManagerUserMetricsKeysOperations(object): - """TrafficManagerUserMetricsKeysOperations operations. - - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. - - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.trafficmanager.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +class TrafficManagerUserMetricsKeysOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.trafficmanager.TrafficManagerManagementClient`'s + :attr:`traffic_manager_user_metrics_keys` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer): - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace - def get( - self, - **kwargs: Any - ) -> "_models.UserMetricsModel": + def get(self, **kwargs: Any) -> _models.UserMetricsModel: """Get the subscription-level key used for Real User Metrics collection. :keyword callable cls: A custom type or function that will be passed the direct response - :return: UserMetricsModel, or the result of cls(response) + :return: UserMetricsModel or the result of cls(response) :rtype: ~azure.mgmt.trafficmanager.models.UserMetricsModel - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.UserMetricsModel"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-04-01-preview"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.UserMetricsModel] - request = build_get_request( subscription_id=self._config.subscription_id, - template_url=self.get.metadata['url'], + 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) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - 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('UserMetricsModel', pipeline_response) + deserialized = self._deserialize("UserMetricsModel", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Network/trafficManagerUserMetricsKeys/default'} # type: ignore - + get.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Network/trafficManagerUserMetricsKeys/default"} # type: ignore @distributed_trace - def create_or_update( - self, - **kwargs: Any - ) -> "_models.UserMetricsModel": + def create_or_update(self, **kwargs: Any) -> _models.UserMetricsModel: """Create or update a subscription-level key used for Real User Metrics collection. :keyword callable cls: A custom type or function that will be passed the direct response - :return: UserMetricsModel, or the result of cls(response) + :return: UserMetricsModel or the result of cls(response) :rtype: ~azure.mgmt.trafficmanager.models.UserMetricsModel - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.UserMetricsModel"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-04-01-preview"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.UserMetricsModel] - request = build_create_or_update_request( subscription_id=self._config.subscription_id, - template_url=self.create_or_update.metadata['url'], + api_version=api_version, + template_url=self.create_or_update.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [201]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('UserMetricsModel', pipeline_response) + deserialized = self._deserialize("UserMetricsModel", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Network/trafficManagerUserMetricsKeys/default'} # type: ignore - + create_or_update.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Network/trafficManagerUserMetricsKeys/default"} # type: ignore @distributed_trace - def delete( - self, - **kwargs: Any - ) -> "_models.DeleteOperationResult": + def delete(self, **kwargs: Any) -> _models.DeleteOperationResult: """Delete a subscription-level key used for Real User Metrics collection. :keyword callable cls: A custom type or function that will be passed the direct response - :return: DeleteOperationResult, or the result of cls(response) + :return: DeleteOperationResult or the result of cls(response) :rtype: ~azure.mgmt.trafficmanager.models.DeleteOperationResult - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.DeleteOperationResult"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-04-01-preview"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.DeleteOperationResult] - request = build_delete_request( subscription_id=self._config.subscription_id, - template_url=self.delete.metadata['url'], + 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) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - 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('DeleteOperationResult', pipeline_response) + deserialized = self._deserialize("DeleteOperationResult", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - delete.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Network/trafficManagerUserMetricsKeys/default'} # type: ignore - + delete.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Network/trafficManagerUserMetricsKeys/default"} # type: ignore diff --git a/sdk/trafficmanager/azure-mgmt-trafficmanager/generated_samples/endpoint_delete_external.py b/sdk/trafficmanager/azure-mgmt-trafficmanager/generated_samples/endpoint_delete_external.py new file mode 100644 index 000000000000..e0d8793e92d0 --- /dev/null +++ b/sdk/trafficmanager/azure-mgmt-trafficmanager/generated_samples/endpoint_delete_external.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.trafficmanager import TrafficManagerManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-trafficmanager +# USAGE + python endpoint_delete_external.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 = TrafficManagerManagementClient( + credential=DefaultAzureCredential(), + subscription_id="{subscription-id}", + ) + + response = client.endpoints.delete( + resource_group_name="azuresdkfornetautoresttrafficmanager1421", + profile_name="azsmnet6386", + endpoint_type="ExternalEndpoints", + endpoint_name="azsmnet7187", + ) + print(response) + + +# x-ms-original-file: specification/trafficmanager/resource-manager/Microsoft.Network/preview/2022-04-01-preview/examples/Endpoint-DELETE-External.json +if __name__ == "__main__": + main() diff --git a/sdk/trafficmanager/azure-mgmt-trafficmanager/generated_samples/endpoint_get_external_with_geo_mapping.py b/sdk/trafficmanager/azure-mgmt-trafficmanager/generated_samples/endpoint_get_external_with_geo_mapping.py new file mode 100644 index 000000000000..57c927263d59 --- /dev/null +++ b/sdk/trafficmanager/azure-mgmt-trafficmanager/generated_samples/endpoint_get_external_with_geo_mapping.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.trafficmanager import TrafficManagerManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-trafficmanager +# USAGE + python endpoint_get_external_with_geo_mapping.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 = TrafficManagerManagementClient( + credential=DefaultAzureCredential(), + subscription_id="{subscription-id}", + ) + + response = client.endpoints.get( + resource_group_name="azuresdkfornetautoresttrafficmanager2191", + profile_name="azuresdkfornetautoresttrafficmanager8224", + endpoint_type="ExternalEndpoints", + endpoint_name="My%20external%20endpoint", + ) + print(response) + + +# x-ms-original-file: specification/trafficmanager/resource-manager/Microsoft.Network/preview/2022-04-01-preview/examples/Endpoint-GET-External-WithGeoMapping.json +if __name__ == "__main__": + main() diff --git a/sdk/trafficmanager/azure-mgmt-trafficmanager/generated_samples/endpoint_get_external_with_location.py b/sdk/trafficmanager/azure-mgmt-trafficmanager/generated_samples/endpoint_get_external_with_location.py new file mode 100644 index 000000000000..3a692c4bb75b --- /dev/null +++ b/sdk/trafficmanager/azure-mgmt-trafficmanager/generated_samples/endpoint_get_external_with_location.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.trafficmanager import TrafficManagerManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-trafficmanager +# USAGE + python endpoint_get_external_with_location.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 = TrafficManagerManagementClient( + credential=DefaultAzureCredential(), + subscription_id="{subscription-id}", + ) + + response = client.endpoints.get( + resource_group_name="azuresdkfornetautoresttrafficmanager1421", + profile_name="azsmnet6386", + endpoint_type="ExternalEndpoints", + endpoint_name="azsmnet7187", + ) + print(response) + + +# x-ms-original-file: specification/trafficmanager/resource-manager/Microsoft.Network/preview/2022-04-01-preview/examples/Endpoint-GET-External-WithLocation.json +if __name__ == "__main__": + main() diff --git a/sdk/trafficmanager/azure-mgmt-trafficmanager/generated_samples/endpoint_get_external_with_subnet_mapping.py b/sdk/trafficmanager/azure-mgmt-trafficmanager/generated_samples/endpoint_get_external_with_subnet_mapping.py new file mode 100644 index 000000000000..7d60e2775597 --- /dev/null +++ b/sdk/trafficmanager/azure-mgmt-trafficmanager/generated_samples/endpoint_get_external_with_subnet_mapping.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.trafficmanager import TrafficManagerManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-trafficmanager +# USAGE + python endpoint_get_external_with_subnet_mapping.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 = TrafficManagerManagementClient( + credential=DefaultAzureCredential(), + subscription_id="{subscription-id}", + ) + + response = client.endpoints.get( + resource_group_name="azuresdkfornetautoresttrafficmanager2191", + profile_name="azuresdkfornetautoresttrafficmanager8224", + endpoint_type="ExternalEndpoints", + endpoint_name="My%20external%20endpoint", + ) + print(response) + + +# x-ms-original-file: specification/trafficmanager/resource-manager/Microsoft.Network/preview/2022-04-01-preview/examples/Endpoint-GET-External-WithSubnetMapping.json +if __name__ == "__main__": + main() diff --git a/sdk/trafficmanager/azure-mgmt-trafficmanager/generated_samples/endpoint_patch_external_target.py b/sdk/trafficmanager/azure-mgmt-trafficmanager/generated_samples/endpoint_patch_external_target.py new file mode 100644 index 000000000000..35f6666d85f7 --- /dev/null +++ b/sdk/trafficmanager/azure-mgmt-trafficmanager/generated_samples/endpoint_patch_external_target.py @@ -0,0 +1,49 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.trafficmanager import TrafficManagerManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-trafficmanager +# USAGE + python endpoint_patch_external_target.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 = TrafficManagerManagementClient( + credential=DefaultAzureCredential(), + subscription_id="{subscription-id}", + ) + + response = client.endpoints.update( + resource_group_name="azuresdkfornetautoresttrafficmanager1421", + profile_name="azsmnet6386", + endpoint_type="ExternalEndpoints", + endpoint_name="azsmnet7187", + parameters={ + "id": "/subscriptions/{subscription-id}/resourceGroups/azuresdkfornetautoresttrafficmanager1421/providers/Microsoft.Network/trafficManagerProfiles/azsmnet6386/externalEndpoints/azsmnet7187", + "name": "azsmnet7187", + "properties": {"target": "another.foobar.contoso.com"}, + "type": "Microsoft.Network/trafficManagerProfiles/externalEndpoints", + }, + ) + print(response) + + +# x-ms-original-file: specification/trafficmanager/resource-manager/Microsoft.Network/preview/2022-04-01-preview/examples/Endpoint-PATCH-External-Target.json +if __name__ == "__main__": + main() diff --git a/sdk/trafficmanager/azure-mgmt-trafficmanager/generated_samples/endpoint_put_external_with_always_serve.py b/sdk/trafficmanager/azure-mgmt-trafficmanager/generated_samples/endpoint_put_external_with_always_serve.py new file mode 100644 index 000000000000..57ee7baa5a22 --- /dev/null +++ b/sdk/trafficmanager/azure-mgmt-trafficmanager/generated_samples/endpoint_put_external_with_always_serve.py @@ -0,0 +1,53 @@ +# 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.trafficmanager import TrafficManagerManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-trafficmanager +# USAGE + python endpoint_put_external_with_always_serve.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 = TrafficManagerManagementClient( + credential=DefaultAzureCredential(), + subscription_id="{subscription-id}", + ) + + response = client.endpoints.create_or_update( + resource_group_name="azuresdkfornetautoresttrafficmanager1421", + profile_name="azsmnet6386", + endpoint_type="ExternalEndpoints", + endpoint_name="azsmnet7187", + parameters={ + "name": "azsmnet7187", + "properties": { + "alwaysServe": "Enabled", + "endpointLocation": "North Europe", + "endpointStatus": "Enabled", + "target": "foobar.contoso.com", + }, + "type": "Microsoft.network/TrafficManagerProfiles/ExternalEndpoints", + }, + ) + print(response) + + +# x-ms-original-file: specification/trafficmanager/resource-manager/Microsoft.Network/preview/2022-04-01-preview/examples/Endpoint-PUT-External-WithAlwaysServe.json +if __name__ == "__main__": + main() diff --git a/sdk/trafficmanager/azure-mgmt-trafficmanager/generated_samples/endpoint_put_external_with_custom_headers.py b/sdk/trafficmanager/azure-mgmt-trafficmanager/generated_samples/endpoint_put_external_with_custom_headers.py new file mode 100644 index 000000000000..2b1556062166 --- /dev/null +++ b/sdk/trafficmanager/azure-mgmt-trafficmanager/generated_samples/endpoint_put_external_with_custom_headers.py @@ -0,0 +1,53 @@ +# 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.trafficmanager import TrafficManagerManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-trafficmanager +# USAGE + python endpoint_put_external_with_custom_headers.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 = TrafficManagerManagementClient( + credential=DefaultAzureCredential(), + subscription_id="{subscription-id}", + ) + + response = client.endpoints.create_or_update( + resource_group_name="azuresdkfornetautoresttrafficmanager1421", + profile_name="azsmnet6386", + endpoint_type="ExternalEndpoints", + endpoint_name="azsmnet7187", + parameters={ + "name": "azsmnet7187", + "properties": { + "customHeaders": [{"name": "header-1", "value": "value-1"}, {"name": "header-2", "value": "value-2"}], + "endpointLocation": "North Europe", + "endpointStatus": "Enabled", + "target": "foobar.contoso.com", + }, + "type": "Microsoft.network/TrafficManagerProfiles/ExternalEndpoints", + }, + ) + print(response) + + +# x-ms-original-file: specification/trafficmanager/resource-manager/Microsoft.Network/preview/2022-04-01-preview/examples/Endpoint-PUT-External-WithCustomHeaders.json +if __name__ == "__main__": + main() diff --git a/sdk/trafficmanager/azure-mgmt-trafficmanager/generated_samples/endpoint_put_external_with_geo_mapping.py b/sdk/trafficmanager/azure-mgmt-trafficmanager/generated_samples/endpoint_put_external_with_geo_mapping.py new file mode 100644 index 000000000000..fbe98b3a1e7d --- /dev/null +++ b/sdk/trafficmanager/azure-mgmt-trafficmanager/generated_samples/endpoint_put_external_with_geo_mapping.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.trafficmanager import TrafficManagerManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-trafficmanager +# USAGE + python endpoint_put_external_with_geo_mapping.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 = TrafficManagerManagementClient( + credential=DefaultAzureCredential(), + subscription_id="{subscription-id}", + ) + + response = client.endpoints.create_or_update( + resource_group_name="azuresdkfornetautoresttrafficmanager2191", + profile_name="azuresdkfornetautoresttrafficmanager8224", + endpoint_type="ExternalEndpoints", + endpoint_name="My%20external%20endpoint", + parameters={ + "name": "My external endpoint", + "properties": { + "endpointStatus": "Enabled", + "geoMapping": ["GEO-AS", "GEO-AF"], + "target": "foobar.contoso.com", + }, + "type": "Microsoft.network/TrafficManagerProfiles/ExternalEndpoints", + }, + ) + print(response) + + +# x-ms-original-file: specification/trafficmanager/resource-manager/Microsoft.Network/preview/2022-04-01-preview/examples/Endpoint-PUT-External-WithGeoMapping.json +if __name__ == "__main__": + main() diff --git a/sdk/trafficmanager/azure-mgmt-trafficmanager/generated_samples/endpoint_put_external_with_location.py b/sdk/trafficmanager/azure-mgmt-trafficmanager/generated_samples/endpoint_put_external_with_location.py new file mode 100644 index 000000000000..aefcafc738a4 --- /dev/null +++ b/sdk/trafficmanager/azure-mgmt-trafficmanager/generated_samples/endpoint_put_external_with_location.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.trafficmanager import TrafficManagerManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-trafficmanager +# USAGE + python endpoint_put_external_with_location.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 = TrafficManagerManagementClient( + credential=DefaultAzureCredential(), + subscription_id="{subscription-id}", + ) + + response = client.endpoints.create_or_update( + resource_group_name="azuresdkfornetautoresttrafficmanager1421", + profile_name="azsmnet6386", + endpoint_type="ExternalEndpoints", + endpoint_name="azsmnet7187", + parameters={ + "name": "azsmnet7187", + "properties": { + "endpointLocation": "North Europe", + "endpointStatus": "Enabled", + "target": "foobar.contoso.com", + }, + "type": "Microsoft.network/TrafficManagerProfiles/ExternalEndpoints", + }, + ) + print(response) + + +# x-ms-original-file: specification/trafficmanager/resource-manager/Microsoft.Network/preview/2022-04-01-preview/examples/Endpoint-PUT-External-WithLocation.json +if __name__ == "__main__": + main() diff --git a/sdk/trafficmanager/azure-mgmt-trafficmanager/generated_samples/endpoint_put_external_with_subnet_mapping.py b/sdk/trafficmanager/azure-mgmt-trafficmanager/generated_samples/endpoint_put_external_with_subnet_mapping.py new file mode 100644 index 000000000000..a0adb74d4e8c --- /dev/null +++ b/sdk/trafficmanager/azure-mgmt-trafficmanager/generated_samples/endpoint_put_external_with_subnet_mapping.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.trafficmanager import TrafficManagerManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-trafficmanager +# USAGE + python endpoint_put_external_with_subnet_mapping.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 = TrafficManagerManagementClient( + credential=DefaultAzureCredential(), + subscription_id="{subscription-id}", + ) + + response = client.endpoints.create_or_update( + resource_group_name="azuresdkfornetautoresttrafficmanager2191", + profile_name="azuresdkfornetautoresttrafficmanager8224", + endpoint_type="ExternalEndpoints", + endpoint_name="My%20external%20endpoint", + parameters={ + "name": "My external endpoint", + "properties": { + "endpointStatus": "Enabled", + "subnets": [{"first": "1.2.3.0", "scope": 24}, {"first": "25.26.27.28", "last": "29.30.31.32"}], + "target": "foobar.contoso.com", + }, + "type": "Microsoft.network/TrafficManagerProfiles/ExternalEndpoints", + }, + ) + print(response) + + +# x-ms-original-file: specification/trafficmanager/resource-manager/Microsoft.Network/preview/2022-04-01-preview/examples/Endpoint-PUT-External-WithSubnetMapping.json +if __name__ == "__main__": + main() diff --git a/sdk/trafficmanager/azure-mgmt-trafficmanager/generated_samples/geographic_hierarchy_getdefault.py b/sdk/trafficmanager/azure-mgmt-trafficmanager/generated_samples/geographic_hierarchy_getdefault.py new file mode 100644 index 000000000000..8d21ea985ab9 --- /dev/null +++ b/sdk/trafficmanager/azure-mgmt-trafficmanager/generated_samples/geographic_hierarchy_getdefault.py @@ -0,0 +1,38 @@ +# 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.trafficmanager import TrafficManagerManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-trafficmanager +# USAGE + python geographic_hierarchy_getdefault.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 = TrafficManagerManagementClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.geographic_hierarchies.get_default() + print(response) + + +# x-ms-original-file: specification/trafficmanager/resource-manager/Microsoft.Network/preview/2022-04-01-preview/examples/GeographicHierarchy-GET-default.json +if __name__ == "__main__": + main() diff --git a/sdk/trafficmanager/azure-mgmt-trafficmanager/generated_samples/heat_map_get.py b/sdk/trafficmanager/azure-mgmt-trafficmanager/generated_samples/heat_map_get.py new file mode 100644 index 000000000000..bbb192375909 --- /dev/null +++ b/sdk/trafficmanager/azure-mgmt-trafficmanager/generated_samples/heat_map_get.py @@ -0,0 +1,41 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.trafficmanager import TrafficManagerManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-trafficmanager +# USAGE + python heat_map_get.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = TrafficManagerManagementClient( + credential=DefaultAzureCredential(), + subscription_id="{subscription-id}", + ) + + response = client.heat_map.get( + resource_group_name="azuresdkfornetautoresttrafficmanager1323", + profile_name="azuresdkfornetautoresttrafficmanager3880", + ) + print(response) + + +# x-ms-original-file: specification/trafficmanager/resource-manager/Microsoft.Network/preview/2022-04-01-preview/examples/HeatMap-GET.json +if __name__ == "__main__": + main() diff --git a/sdk/trafficmanager/azure-mgmt-trafficmanager/generated_samples/heat_map_get_with_null_values.py b/sdk/trafficmanager/azure-mgmt-trafficmanager/generated_samples/heat_map_get_with_null_values.py new file mode 100644 index 000000000000..f7d6511b026f --- /dev/null +++ b/sdk/trafficmanager/azure-mgmt-trafficmanager/generated_samples/heat_map_get_with_null_values.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.trafficmanager import TrafficManagerManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-trafficmanager +# USAGE + python heat_map_get_with_null_values.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 = TrafficManagerManagementClient( + credential=DefaultAzureCredential(), + subscription_id="{subscription-id}", + ) + + response = client.heat_map.get( + resource_group_name="azuresdkfornetautoresttrafficmanager1323", + profile_name="azuresdkfornetautoresttrafficmanager3880", + ) + print(response) + + +# x-ms-original-file: specification/trafficmanager/resource-manager/Microsoft.Network/preview/2022-04-01-preview/examples/HeatMap-GET-With-Null-Values.json +if __name__ == "__main__": + main() diff --git a/sdk/trafficmanager/azure-mgmt-trafficmanager/generated_samples/heat_map_get_with_top_left_bot_right.py b/sdk/trafficmanager/azure-mgmt-trafficmanager/generated_samples/heat_map_get_with_top_left_bot_right.py new file mode 100644 index 000000000000..10393d069efa --- /dev/null +++ b/sdk/trafficmanager/azure-mgmt-trafficmanager/generated_samples/heat_map_get_with_top_left_bot_right.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.trafficmanager import TrafficManagerManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-trafficmanager +# USAGE + python heat_map_get_with_top_left_bot_right.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 = TrafficManagerManagementClient( + credential=DefaultAzureCredential(), + subscription_id="{subscription-id}", + ) + + response = client.heat_map.get( + resource_group_name="azuresdkfornetautoresttrafficmanager1323", + profile_name="azuresdkfornetautoresttrafficmanager3880", + ) + print(response) + + +# x-ms-original-file: specification/trafficmanager/resource-manager/Microsoft.Network/preview/2022-04-01-preview/examples/HeatMap-GET-With-TopLeft-BotRight.json +if __name__ == "__main__": + main() diff --git a/sdk/trafficmanager/azure-mgmt-trafficmanager/generated_samples/list_by_subscription.py b/sdk/trafficmanager/azure-mgmt-trafficmanager/generated_samples/list_by_subscription.py new file mode 100644 index 000000000000..af455316ab28 --- /dev/null +++ b/sdk/trafficmanager/azure-mgmt-trafficmanager/generated_samples/list_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.trafficmanager import TrafficManagerManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-trafficmanager +# USAGE + python list_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 = TrafficManagerManagementClient( + credential=DefaultAzureCredential(), + subscription_id="{subscription-id}", + ) + + response = client.profiles.list_by_subscription() + for item in response: + print(item) + + +# x-ms-original-file: specification/trafficmanager/resource-manager/Microsoft.Network/preview/2022-04-01-preview/examples/Profile-GET-BySubscription.json +if __name__ == "__main__": + main() diff --git a/sdk/trafficmanager/azure-mgmt-trafficmanager/generated_samples/list_profiles_by_resource_group.py b/sdk/trafficmanager/azure-mgmt-trafficmanager/generated_samples/list_profiles_by_resource_group.py new file mode 100644 index 000000000000..3565f38e83ae --- /dev/null +++ b/sdk/trafficmanager/azure-mgmt-trafficmanager/generated_samples/list_profiles_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.trafficmanager import TrafficManagerManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-trafficmanager +# USAGE + python list_profiles_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 = TrafficManagerManagementClient( + credential=DefaultAzureCredential(), + subscription_id="{subscription-id}", + ) + + response = client.profiles.list_by_resource_group( + resource_group_name="azuresdkfornetautoresttrafficmanager3640", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/trafficmanager/resource-manager/Microsoft.Network/preview/2022-04-01-preview/examples/Profile-GET-ByResourceGroup.json +if __name__ == "__main__": + main() diff --git a/sdk/trafficmanager/azure-mgmt-trafficmanager/generated_samples/name_availability_test_name_available_post21.py b/sdk/trafficmanager/azure-mgmt-trafficmanager/generated_samples/name_availability_test_name_available_post21.py new file mode 100644 index 000000000000..65ff087dc9b1 --- /dev/null +++ b/sdk/trafficmanager/azure-mgmt-trafficmanager/generated_samples/name_availability_test_name_available_post21.py @@ -0,0 +1,40 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.trafficmanager import TrafficManagerManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-trafficmanager +# USAGE + python name_availability_test_name_available_post21.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 = TrafficManagerManagementClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.profiles.check_traffic_manager_relative_dns_name_availability( + parameters={"name": "azsmnet5403", "type": "microsoft.network/trafficmanagerprofiles"}, + ) + print(response) + + +# x-ms-original-file: specification/trafficmanager/resource-manager/Microsoft.Network/preview/2022-04-01-preview/examples/NameAvailabilityTest_NameAvailable-POST-example-21.json +if __name__ == "__main__": + main() diff --git a/sdk/trafficmanager/azure-mgmt-trafficmanager/generated_samples/name_availability_test_name_not_available_post23.py b/sdk/trafficmanager/azure-mgmt-trafficmanager/generated_samples/name_availability_test_name_not_available_post23.py new file mode 100644 index 000000000000..6121f3135f0c --- /dev/null +++ b/sdk/trafficmanager/azure-mgmt-trafficmanager/generated_samples/name_availability_test_name_not_available_post23.py @@ -0,0 +1,40 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.trafficmanager import TrafficManagerManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-trafficmanager +# USAGE + python name_availability_test_name_not_available_post23.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 = TrafficManagerManagementClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.profiles.check_traffic_manager_relative_dns_name_availability( + parameters={"name": "azsmnet4696", "type": "microsoft.network/trafficmanagerprofiles"}, + ) + print(response) + + +# x-ms-original-file: specification/trafficmanager/resource-manager/Microsoft.Network/preview/2022-04-01-preview/examples/NameAvailabilityTest_NameNotAvailable-POST-example-23.json +if __name__ == "__main__": + main() diff --git a/sdk/trafficmanager/azure-mgmt-trafficmanager/generated_samples/profile_delete.py b/sdk/trafficmanager/azure-mgmt-trafficmanager/generated_samples/profile_delete.py new file mode 100644 index 000000000000..d7022ffabca2 --- /dev/null +++ b/sdk/trafficmanager/azure-mgmt-trafficmanager/generated_samples/profile_delete.py @@ -0,0 +1,41 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.trafficmanager import TrafficManagerManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-trafficmanager +# USAGE + python profile_delete.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = TrafficManagerManagementClient( + credential=DefaultAzureCredential(), + subscription_id="{subscription-id}", + ) + + response = client.profiles.delete( + resource_group_name="azuresdkfornetautoresttrafficmanager1323", + profile_name="azuresdkfornetautoresttrafficmanager3880", + ) + print(response) + + +# x-ms-original-file: specification/trafficmanager/resource-manager/Microsoft.Network/preview/2022-04-01-preview/examples/Profile-DELETE.json +if __name__ == "__main__": + main() diff --git a/sdk/trafficmanager/azure-mgmt-trafficmanager/generated_samples/profile_get_with_endpoints.py b/sdk/trafficmanager/azure-mgmt-trafficmanager/generated_samples/profile_get_with_endpoints.py new file mode 100644 index 000000000000..a84fae9fd33c --- /dev/null +++ b/sdk/trafficmanager/azure-mgmt-trafficmanager/generated_samples/profile_get_with_endpoints.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.trafficmanager import TrafficManagerManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-trafficmanager +# USAGE + python profile_get_with_endpoints.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 = TrafficManagerManagementClient( + credential=DefaultAzureCredential(), + subscription_id="{subscription-id}", + ) + + response = client.profiles.get( + resource_group_name="azuresdkfornetautoresttrafficmanager1323", + profile_name="azuresdkfornetautoresttrafficmanager3880", + ) + print(response) + + +# x-ms-original-file: specification/trafficmanager/resource-manager/Microsoft.Network/preview/2022-04-01-preview/examples/Profile-GET-WithEndpoints.json +if __name__ == "__main__": + main() diff --git a/sdk/trafficmanager/azure-mgmt-trafficmanager/generated_samples/profile_get_with_traffic_view_disabled.py b/sdk/trafficmanager/azure-mgmt-trafficmanager/generated_samples/profile_get_with_traffic_view_disabled.py new file mode 100644 index 000000000000..593913215d30 --- /dev/null +++ b/sdk/trafficmanager/azure-mgmt-trafficmanager/generated_samples/profile_get_with_traffic_view_disabled.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.trafficmanager import TrafficManagerManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-trafficmanager +# USAGE + python profile_get_with_traffic_view_disabled.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 = TrafficManagerManagementClient( + credential=DefaultAzureCredential(), + subscription_id="{subscription-id}", + ) + + response = client.profiles.get( + resource_group_name="azuresdkfornetautoresttrafficmanager1323", + profile_name="azuresdkfornetautoresttrafficmanager3880", + ) + print(response) + + +# x-ms-original-file: specification/trafficmanager/resource-manager/Microsoft.Network/preview/2022-04-01-preview/examples/Profile-GET-WithTrafficViewDisabled.json +if __name__ == "__main__": + main() diff --git a/sdk/trafficmanager/azure-mgmt-trafficmanager/generated_samples/profile_get_with_traffic_view_enabled.py b/sdk/trafficmanager/azure-mgmt-trafficmanager/generated_samples/profile_get_with_traffic_view_enabled.py new file mode 100644 index 000000000000..f581c05b41af --- /dev/null +++ b/sdk/trafficmanager/azure-mgmt-trafficmanager/generated_samples/profile_get_with_traffic_view_enabled.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.trafficmanager import TrafficManagerManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-trafficmanager +# USAGE + python profile_get_with_traffic_view_enabled.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 = TrafficManagerManagementClient( + credential=DefaultAzureCredential(), + subscription_id="{subscription-id}", + ) + + response = client.profiles.get( + resource_group_name="azuresdkfornetautoresttrafficmanager1323", + profile_name="azuresdkfornetautoresttrafficmanager3880", + ) + print(response) + + +# x-ms-original-file: specification/trafficmanager/resource-manager/Microsoft.Network/preview/2022-04-01-preview/examples/Profile-GET-WithTrafficViewEnabled.json +if __name__ == "__main__": + main() diff --git a/sdk/trafficmanager/azure-mgmt-trafficmanager/generated_samples/profile_patch_monitor_config.py b/sdk/trafficmanager/azure-mgmt-trafficmanager/generated_samples/profile_patch_monitor_config.py new file mode 100644 index 000000000000..6ea4defe5011 --- /dev/null +++ b/sdk/trafficmanager/azure-mgmt-trafficmanager/generated_samples/profile_patch_monitor_config.py @@ -0,0 +1,57 @@ +# 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.trafficmanager import TrafficManagerManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-trafficmanager +# USAGE + python profile_patch_monitor_config.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 = TrafficManagerManagementClient( + credential=DefaultAzureCredential(), + subscription_id="{subscription-id}", + ) + + response = client.profiles.update( + resource_group_name="azuresdkfornetautoresttrafficmanager2583", + profile_name="azuresdkfornetautoresttrafficmanager6192", + parameters={ + "properties": { + "monitorConfig": { + "customHeaders": [ + {"name": "header-1", "value": "value-1"}, + {"name": "header-2", "value": "value-2"}, + ], + "intervalInSeconds": 30, + "path": "/testpath.aspx", + "port": 80, + "protocol": "HTTP", + "timeoutInSeconds": 6, + "toleratedNumberOfFailures": 4, + } + } + }, + ) + print(response) + + +# x-ms-original-file: specification/trafficmanager/resource-manager/Microsoft.Network/preview/2022-04-01-preview/examples/Profile-PATCH-MonitorConfig.json +if __name__ == "__main__": + main() diff --git a/sdk/trafficmanager/azure-mgmt-trafficmanager/generated_samples/profile_put_multi_value.py b/sdk/trafficmanager/azure-mgmt-trafficmanager/generated_samples/profile_put_multi_value.py new file mode 100644 index 000000000000..aa80d82584c2 --- /dev/null +++ b/sdk/trafficmanager/azure-mgmt-trafficmanager/generated_samples/profile_put_multi_value.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.trafficmanager import TrafficManagerManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-trafficmanager +# USAGE + python profile_put_multi_value.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 = TrafficManagerManagementClient( + credential=DefaultAzureCredential(), + subscription_id="{subscription-id}", + ) + + response = client.profiles.create_or_update( + resource_group_name="azuresdkfornetautoresttrafficmanager1421", + profile_name="azsmnet6386", + parameters={ + "location": "global", + "properties": { + "dnsConfig": {"relativeName": "azsmnet6386", "ttl": 35}, + "maxReturn": 2, + "monitorConfig": {"path": "/testpath.aspx", "port": 80, "protocol": "HTTP"}, + "profileStatus": "Enabled", + "trafficRoutingMethod": "MultiValue", + "trafficViewEnrollmentStatus": "Disabled", + }, + }, + ) + print(response) + + +# x-ms-original-file: specification/trafficmanager/resource-manager/Microsoft.Network/preview/2022-04-01-preview/examples/Profile-PUT-MultiValue.json +if __name__ == "__main__": + main() diff --git a/sdk/trafficmanager/azure-mgmt-trafficmanager/generated_samples/profile_put_no_endpoints.py b/sdk/trafficmanager/azure-mgmt-trafficmanager/generated_samples/profile_put_no_endpoints.py new file mode 100644 index 000000000000..f550d17a8e8e --- /dev/null +++ b/sdk/trafficmanager/azure-mgmt-trafficmanager/generated_samples/profile_put_no_endpoints.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.trafficmanager import TrafficManagerManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-trafficmanager +# USAGE + python profile_put_no_endpoints.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 = TrafficManagerManagementClient( + credential=DefaultAzureCredential(), + subscription_id="{subscription-id}", + ) + + response = client.profiles.create_or_update( + resource_group_name="azuresdkfornetautoresttrafficmanager1421", + profile_name="azsmnet6386", + parameters={ + "location": "global", + "properties": { + "dnsConfig": {"relativeName": "azsmnet6386", "ttl": 35}, + "monitorConfig": {"path": "/testpath.aspx", "port": 80, "protocol": "HTTP"}, + "profileStatus": "Enabled", + "trafficRoutingMethod": "Performance", + }, + }, + ) + print(response) + + +# x-ms-original-file: specification/trafficmanager/resource-manager/Microsoft.Network/preview/2022-04-01-preview/examples/Profile-PUT-NoEndpoints.json +if __name__ == "__main__": + main() diff --git a/sdk/trafficmanager/azure-mgmt-trafficmanager/generated_samples/profile_put_with_aliasing.py b/sdk/trafficmanager/azure-mgmt-trafficmanager/generated_samples/profile_put_with_aliasing.py new file mode 100644 index 000000000000..1959261f0ef1 --- /dev/null +++ b/sdk/trafficmanager/azure-mgmt-trafficmanager/generated_samples/profile_put_with_aliasing.py @@ -0,0 +1,69 @@ +# 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.trafficmanager import TrafficManagerManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-trafficmanager +# USAGE + python profile_put_with_aliasing.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 = TrafficManagerManagementClient( + credential=DefaultAzureCredential(), + subscription_id="{subscription-id}", + ) + + response = client.profiles.create_or_update( + resource_group_name="azuresdkfornetautoresttrafficmanager2583", + profile_name="azuresdkfornetautoresttrafficmanager6192", + parameters={ + "location": "global", + "properties": { + "allowedEndpointRecordTypes": ["DomainName"], + "dnsConfig": {"relativeName": "azuresdkfornetautoresttrafficmanager6192", "ttl": 35}, + "endpoints": [ + { + "name": "My external endpoint", + "properties": { + "endpointLocation": "North Europe", + "endpointStatus": "Enabled", + "target": "foobar.contoso.com", + }, + "type": "Microsoft.network/TrafficManagerProfiles/ExternalEndpoints", + } + ], + "monitorConfig": { + "intervalInSeconds": 10, + "path": "/testpath.aspx", + "port": 80, + "protocol": "HTTP", + "timeoutInSeconds": 5, + "toleratedNumberOfFailures": 2, + }, + "profileStatus": "Enabled", + "trafficRoutingMethod": "Performance", + }, + }, + ) + print(response) + + +# x-ms-original-file: specification/trafficmanager/resource-manager/Microsoft.Network/preview/2022-04-01-preview/examples/Profile-PUT-WithAliasing.json +if __name__ == "__main__": + main() diff --git a/sdk/trafficmanager/azure-mgmt-trafficmanager/generated_samples/profile_put_with_custom_headers.py b/sdk/trafficmanager/azure-mgmt-trafficmanager/generated_samples/profile_put_with_custom_headers.py new file mode 100644 index 000000000000..138d7de3ccea --- /dev/null +++ b/sdk/trafficmanager/azure-mgmt-trafficmanager/generated_samples/profile_put_with_custom_headers.py @@ -0,0 +1,75 @@ +# 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.trafficmanager import TrafficManagerManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-trafficmanager +# USAGE + python profile_put_with_custom_headers.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 = TrafficManagerManagementClient( + credential=DefaultAzureCredential(), + subscription_id="{subscription-id}", + ) + + response = client.profiles.create_or_update( + resource_group_name="azuresdkfornetautoresttrafficmanager2583", + profile_name="azuresdkfornetautoresttrafficmanager6192", + parameters={ + "location": "global", + "properties": { + "dnsConfig": {"relativeName": "azuresdkfornetautoresttrafficmanager6192", "ttl": 35}, + "endpoints": [ + { + "name": "My external endpoint", + "properties": { + "customHeaders": [{"name": "header-2", "value": "value-2-overridden"}], + "endpointLocation": "North Europe", + "endpointStatus": "Enabled", + "target": "foobar.contoso.com", + }, + "type": "Microsoft.network/TrafficManagerProfiles/ExternalEndpoints", + } + ], + "monitorConfig": { + "customHeaders": [ + {"name": "header-1", "value": "value-1"}, + {"name": "header-2", "value": "value-2"}, + ], + "expectedStatusCodeRanges": [{"max": 205, "min": 200}, {"max": 410, "min": 400}], + "intervalInSeconds": 10, + "path": "/testpath.aspx", + "port": 80, + "protocol": "HTTP", + "timeoutInSeconds": 5, + "toleratedNumberOfFailures": 2, + }, + "profileStatus": "Enabled", + "trafficRoutingMethod": "Performance", + "trafficViewEnrollmentStatus": "Disabled", + }, + }, + ) + print(response) + + +# x-ms-original-file: specification/trafficmanager/resource-manager/Microsoft.Network/preview/2022-04-01-preview/examples/Profile-PUT-WithCustomHeaders.json +if __name__ == "__main__": + main() diff --git a/sdk/trafficmanager/azure-mgmt-trafficmanager/generated_samples/profile_put_with_endpoints.py b/sdk/trafficmanager/azure-mgmt-trafficmanager/generated_samples/profile_put_with_endpoints.py new file mode 100644 index 000000000000..e28a48f00434 --- /dev/null +++ b/sdk/trafficmanager/azure-mgmt-trafficmanager/generated_samples/profile_put_with_endpoints.py @@ -0,0 +1,68 @@ +# 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.trafficmanager import TrafficManagerManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-trafficmanager +# USAGE + python profile_put_with_endpoints.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 = TrafficManagerManagementClient( + credential=DefaultAzureCredential(), + subscription_id="{subscription-id}", + ) + + response = client.profiles.create_or_update( + resource_group_name="azuresdkfornetautoresttrafficmanager2583", + profile_name="azuresdkfornetautoresttrafficmanager6192", + parameters={ + "location": "global", + "properties": { + "dnsConfig": {"relativeName": "azuresdkfornetautoresttrafficmanager6192", "ttl": 35}, + "endpoints": [ + { + "name": "My external endpoint", + "properties": { + "endpointLocation": "North Europe", + "endpointStatus": "Enabled", + "target": "foobar.contoso.com", + }, + "type": "Microsoft.network/TrafficManagerProfiles/ExternalEndpoints", + } + ], + "monitorConfig": { + "intervalInSeconds": 10, + "path": "/testpath.aspx", + "port": 80, + "protocol": "HTTP", + "timeoutInSeconds": 5, + "toleratedNumberOfFailures": 2, + }, + "profileStatus": "Enabled", + "trafficRoutingMethod": "Performance", + }, + }, + ) + print(response) + + +# x-ms-original-file: specification/trafficmanager/resource-manager/Microsoft.Network/preview/2022-04-01-preview/examples/Profile-PUT-WithEndpoints.json +if __name__ == "__main__": + main() diff --git a/sdk/trafficmanager/azure-mgmt-trafficmanager/generated_samples/profile_put_with_nested_endpoints.py b/sdk/trafficmanager/azure-mgmt-trafficmanager/generated_samples/profile_put_with_nested_endpoints.py new file mode 100644 index 000000000000..ced504b8429a --- /dev/null +++ b/sdk/trafficmanager/azure-mgmt-trafficmanager/generated_samples/profile_put_with_nested_endpoints.py @@ -0,0 +1,85 @@ +# 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.trafficmanager import TrafficManagerManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-trafficmanager +# USAGE + python profile_put_with_nested_endpoints.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 = TrafficManagerManagementClient( + credential=DefaultAzureCredential(), + subscription_id="{subscription-id}", + ) + + response = client.profiles.create_or_update( + resource_group_name="myresourcegroup", + profile_name="parentprofile", + parameters={ + "location": "global", + "properties": { + "dnsConfig": {"relativeName": "parentprofile", "ttl": 35}, + "endpoints": [ + { + "name": "MyFirstNestedEndpoint", + "properties": { + "endpointStatus": "Enabled", + "minChildEndpoints": 2, + "minChildEndpointsIPv4": 1, + "minChildEndpointsIPv6": 2, + "priority": 1, + "target": "firstnestedprofile.tmpreview.watmtest.azure-test.net", + "weight": 1, + }, + "type": "Microsoft.Network/trafficManagerProfiles/nestedEndpoints", + }, + { + "name": "MySecondNestedEndpoint", + "properties": { + "endpointStatus": "Enabled", + "minChildEndpoints": 2, + "minChildEndpointsIPv4": 2, + "minChildEndpointsIPv6": 1, + "priority": 2, + "target": "secondnestedprofile.tmpreview.watmtest.azure-test.net", + "weight": 1, + }, + "type": "Microsoft.Network/trafficManagerProfiles/nestedEndpoints", + }, + ], + "monitorConfig": { + "intervalInSeconds": 10, + "path": "/testpath.aspx", + "port": 80, + "protocol": "HTTP", + "timeoutInSeconds": 5, + "toleratedNumberOfFailures": 2, + }, + "profileStatus": "Enabled", + "trafficRoutingMethod": "Priority", + }, + }, + ) + print(response) + + +# x-ms-original-file: specification/trafficmanager/resource-manager/Microsoft.Network/preview/2022-04-01-preview/examples/Profile-PUT-WithNestedEndpoints.json +if __name__ == "__main__": + main() diff --git a/sdk/trafficmanager/azure-mgmt-trafficmanager/generated_samples/traffic_manager_user_metrics_keys_delete.py b/sdk/trafficmanager/azure-mgmt-trafficmanager/generated_samples/traffic_manager_user_metrics_keys_delete.py new file mode 100644 index 000000000000..15fea7470b6f --- /dev/null +++ b/sdk/trafficmanager/azure-mgmt-trafficmanager/generated_samples/traffic_manager_user_metrics_keys_delete.py @@ -0,0 +1,38 @@ +# 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.trafficmanager import TrafficManagerManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-trafficmanager +# USAGE + python traffic_manager_user_metrics_keys_delete.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = TrafficManagerManagementClient( + credential=DefaultAzureCredential(), + subscription_id="{subscription-id}", + ) + + response = client.traffic_manager_user_metrics_keys.delete() + print(response) + + +# x-ms-original-file: specification/trafficmanager/resource-manager/Microsoft.Network/preview/2022-04-01-preview/examples/TrafficManagerUserMetricsKeys-DELETE.json +if __name__ == "__main__": + main() diff --git a/sdk/trafficmanager/azure-mgmt-trafficmanager/generated_samples/traffic_manager_user_metrics_keys_get.py b/sdk/trafficmanager/azure-mgmt-trafficmanager/generated_samples/traffic_manager_user_metrics_keys_get.py new file mode 100644 index 000000000000..dbfb4dc604ef --- /dev/null +++ b/sdk/trafficmanager/azure-mgmt-trafficmanager/generated_samples/traffic_manager_user_metrics_keys_get.py @@ -0,0 +1,38 @@ +# 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.trafficmanager import TrafficManagerManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-trafficmanager +# USAGE + python traffic_manager_user_metrics_keys_get.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = TrafficManagerManagementClient( + credential=DefaultAzureCredential(), + subscription_id="{subscription-id}", + ) + + response = client.traffic_manager_user_metrics_keys.get() + print(response) + + +# x-ms-original-file: specification/trafficmanager/resource-manager/Microsoft.Network/preview/2022-04-01-preview/examples/TrafficManagerUserMetricsKeys-GET.json +if __name__ == "__main__": + main() diff --git a/sdk/trafficmanager/azure-mgmt-trafficmanager/generated_samples/traffic_manager_user_metrics_keys_put.py b/sdk/trafficmanager/azure-mgmt-trafficmanager/generated_samples/traffic_manager_user_metrics_keys_put.py new file mode 100644 index 000000000000..ecd321c26027 --- /dev/null +++ b/sdk/trafficmanager/azure-mgmt-trafficmanager/generated_samples/traffic_manager_user_metrics_keys_put.py @@ -0,0 +1,38 @@ +# 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.trafficmanager import TrafficManagerManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-trafficmanager +# USAGE + python traffic_manager_user_metrics_keys_put.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 = TrafficManagerManagementClient( + credential=DefaultAzureCredential(), + subscription_id="{subscription-id}", + ) + + response = client.traffic_manager_user_metrics_keys.create_or_update() + print(response) + + +# x-ms-original-file: specification/trafficmanager/resource-manager/Microsoft.Network/preview/2022-04-01-preview/examples/TrafficManagerUserMetricsKeys-PUT.json +if __name__ == "__main__": + main()